answer
stringlengths
17
10.2M
package os.running.leaderboard.app; import android.annotation.TargetApi; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.squareup.picasso.Picasso; import de.hdodenhof.circleimageview.CircleImageView; import os.running.leaderboard.app.base.Database; import os.running.leaderboard.app.base.Runtastic; import os.running.leaderboard.app.fragment.Friends; import os.running.leaderboard.app.fragment.LeaderBoard; import os.running.leaderboard.app.fragment.LiveSessions; import os.running.leaderboard.app.util.Navigation; public class Main extends AppCompatActivity { private DrawerLayout drawerLayout; public static AppCompatActivity activity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Main.activity = this; // Initializing Toolbar and setting it as the actionbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Setting Navigation Item Listener to handle the item click of the navigation menu NavigationView navigation = (NavigationView)findViewById(R.id.navigation); navigation.setNavigationItemSelectedListener(new NavigationItemListener()); // Initializing Drawer Layout and ActionBarToggle drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ); actionBarDrawerToggle.syncState(); drawerLayout.setDrawerListener(actionBarDrawerToggle); updateNavigationHeader(); // Initializing default fragment Navigation.from(activity).to(LeaderBoard.class.getName()); FragmentManager fm = getSupportFragmentManager(); fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { if (drawerLayout.isDrawerOpen(Gravity.LEFT)) { drawerLayout.closeDrawers(); } else { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { finish(); } } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { // update navigation header updateNavigationHeader(false); } } private void updateNavigationHeader() { updateNavigationHeader(true); } private void updateNavigationHeader(Boolean withLogin) { // update navigation header final Runtastic runtastic = new Runtastic(this); if (runtastic.hasLogin()) { /*new Thread(new Runnable() { public void run() { // get session with automatic login runtastic.login(true); } }).start();*/ Database DB = Database.getInstance(this); String accountData = DB.getAccountData("firstName"); if (accountData != null) { ((TextView)this.findViewById(R.id.username)).setText(accountData); } accountData = DB.getAccountData("avatarUrl"); if (accountData != null) { CircleImageView image = (CircleImageView)this.findViewById(R.id.profile_image); Picasso.with(this).load(accountData).placeholder(R.drawable.default_profile).into(image); } } else { TextView text = (TextView)this.findViewById(R.id.username); text.setText(R.string.default_login); text.setClickable(true); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(view.getContext(), Login.class); startActivityForResult(intent, 1); } }); ((CircleImageView)this.findViewById(R.id.profile_image)).setImageResource(R.drawable.default_profile); if (withLogin) { Intent intent = new Intent(this, Login.class); startActivityForResult(intent, 1); } } } private class NavigationItemListener implements NavigationView.OnNavigationItemSelectedListener { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // Checking if the item is in checked state or not, if not make it in checked state if (menuItem.isChecked()) { menuItem.setChecked(false); } else { menuItem.setChecked(true); } // Closing drawer on item click drawerLayout.closeDrawers(); // Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { // Replacing the main content with ContentFragment Which is our Inbox View; case R.id.menu_leader_board: Navigation.from(activity).replace(LeaderBoard.class.getName()); return true; case R.id.menu_sessions: Navigation.from(activity).replace(LiveSessions.class.getName()); return true; case R.id.menu_friends: Navigation.from(activity).replace(Friends.class.getName()); return true; case R.id.menu_runtastic_apps: Uri appUrl = Uri.parse("https://play.google.com/store/apps/dev?id=8438666261259599516"); Intent appsIntent = new Intent(Intent.ACTION_VIEW, appUrl); if (appsIntent.resolveActivity(getPackageManager()) != null) { startActivity(appsIntent); } return true; case R.id.menu_runtastic_url: Uri pageUrl = Uri.parse("http: Intent pageIntent = new Intent(Intent.ACTION_VIEW, pageUrl); if (pageIntent.resolveActivity(getPackageManager()) != null) { startActivity(pageIntent); } return true; /*case R.id.menu_settings: // default output TODO add a settings view Toast.makeText(getApplicationContext(), "Coming soon ...", Toast.LENGTH_LONG).show(); return true;*/ default: return true; } } } @Override @TargetApi(9) public void onBackPressed() { if (drawerLayout.isDrawerOpen(Gravity.LEFT)) { drawerLayout.closeDrawers(); } else { getSupportFragmentManager().popBackStack(); } } }
package pitt.search.semanticvectors; import org.apache.lucene.document.Document; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.PermutationUtils; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.logging.Logger; /** * Generates predication vectors incrementally.Requires as input an index containing * documents with the fields "subject", "predicate" and "object" * * Produces as output the files: elementalvectors.bin, predicatevectors.bin and semanticvectors.bin * * @author Trevor Cohen, Dominic Widdows */ public class PSI { private static final Logger logger = Logger.getLogger(PSI.class.getCanonicalName()); private FlagConfig flagConfig; private VectorStore elementalItemVectors, elementalPredicateVectors; private VectorStoreRAM semanticItemVectors, semanticPredicateVectors; private static final String SUBJECT_FIELD = "subject"; private static final String PREDICATE_FIELD = "predicate"; private static final String OBJECT_FIELD = "object"; private static final String PREDICATION_FIELD = "predication"; private String[] itemFields = {SUBJECT_FIELD, OBJECT_FIELD}; private LuceneUtils luceneUtils; private int[] predicatePermutation; private PSI(FlagConfig flagConfig) { predicatePermutation = PermutationUtils.getShiftPermutation(flagConfig.vectortype(), flagConfig.dimension(), 1); }; /** * Creates PSI vectors incrementally, using the fields "subject" and "object" from a Lucene index. */ public static void createIncrementalPSIVectors(FlagConfig flagConfig) throws IOException { PSI incrementalPSIVectors = new PSI(flagConfig); incrementalPSIVectors.flagConfig = flagConfig; incrementalPSIVectors.initialize(); VectorStoreWriter.writeVectors( flagConfig.elementalvectorfile(), flagConfig, incrementalPSIVectors.elementalItemVectors); VectorStoreWriter.writeVectors( flagConfig.elementalpredicatevectorfile(), flagConfig, incrementalPSIVectors.elementalPredicateVectors); VerbatimLogger.info("Performing first round of PSI training ..."); incrementalPSIVectors.trainIncrementalPSIVectors(""); VerbatimLogger.info("Performing next round of PSI training ..."); incrementalPSIVectors.elementalItemVectors = incrementalPSIVectors.semanticItemVectors; incrementalPSIVectors.elementalPredicateVectors = incrementalPSIVectors.semanticPredicateVectors; incrementalPSIVectors.trainIncrementalPSIVectors("1"); VerbatimLogger.info("Done with createIncrementalPSIVectors."); } /** * Creates elemental and semantic vectors for each concept, and elemental vectors for predicates. * * @throws IOException */ private void initialize() throws IOException { if (this.luceneUtils == null) { this.luceneUtils = new LuceneUtils(flagConfig); } elementalItemVectors = new ElementalVectorStore(flagConfig); semanticItemVectors = new VectorStoreRAM(flagConfig); elementalPredicateVectors = new ElementalVectorStore(flagConfig); semanticPredicateVectors = new VectorStoreRAM(flagConfig); flagConfig.setContentsfields(itemFields); HashSet<String> addedConcepts = new HashSet<String>(); for (String fieldName : itemFields) { Terms terms = luceneUtils.getTermsForField(fieldName); if (terms == null) { throw new NullPointerException(String.format( "No terms for field '%s'. Please check that index at '%s' was built correctly for use with PSI.", fieldName, flagConfig.luceneindexpath())); } TermsEnum termsEnum = terms.iterator(null); BytesRef bytes; while((bytes = termsEnum.next()) != null) { Term term = new Term(fieldName, bytes); if (!luceneUtils.termFilter(term)) { VerbatimLogger.fine("Filtering out term: " + term + "\n"); continue; } if (!addedConcepts.contains(term.text())) { addedConcepts.add(term.text()); elementalItemVectors.getVector(term.text()); // Causes vector to be created. semanticItemVectors.putVector(term.text(), VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension())); } } } // Now elemental vectors for the predicate field. Terms predicateTerms = luceneUtils.getTermsForField(PREDICATE_FIELD); String[] dummyArray = new String[] { PREDICATE_FIELD }; // To satisfy LuceneUtils.termFilter interface. TermsEnum termsEnum = predicateTerms.iterator(null); BytesRef bytes; while((bytes = termsEnum.next()) != null) { Term term = new Term(PREDICATE_FIELD, bytes); // frequency thresholds do not apply to predicates... but the stopword list does if (!luceneUtils.termFilter(term, dummyArray, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, 1)) { continue; } elementalPredicateVectors.getVector(term.text().trim()); semanticPredicateVectors.putVector(term.text().trim(), VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension())); // Add inverse vector for the predicates. elementalPredicateVectors.getVector(term.text().trim() + "-INV"); semanticPredicateVectors.putVector(term.text().trim() + "-INV", VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension())); } } /** * Performs training by iterating over predications. Assumes that elemental vector stores are populated. * * @throws IOException */ private void trainIncrementalPSIVectors(String iterationTag) throws IOException { String fieldName = PREDICATION_FIELD; // Iterate through documents (each document = one predication). Terms allTerms = luceneUtils.getTermsForField(fieldName); TermsEnum termsEnum = allTerms.iterator(null); BytesRef bytes; while((bytes = termsEnum.next()) != null) { int pc = 0; Term term = new Term(fieldName, bytes); pc++; // Output progress counter. if ((pc > 0) && ((pc % 10000 == 0) || ( pc < 10000 && pc % 1000 == 0 ))) { VerbatimLogger.info("Processed " + pc + " unique predications ... "); } DocsEnum termDocs = luceneUtils.getDocsForTerm(term); termDocs.nextDoc(); Document document = luceneUtils.getDoc(termDocs.docID()); String subject = document.get(SUBJECT_FIELD); String predicate = document.get(PREDICATE_FIELD); String object = document.get(OBJECT_FIELD); if (!(elementalItemVectors.containsVector(object) && elementalItemVectors.containsVector(subject) && elementalPredicateVectors.containsVector(predicate))) { logger.info("skipping predication " + subject + " " + predicate + " " + object); continue; } float sWeight = 1; float oWeight = 1; float pWeight = 1; sWeight = luceneUtils.getGlobalTermWeight(new Term(SUBJECT_FIELD, subject)); oWeight = luceneUtils.getGlobalTermWeight(new Term(OBJECT_FIELD, object)); // TODO: Explain different weighting for predicates, log(occurrences of predication) pWeight = luceneUtils.getLocalTermWeight(luceneUtils.getGlobalTermFreq(term)); Vector subjectSemanticVector = semanticItemVectors.getVector(subject); Vector objectSemanticVector = semanticItemVectors.getVector(object); Vector subjectElementalVector = elementalItemVectors.getVector(subject); Vector objectElementalVector = elementalItemVectors.getVector(object); Vector predicateElementalVector = elementalPredicateVectors.getVector(predicate); Vector predicateElementalVectorInv = elementalPredicateVectors.getVector(predicate + "-INV"); Vector predicateSemanticVector = semanticPredicateVectors.getVector(predicate); Vector predicateSemanticVectorInv = semanticPredicateVectors.getVector(predicate+ "-INV"); //construct permuted editions of subject and object vectors (so binding doesn't commute) Vector permutedSubjectElementalVector = VectorFactory.createZeroVector(flagConfig.vectortype(), flagConfig.dimension()); Vector permutedObjectElementalVector = VectorFactory.createZeroVector(flagConfig.vectortype(), flagConfig.dimension()); permutedSubjectElementalVector.superpose(subjectElementalVector, 1, predicatePermutation); permutedObjectElementalVector.superpose(objectElementalVector, 1, predicatePermutation); permutedSubjectElementalVector.normalize(); permutedObjectElementalVector.normalize(); Vector objToAdd = objectElementalVector.copy(); objToAdd.bind(predicateElementalVector); subjectSemanticVector.superpose(objToAdd, pWeight * oWeight, null); Vector subjToAdd = subjectElementalVector.copy(); subjToAdd.bind(predicateElementalVectorInv); objectSemanticVector.superpose(subjToAdd, pWeight * sWeight, null); Vector predToAdd = subjectElementalVector.copy(); predToAdd.bind(permutedObjectElementalVector); predicateSemanticVector.superpose(predToAdd, sWeight * oWeight, null); Vector predToAddInv = objectElementalVector.copy(); predToAddInv.bind(permutedSubjectElementalVector); predicateSemanticVectorInv.superpose(predToAddInv, oWeight * sWeight, null); } // Finish iterating through predications. // Normalize semantic vectors and write out. Enumeration<ObjectVector> e = semanticItemVectors.getAllVectors(); while (e.hasMoreElements()) { e.nextElement().getVector().normalize(); } e = semanticPredicateVectors.getAllVectors(); while (e.hasMoreElements()) { e.nextElement().getVector().normalize(); } VectorStoreWriter.writeVectors( flagConfig.semanticvectorfile() + iterationTag, flagConfig, semanticItemVectors); VectorStoreWriter.writeVectors( flagConfig.semanticpredicatevectorfile() + iterationTag, flagConfig, semanticPredicateVectors); VerbatimLogger.info("Finished writing this round of semantic item and predicate vectors.\n"); } /** * Main method for building PSI indexes. */ public static void main(String[] args) throws IllegalArgumentException, IOException { FlagConfig flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; if (flagConfig.luceneindexpath().isEmpty()) { throw (new IllegalArgumentException("-luceneindexpath argument must be provided.")); } VerbatimLogger.info("Building PSI model from index in: " + flagConfig.luceneindexpath() + "\n"); VerbatimLogger.info("Minimum frequency = " + flagConfig.minfrequency() + "\n"); VerbatimLogger.info("Maximum frequency = " + flagConfig.maxfrequency() + "\n"); VerbatimLogger.info("Number non-alphabet characters = " + flagConfig.maxnonalphabetchars() + "\n"); createIncrementalPSIVectors(flagConfig); } }
package pro.extsoft.comments.tests; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; abstract class Base { WebDriver driver; @BeforeTest public void setUp() throws MalformedURLException { driver = new RemoteWebDriver(new URL("http://localhost:9515"), DesiredCapabilities.chrome()); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); } @AfterTest public void tearDown() { driver.close(); } }
package quadrum.block; import java.util.ArrayList; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import quadrum.block.data.BlockData; import quadrum.lib.BlockStaticMethodHandler; import quadrum.lib.IQuadrumObject; import quadrum.util.Utils; public class BlockQuadrumFence extends BlockFence implements IQuadrumObject { private final BlockData blockData; IIcon icon; public BlockQuadrumFence(BlockData blockData) { super("", blockData.getBlockMaterial()); this.blockData = blockData; setStepSound(blockData.getBlockSound()); setHardness(blockData.hardness); setResistance(blockData.resistance); setBlockName(blockData.name); setCreativeTab(blockData.getCreativeTab()); if (blockData.requiresTool) setHarvestLevel(blockData.getHarvestTool(), blockData.miningLevel); } @Override @SideOnly(Side.CLIENT) public int getRenderBlockPass() { return blockData.transparent ? 1 : 0; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister register) { icon = register.registerIcon(Utils.getIconForRegister(blockData.defaultTexture)); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return icon; } @Override public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) { return BlockStaticMethodHandler.getDrops(this, blockData, world, x, y, z, metadata, fortune); } @Override public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { return blockData.collision ? super.getCollisionBoundingBoxFromPool(world, x, y, z) : null; } @Override public boolean canConnectFenceTo(IBlockAccess world, int x, int y, int z) { Block neighbour = world.getBlock(x, y, z); return neighbour instanceof BlockFence || neighbour instanceof BlockFenceGate || (neighbour.isOpaqueCube() && neighbour.renderAsNormalBlock()); } @Override public BlockData get() { return blockData; } }
package redis.clients.jedis; import java.io.Serializable; public class HostAndPort implements Serializable { private static final long serialVersionUID = -519876229978427751L; public static final String LOCALHOST_STR = "localhost"; private String host; private int port; public HostAndPort(String host, int port) { this.host = host; this.port = port; } public String getHost() { return host; } public int getPort() { return port; } @Override public boolean equals(Object obj) { if (obj instanceof HostAndPort) { HostAndPort hp = (HostAndPort) obj; String thisHost = convertHost(host); String hpHost = convertHost(hp.host); return port == hp.port && thisHost.equals(hpHost); } return false; } @Override public int hashCode() { return 31 * convertHost(host).hashCode() + port; } @Override public String toString() { return host + ":" + port; } private String convertHost(String host) { if (host.equals("127.0.0.1")) return LOCALHOST_STR; else if (host.equals("::1")) return LOCALHOST_STR; return host; } }
package refinedstorage.tile; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.datasync.DataSerializers; import net.minecraftforge.items.ItemHandlerHelper; import refinedstorage.RS; import refinedstorage.RSBlocks; import refinedstorage.RSUtils; import refinedstorage.api.network.INetworkMaster; import refinedstorage.api.storage.AccessType; import refinedstorage.api.storage.item.IItemStorage; import refinedstorage.api.storage.item.IItemStorageProvider; import refinedstorage.api.util.IComparer; import refinedstorage.apiimpl.storage.item.ItemStorageNBT; import refinedstorage.block.BlockStorage; import refinedstorage.block.EnumItemStorageType; import refinedstorage.inventory.ItemHandlerBasic; import refinedstorage.tile.config.*; import refinedstorage.tile.data.ITileDataProducer; import refinedstorage.tile.data.TileDataParameter; import java.util.List; public class TileStorage extends TileNode implements IItemStorageProvider, IStorageGui, IComparable, IFilterable, IPrioritizable, IExcessVoidable, IAccessType { public static final TileDataParameter<Integer> PRIORITY = IPrioritizable.createParameter(); public static final TileDataParameter<Integer> COMPARE = IComparable.createParameter(); public static final TileDataParameter<Integer> MODE = IFilterable.createParameter(); public static final TileDataParameter<AccessType> ACCESS_TYPE = IAccessType.createParameter(); public static final TileDataParameter<Integer> STORED = new TileDataParameter<>(DataSerializers.VARINT, 0, new ITileDataProducer<Integer, TileStorage>() { @Override public Integer getValue(TileStorage tile) { return ItemStorageNBT.getStoredFromNBT(tile.storageTag); } }); public static final TileDataParameter<Boolean> VOID_EXCESS = IExcessVoidable.createParameter(); class ItemStorage extends ItemStorageNBT { public ItemStorage() { super(TileStorage.this.getStorageTag(), TileStorage.this.getCapacity(), TileStorage.this); } @Override public int getPriority() { return priority; } @Override public ItemStack insertItem(ItemStack stack, int size, boolean simulate) { if (!IFilterable.canTake(filters, mode, compare, stack)) { return ItemHandlerHelper.copyStackWithSize(stack, size); } ItemStack result = super.insertItem(stack, size, simulate); if (voidExcess && result != null) { // Simulate should not matter as the items are voided anyway result.stackSize = -result.stackSize; } return result; } @Override public AccessType getAccessType() { return accessType; } } public static final String NBT_STORAGE = "Storage"; private static final String NBT_PRIORITY = "Priority"; private static final String NBT_COMPARE = "Compare"; private static final String NBT_MODE = "Mode"; private static final String NBT_VOID_EXCESS = "VoidExcess"; private ItemHandlerBasic filters = new ItemHandlerBasic(9, this); private NBTTagCompound storageTag = ItemStorageNBT.createNBT(); private ItemStorage storage; private EnumItemStorageType type; private AccessType accessType = AccessType.READ_WRITE; private int priority = 0; private int compare = IComparer.COMPARE_NBT | IComparer.COMPARE_DAMAGE; private int mode = IFilterable.WHITELIST; private boolean voidExcess = false; public TileStorage() { dataManager.addWatchedParameter(PRIORITY); dataManager.addWatchedParameter(COMPARE); dataManager.addWatchedParameter(MODE); dataManager.addWatchedParameter(STORED); dataManager.addWatchedParameter(VOID_EXCESS); dataManager.addWatchedParameter(ACCESS_TYPE); } @Override public int getEnergyUsage() { return RS.INSTANCE.config.storageUsage; } @Override public void updateNode() { } @Override public void update() { super.update(); if (storage == null && storageTag != null) { storage = new ItemStorage(); if (network != null) { network.getItemStorageCache().invalidate(); } } } public void onBreak() { if (storage != null) { storage.writeToNBT(); } } @Override public void onConnectionChange(INetworkMaster network, boolean state) { super.onConnectionChange(network, state); network.getItemStorageCache().invalidate(); } @Override public void addItemStorages(List<IItemStorage> storages) { if (storage != null) { storages.add(storage); } } @Override public void read(NBTTagCompound tag) { super.read(tag); RSUtils.readItems(filters, 0, tag); if (tag.hasKey(NBT_PRIORITY)) { priority = tag.getInteger(NBT_PRIORITY); } if (tag.hasKey(NBT_STORAGE)) { storageTag = tag.getCompoundTag(NBT_STORAGE); } if (tag.hasKey(NBT_COMPARE)) { compare = tag.getInteger(NBT_COMPARE); } if (tag.hasKey(NBT_MODE)) { mode = tag.getInteger(NBT_MODE); } if (tag.hasKey(NBT_VOID_EXCESS)) { voidExcess = tag.getBoolean(NBT_VOID_EXCESS); } accessType = RSUtils.readAccessType(tag); } @Override public NBTTagCompound write(NBTTagCompound tag) { super.write(tag); RSUtils.writeItems(filters, 0, tag); tag.setInteger(NBT_PRIORITY, priority); if (storage != null) { storage.writeToNBT(); } tag.setTag(NBT_STORAGE, storageTag); tag.setInteger(NBT_COMPARE, compare); tag.setInteger(NBT_MODE, mode); tag.setBoolean(NBT_VOID_EXCESS, voidExcess); RSUtils.writeAccessType(tag, accessType); return tag; } public EnumItemStorageType getType() { if (type == null && worldObj.getBlockState(pos).getBlock() == RSBlocks.STORAGE) { this.type = ((EnumItemStorageType) worldObj.getBlockState(pos).getValue(BlockStorage.TYPE)); } return type == null ? EnumItemStorageType.TYPE_1K : type; } @Override public int getCompare() { return compare; } @Override public void setCompare(int compare) { this.compare = compare; markDirty(); } @Override public int getMode() { return mode; } @Override public void setMode(int mode) { this.mode = mode; markDirty(); } @Override public boolean getVoidExcess() { return voidExcess; } @Override public void setVoidExcess(boolean voidExcess) { this.voidExcess = voidExcess; markDirty(); } @Override public String getGuiTitle() { return "block.refinedstorage:storage." + getType().getId() + ".name"; } @Override public TileDataParameter<Integer> getTypeParameter() { return null; } @Override public TileDataParameter<Integer> getRedstoneModeParameter() { return REDSTONE_MODE; } @Override public TileDataParameter<Integer> getCompareParameter() { return COMPARE; } @Override public TileDataParameter<Integer> getFilterParameter() { return MODE; } @Override public TileDataParameter<Integer> getPriorityParameter() { return PRIORITY; } @Override public TileDataParameter<Boolean> getVoidExcessParameter() { return VOID_EXCESS; } @Override public TileDataParameter<AccessType> getAccessTypeParameter() { return ACCESS_TYPE; } @Override public String getVoidExcessType() { return "items"; } public NBTTagCompound getStorageTag() { return storageTag; } public void setStorageTag(NBTTagCompound storageTag) { this.storageTag = storageTag; } public ItemStorageNBT getStorage() { return storage; } public ItemHandlerBasic getFilters() { return filters; } @Override public AccessType getAccessType() { return accessType; } @Override public void setAccessType(AccessType value) { this.accessType = value; if (network != null) { network.getItemStorageCache().invalidate(); } markDirty(); } @Override public int getPriority() { return priority; } @Override public void setPriority(int priority) { this.priority = priority; markDirty(); } @Override public int getStored() { return STORED.getValue(); } @Override public int getCapacity() { return getType().getCapacity(); } }
package ru.serce.jnrfuse; import jnr.ffi.LibraryLoader; import jnr.ffi.Pointer; import jnr.ffi.Runtime; import jnr.ffi.Struct; import jnr.ffi.mapper.FromNativeConverter; import jnr.ffi.provider.jffi.ClosureHelper; import jnr.posix.util.Platform; import ru.serce.jnrfuse.struct.*; import ru.serce.jnrfuse.utils.MountUtils; import ru.serce.jnrfuse.utils.WinPathUtils; import ru.serce.jnrfuse.utils.SecurityUtils; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; public abstract class AbstractFuseFS implements FuseFS { private static final int TIMEOUT = 2000; private static final String[] osxFuseLibraries = {"fuse4x", "osxfuse", "macfuse", "fuse"}; private Set<String> notImplementedMethods; protected final LibFuse libFuse; protected final FuseOperations fuseOperations; protected final AtomicBoolean mounted = new AtomicBoolean(); protected Path mountPoint; private volatile Pointer fusePointer; public AbstractFuseFS() { LibraryLoader<LibFuse> loader = LibraryLoader.create(LibFuse.class).failImmediately(); jnr.ffi.Platform p = jnr.ffi.Platform.getNativePlatform(); LibFuse libFuse = null; switch (p.getOS()) { case LINUX: libFuse = loader.load("libfuse.so.2"); break; case DARWIN: for (String library : osxFuseLibraries) { try { // Regular FUSE-compatible fuse library libFuse = LibraryLoader.create(LibFuse.class).failImmediately().load(library); break; } catch (Throwable e) { // Carry on } } if (libFuse == null) { // Everything failed. Do a last-ditch attempt. // Worst-case scenario, this causes an exception // which will be more meaningful to the user than a NullPointerException on libFuse. libFuse = LibraryLoader.create(LibFuse.class).failImmediately().load("fuse"); } break; case WINDOWS: String winFspPath = WinPathUtils.getWinFspPath(); libFuse = loader.load(winFspPath); break; default: // try fuse try { // assume linux libFuse = LibraryLoader.create(LibFuse.class).failImmediately().load("libfuse.so.2"); } catch (Throwable e) { libFuse = LibraryLoader.create(LibFuse.class).failImmediately().load("fuse"); } } this.libFuse = libFuse; Runtime runtime = Runtime.getSystemRuntime(); fuseOperations = new FuseOperations(runtime); init(fuseOperations); } public FuseContext getContext() { return libFuse.fuse_get_context(); } private void init(FuseOperations fuseOperations) { notImplementedMethods = Arrays.stream(getClass().getMethods()) .filter(method -> method.getAnnotation(NotImplemented.class) != null) .map(Method::getName) .collect(Collectors.toSet()); AbstractFuseFS fuse = this; if (isImplemented("getattr")) { fuseOperations.getattr.set((path, stbuf) -> fuse.getattr(path, FileStat.of(stbuf))); } if (isImplemented("readlink")) { fuseOperations.readlink.set(fuse::readlink); } if (isImplemented("mknod")) { fuseOperations.mknod.set(fuse::mknod); } if (isImplemented("mkdir")) { fuseOperations.mkdir.set(fuse::mkdir); } if (isImplemented("unlink")) { fuseOperations.unlink.set(fuse::unlink); } if (isImplemented("rmdir")) { fuseOperations.rmdir.set(fuse::rmdir); } if (isImplemented("symlink")) { fuseOperations.symlink.set(fuse::symlink); } if (isImplemented("rename")) { fuseOperations.rename.set(fuse::rename); } if (isImplemented("link")) { fuseOperations.link.set(fuse::link); } if (isImplemented("chmod")) { fuseOperations.chmod.set(fuse::chmod); } if (isImplemented("chown")) { fuseOperations.chown.set(fuse::chown); } if (isImplemented("truncate")) { fuseOperations.truncate.set(fuse::truncate); } if (isImplemented("open")) { fuseOperations.open.set((path, fi) -> fuse.open(path, FuseFileInfo.of(fi))); } if (isImplemented("read")) { fuseOperations.read.set((path, buf, size, offset, fi) -> fuse.read(path, buf, size, offset, FuseFileInfo.of(fi))); } if (isImplemented("write")) { fuseOperations.write.set((path, buf, size, offset, fi) -> fuse.write(path, buf, size, offset, FuseFileInfo.of(fi))); } if (isImplemented("statfs")) { fuseOperations.statfs.set((path, stbuf) -> fuse.statfs(path, Statvfs.of(stbuf))); } if (isImplemented("flush")) { fuseOperations.flush.set((path, fi) -> fuse.flush(path, FuseFileInfo.of(fi))); } if (isImplemented("release")) { fuseOperations.release.set((path, fi) -> fuse.release(path, FuseFileInfo.of(fi))); } if (isImplemented("fsync")) { fuseOperations.fsync.set((path, isdatasync, fi) -> fuse.fsync(path, isdatasync, FuseFileInfo.of(fi))); } if (isImplemented("setxattr")) { fuseOperations.setxattr.set(fuse::setxattr); } if (isImplemented("getxattr")) { fuseOperations.getxattr.set(fuse::getxattr); } if (isImplemented("listxattr")) { fuseOperations.listxattr.set(fuse::listxattr); } if (isImplemented("removexattr")) { fuseOperations.removexattr.set(fuse::removexattr); } if (isImplemented("opendir")) { fuseOperations.opendir.set((path, fi) -> fuse.opendir(path, FuseFileInfo.of(fi))); } if (isImplemented("readdir")) { fuseOperations.readdir.set((path, buf, filter, offset, fi) -> { ClosureHelper helper = ClosureHelper.getInstance(); FromNativeConverter<FuseFillDir, Pointer> conveter = helper.getNativeConveter(FuseFillDir.class); FuseFillDir filterFunc = conveter.fromNative(filter, helper.getFromNativeContext()); return fuse.readdir(path, buf, filterFunc, offset, FuseFileInfo.of(fi)); }); } if (isImplemented("releasedir")) { fuseOperations.releasedir.set((path, fi) -> fuse.releasedir(path, FuseFileInfo.of(fi))); } if (isImplemented("fsyncdir")) { fuseOperations.fsyncdir.set((path, fi) -> fuse.fsyncdir(path, FuseFileInfo.of(fi))); } fuseOperations.init.set(conn -> { AbstractFuseFS.this.fusePointer = libFuse.fuse_get_context().fuse.get(); if (isImplemented("init")) { return fuse.init(conn); } return null; }); if (isImplemented("destroy")) { fuseOperations.destroy.set(fuse::destroy); } if (isImplemented("access")) { fuseOperations.access.set(fuse::access); } if (isImplemented("create")) { fuseOperations.create.set((path, mode, fi) -> fuse.create(path, mode, FuseFileInfo.of(fi))); } if (isImplemented("ftruncate")) { fuseOperations.ftruncate.set((path, size, fi) -> fuse.ftruncate(path, size, FuseFileInfo.of(fi))); } if (isImplemented("fgetattr")) { fuseOperations.fgetattr.set((path, stbuf, fi) -> fuse.fgetattr(path, FileStat.of(stbuf), FuseFileInfo.of(fi))); } if (isImplemented("lock")) { fuseOperations.lock.set((path, fi, cmd, flock) -> fuse.lock(path, FuseFileInfo.of(fi), cmd, Flock.of(flock))); } if (isImplemented("utimens")) { fuseOperations.utimens.set((path, timespec) -> { Timespec timespec1 = Timespec.of(timespec); Timespec timespec2 = Timespec.of(timespec.slice(Struct.size(timespec1))); return fuse.utimens(path, new Timespec[]{timespec1, timespec2}); }); } if (isImplemented("bmap")) { fuseOperations.bmap.set((path, blocksize, idx) -> fuse.bmap(path, blocksize, idx.getLong(0))); } if (isImplemented("ioctl")) { fuseOperations.ioctl.set((path, cmd, arg, fi, flags, data) -> fuse.ioctl(path, cmd, arg, FuseFileInfo.of(fi), flags, data)); } if (isImplemented("poll")) { fuseOperations.poll.set((path, fi, ph, reventsp) -> fuse.poll(path, FuseFileInfo.of(fi), FusePollhandle.of(ph), reventsp)); } if (isImplemented("write_buf")) { fuseOperations.write_buf.set((path, buf, off, fi) -> fuse.write_buf(path, FuseBufvec.of(buf), off, FuseFileInfo.of(fi))); } if (isImplemented("read_buf")) { fuseOperations.read_buf.set((path, bufp, size, off, fi) -> fuse.read_buf(path, bufp, size, off, FuseFileInfo.of(fi))); } if (isImplemented("flock")) { fuseOperations.flock.set((path, fi, op) -> fuse.flock(path, FuseFileInfo.of(fi), op)); } if (isImplemented("fallocate")) { fuseOperations.fallocate.set((path, mode, off, length, fi) -> fuse.fallocate(path, mode, off, length, FuseFileInfo.of(fi))); } } @Override public void mount(Path mountPoint, boolean blocking, boolean debug, String[] fuseOpts) { if (!mounted.compareAndSet(false, true)) { throw new FuseException("Fuse fs already mounted!"); } this.mountPoint = mountPoint; String[] arg; String mountPointStr = mountPoint.toAbsolutePath().toString(); if (mountPointStr.endsWith("\\")) { mountPointStr = mountPointStr.substring(0, mountPointStr.length() - 1); } if (!debug) { arg = new String[]{getFSName(), "-f", mountPointStr}; } else { arg = new String[]{getFSName(), "-f", "-d", mountPointStr}; } if (fuseOpts.length != 0) { int argLen = arg.length; arg = Arrays.copyOf(arg, argLen + fuseOpts.length); System.arraycopy(fuseOpts, 0, arg, argLen, fuseOpts.length); } final String[] args = arg; try { if (SecurityUtils.canHandleShutdownHooks()) { java.lang.Runtime.getRuntime().addShutdownHook(new Thread(this::umount)); } int res; if (blocking) { res = execMount(args); } else { // Create a separate thread to hold the mounted FUSE file system. CompletableFuture<Integer> mountResult = new CompletableFuture<>(); Thread mountThread = new Thread(() -> { try { mountResult.complete(execMount(args)); } catch (Throwable t) { mountResult.completeExceptionally(t); } }, "jnr-fuse-mount-thread"); mountThread.setDaemon(true); mountThread.start(); try { res = mountResult.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { res = 0; } } if (res != 0) { throw new FuseException("Unable to mount FS, return code = " + res); } } catch (Exception e) { mounted.set(false); throw new FuseException("Unable to mount FS", e); } } private boolean isImplemented(String funcName) { return !notImplementedMethods.contains(funcName); } private int execMount(String[] arg) { return libFuse.fuse_main_real(arg.length, arg, fuseOperations, Struct.size(fuseOperations), null); } @Override public void umount() { if (!mounted.get()) { return; } if (Platform.IS_WINDOWS) { Pointer fusePointer = this.fusePointer; if (fusePointer != null) { libFuse.fuse_exit(fusePointer); } } else { MountUtils.umount(mountPoint); } mounted.set(false); } protected String getFSName() { return "fusefs" + ThreadLocalRandom.current().nextInt(); } }
package seedu.doist.model.task; import java.util.Date; import java.util.List; import com.joestelmach.natty.DateGroup; import seedu.doist.commons.exceptions.IllegalValueException; public class TaskDate { private Date startDate; private Date endDate; public TaskDate() { this.startDate = null; this.endDate = null; } public TaskDate (Date startDate, Date endDate) { this.startDate = startDate; this.endDate = endDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String toString() { if (this.startDate != null && this.endDate != null) { return this.startDate.toString() + "--" + this.endDate.toString(); } else { return "No dates"; } } public boolean isPast() { if (this.getStartDate() != null && this.getEndDate() != null) { Date currentDate = new Date(); return (this.getEndDate().compareTo(currentDate) < 0); } else { return false; } } public static boolean validateDate (Date startDate, Date endDate) throws IllegalValueException { if (startDate == null || endDate == null) { throw new IllegalValueException("Incorrect Dates"); } else { return (startDate.compareTo(endDate) <= 0) ? true : false; } } /** * Function to support natural language input for date and time, using a 3rd party library 'Natty' * @param date * @return extracte Date if parsing is succesful, or null if it fails */ public static Date parseDate (String date) { com.joestelmach.natty.Parser parser = new com.joestelmach.natty.Parser(); List<DateGroup> groups = parser.parse(date); Date extractDate = null; boolean flag = false; for (DateGroup group:groups) { List<Date> dates = group.getDates(); if (!dates.isEmpty()) { extractDate = dates.get(0); flag = true; } } return (flag ? extractDate : null); } }
package skadistats.clarity.decoder; import com.google.protobuf.ByteString; import com.rits.cloning.Cloner; import org.xerial.snappy.Snappy; import skadistats.clarity.ClarityException; import skadistats.clarity.decoder.unpacker.Unpacker; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; public class Util { public static int calcBitsNeededFor(long x) { if (x == 0) return (0); int n = 32; if (x <= 0x0000FFFF) { n = n - 16; x = x << 16; } if (x <= 0x00FFFFFF) { n = n - 8; x = x << 8; } if (x <= 0x0FFFFFFF) { n = n - 4; x = x << 4; } if (x <= 0x3FFFFFFF) { n = n - 2; x = x << 2; } if (x <= 0x7FFFFFFF) { n = n - 1; } return n; } public static String convertByteString(ByteString s, String charsetName) { try { return s.toString(charsetName); } catch (UnsupportedEncodingException e) { throw Util.toClarityException(e); } } private static final Cloner CLONER = new Cloner(); public static <T> T clone(T src) { return CLONER.deepClone(src); } public static String arrayIdxToString(int idx) { return String.format("%04d", idx); } public static <T> Class<T> valueClassForUnpacker(Unpacker<T> unpacker) { ParameterizedType interfaceType = (ParameterizedType) unpacker.getClass().getGenericInterfaces()[0]; return (Class<T>)interfaceType.getActualTypeArguments()[0]; } public static void byteCopy(Object src, int srcOffset, Object dst, int dstOffset, int n) { try { Snappy.arrayCopy(src, srcOffset, n, dst, dstOffset); } catch (IOException e) { throw Util.toClarityException(e); } } public static ClarityException toClarityException(Throwable throwable) { if (throwable instanceof ClarityException) { return (ClarityException) throwable; } else { return new ClarityException(throwable); } } }
package starpunk.screens; import com.artemis.World; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import starpunk.logic.EntityFactory; import starpunk.StarPunkGame; import starpunk.services.music.MusicResource; import starpunk.services.sound.SoundResource; import starpunk.logic.systems.MovementSystem; import starpunk.logic.systems.SpriteRenderSystem; public final class GameLoopScreen extends BaseScreen { private World _world; private OrthographicCamera _camera; private SpriteRenderSystem _renderSystem; public GameLoopScreen( final StarPunkGame game ) { super( game ); _camera = new OrthographicCamera( StarPunkGame.WIDTH, StarPunkGame.HEIGHT ); _world = new World(); _renderSystem = _world.setSystem( new SpriteRenderSystem( game, _camera ), true ); _world.setSystem( new MovementSystem() ); _world.initialize(); for( int i = 0; i < 500; i++ ) { EntityFactory.createStar( _world, StarPunkGame.WIDTH, StarPunkGame.HEIGHT ).addToWorld(); } EntityFactory.createShip( _world, 0, 0 ).addToWorld(); } @Override public void show() { super.show(); getGame().getMusicManager().play( new MusicResource( "src/main/assets/music/level.ogg" ) ); } @Override public void hide() { super.hide(); getGame().getMusicManager().play( null ); } @Override public void update( final float delta ) { _world.setDelta( delta ); _world.process(); } @Override public void draw( final float delta ) { _camera.update(); Gdx.gl20.glClear( GL20.GL_COLOR_BUFFER_BIT ); _renderSystem.process(); } @Override public void render( final float delta ) { super.render( delta ); if( Gdx.input.isTouched() ) { getGame().getSoundManager().play( new SoundResource( "src/main/assets/sounds/click.wav" ) ); getGame().setScreen( new EndGameScreen( getGame() ) ); } } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui.layout; import pythagoras.f.Dimension; import pythagoras.f.IDimension; import tripleplay.ui.Element; import tripleplay.ui.Elements; import tripleplay.ui.Layout; import tripleplay.ui.Style; /** * Lays out elements in a horizontal or vertical group. Separate policies are enforced for on-axis * and off-axis sizing. * * <p> On-axis, the available space is divided up as follows: non-stretched elements are given * their preferred size, and remaining space is divided up among the stretched elements * proportional to their configured weight (which defaults to one). If no stretched elements exist, * elements are aligned per the {@link tripleplay.ui.Style.HAlign} and * {@link tripleplay.ui.Style.VAlign} properties on the containing group. </p> * * <p> Off-axis sizing can be configured to either size elements to their preferred size, stretch * them all to a uniform size (equal to the preferred size of the largest element), or to stretch * them all to the size allotted to the container. When elements are not stretched to fill the size * allotted to the container, they may be aligned as above. </p> */ public abstract class AxisLayout extends Layout { /** Specifies the off-axis layout policy. */ public static enum Policy { DEFAULT { public float computeSize (float size, float maxSize, float extent) { return Math.min(size, extent); } }, STRETCH { public float computeSize (float size, float maxSize, float extent) { return extent; } }, EQUALIZE { public float computeSize (float size, float maxSize, float extent) { return Math.min(maxSize, extent); } }; public abstract float computeSize (float size, float maxSize, float extent); }; /** Defines axis layout constraints. */ public static final class Constraint extends Layout.Constraint { public final boolean stretch; public final float weight; public Constraint (boolean stretch, float weight) { this.stretch = stretch; this.weight = weight; } public float computeSize (float size, float totalWeight, float availSize) { return stretch ? (availSize * weight / totalWeight) : size; } } /** A vertical axis layout. */ public static class Vertical extends AxisLayout { @Override public Dimension computeSize (Elements<?> elems, float hintX, float hintY) { Metrics m = computeMetrics(elems, hintX, hintY, true); return new Dimension(m.maxWidth, m.prefHeight + m.gaps(_gap)); } @Override public void layout (Elements<?> elems, float left, float top, float width, float height) { Style.HAlign halign = resolveStyle(elems, Style.HALIGN); Style.VAlign valign = resolveStyle(elems, Style.VALIGN); Metrics m = computeMetrics(elems, width, height, true); float stretchHeight = Math.max(0, height - m.gaps(_gap) - m.fixHeight); float y = top + ((m.stretchers > 0) ? 0 : valign.offset(m.fixHeight + m.gaps(_gap), height)); for (Element<?> elem : elems) { if (!elem.isVisible()) continue; IDimension psize = preferredSize(elem, width, height); // will be cached Constraint c = constraint(elem); float ewidth = _offPolicy.computeSize(psize.width(), m.maxWidth, width); float eheight = c.computeSize(psize.height(), m.totalWeight, stretchHeight); setBounds(elem, left + halign.offset(ewidth, width), y, ewidth, eheight); y += (eheight + _gap); } } } /** A horizontal axis layout. */ public static class Horizontal extends AxisLayout { @Override public Dimension computeSize (Elements<?> elems, float hintX, float hintY) { Metrics m = computeMetrics(elems, hintX, hintY, false); return new Dimension(m.prefWidth + m.gaps(_gap), m.maxHeight); } @Override public void layout (Elements<?> elems, float left, float top, float width, float height) { Style.HAlign halign = resolveStyle(elems, Style.HALIGN); Style.VAlign valign = resolveStyle(elems, Style.VALIGN); Metrics m = computeMetrics(elems, width, height, false); float stretchWidth = Math.max(0, width - m.gaps(_gap) - m.fixWidth); float x = left + ((m.stretchers > 0) ? 0 : halign.offset(m.fixWidth + m.gaps(_gap), width)); for (Element<?> elem : elems) { if (!elem.isVisible()) continue; IDimension psize = preferredSize(elem, width, height); // will be cached Constraint c = constraint(elem); float ewidth = c.computeSize(psize.width(), m.totalWeight, stretchWidth); float eheight = _offPolicy.computeSize(psize.height(), m.maxHeight, height); setBounds(elem, x, top + valign.offset(eheight, height), ewidth, eheight); x += (ewidth + _gap); } } } /** * Creates a vertical axis layout with default gap (5), and off-axis sizing policy (preferred * size). */ public static Vertical vertical () { return new Vertical(); } /** * Creates a horizontal axis layout with default gap (5), and off-axis sizing policy (preferred * size). */ public static Horizontal horizontal () { return new Horizontal(); } /** * Returns a layout constraint indicating that the associated element should be stretched to * consume extra space, with weight 1. */ public static Constraint stretched () { return UNIFORM_STRETCHED; } /** * Returns a layout constraint indicating that the associated element should not be stretched. */ public static Constraint fixed () { return UNSTRETCHED; } /** * Returns a layout constraint indicating that the associated element should be stretched to * consume extra space, with the specified weight. */ public static Constraint stretched (float weight) { return new Constraint(true, weight); } /** * Configures the supplied element with a {@link #stretched} constraint. */ public static <T extends Element<T>> T stretch (T elem) { return elem.setConstraint(stretched()); } /** * Configures the supplied element with a weighted {@link #stretched(float)} constraint. */ public static <T extends Element<T>> T stretch (T elem, float weight) { return elem.setConstraint(stretched(weight)); } /** * Configures the default constraint for elements added to this layout to be stretched. This * is equivalent to calling {@link Element#setConstraint()} with {@link #stretched()} for each * element added to the parent container. */ public AxisLayout stretchByDefault () { _stretchByDefault = true; return this; } /** * Configures the off-axis sizing policy for this layout. */ public AxisLayout offPolicy (Policy policy) { _offPolicy = policy; return this; } /** * Configures this layout to stretch all elements to the available size on the off-axis. */ public AxisLayout offStretch () { return offPolicy(Policy.STRETCH); } /** * Configures this layout to stretch all elements to the size of the largest element on the * off-axis. */ public AxisLayout offEqualize () { return offPolicy(Policy.EQUALIZE); } /** * Configures the inter-element gap, in pixels. */ public AxisLayout gap (int gap) { _gap = gap; return this; } protected Metrics computeMetrics (Elements<?> elems, float hintX, float hintY, boolean vert) { Metrics m = new Metrics(); for (Element<?> elem : elems) { if (!elem.isVisible()) continue; m.count++; // only compute the preferred size for the fixed elements in this pass Constraint c = constraint(elem); if (!c.stretch) { IDimension psize = preferredSize(elem, hintX, hintY); float pwidth = psize.width(), pheight = psize.height(); m.prefWidth += pwidth; m.prefHeight += pheight; m.maxWidth = Math.max(m.maxWidth, pwidth); m.maxHeight = Math.max(m.maxHeight, pheight); m.fixWidth += pwidth; m.fixHeight += pheight; } else { m.stretchers++; m.totalWeight += c.weight; } } // now compute the preferred size for the stretched elements, providing them with more // accurate width/height hints for (Element<?> elem : elems) { if (!elem.isVisible()) continue; Constraint c = constraint(elem); if (!c.stretch) continue; // the first argument to computeSize is not used for stretched elements float availX = hintX - m.gaps(_gap), availY = hintY - m.gaps(_gap); float ehintX = vert ? availX : c.computeSize(0, m.totalWeight, availX); float ehintY = vert ? c.computeSize(0, m.totalWeight, availY) : availY; IDimension psize = preferredSize(elem, ehintX, ehintY); float pwidth = psize.width(), pheight = psize.height(); m.unitWidth = Math.max(m.unitWidth, pwidth / c.weight); m.unitHeight = Math.max(m.unitHeight, pheight / c.weight); m.maxWidth = Math.max(m.maxWidth, pwidth); m.maxHeight = Math.max(m.maxHeight, pheight); } m.prefWidth += m.stretchers * m.unitWidth; m.prefHeight += m.stretchers * m.unitHeight; return m; } protected Constraint constraint (Element<?> elem) { Layout.Constraint c = elem.constraint(); return (c instanceof Constraint) ? (Constraint)c : _stretchByDefault ? UNIFORM_STRETCHED : UNSTRETCHED; } protected static class Metrics { public int count; public float prefWidth; public float prefHeight; public float maxWidth; public float maxHeight; public float fixWidth; public float fixHeight; public float unitWidth; public float unitHeight; public int stretchers; public float totalWeight; public float gaps (float gap) { return gap * (count-1); } } protected int _gap = 5; protected boolean _stretchByDefault; protected Policy _offPolicy = Policy.DEFAULT; protected static final Constraint UNSTRETCHED = new Constraint(false, 1); protected static final Constraint UNIFORM_STRETCHED = new Constraint(true, 1); }
package yanagishima.servlet; import me.geso.tinyorm.TinyORM; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import yanagishima.config.YanagishimaConfig; import yanagishima.exception.HiveQueryErrorException; import yanagishima.result.HiveQueryResult; import yanagishima.row.Query; import yanagishima.service.HiveService; import yanagishima.util.AccessControlUtil; import yanagishima.util.HttpRequestUtil; import yanagishima.util.JsonUtil; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; @Singleton public class HiveServlet extends HttpServlet { private static Logger LOGGER = LoggerFactory .getLogger(HiveServlet.class); private static final long serialVersionUID = 1L; @Inject private TinyORM db; private YanagishimaConfig yanagishimaConfig; private final HiveService hiveService; @Inject public HiveServlet(YanagishimaConfig yanagishimaConfig, HiveService hiveService) { this.yanagishimaConfig = yanagishimaConfig; this.hiveService = hiveService; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, Object> retVal = new HashMap<String, Object>(); Optional<String> queryOptional = Optional.ofNullable(request.getParameter("query")); queryOptional.ifPresent(query -> { try { String userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName()); if (yanagishimaConfig.isUserRequired() && userName == null) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } String datasource = HttpRequestUtil.getParam(request, "datasource"); if (yanagishimaConfig.isCheckDatasource()) { if (!AccessControlUtil.validateDatasource(request, datasource)) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } } if (userName != null) { LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource)); } boolean storeFlag = Boolean.parseBoolean(Optional.ofNullable(request.getParameter("store")).orElse("false")); int limit = yanagishimaConfig.getSelectLimit(); try { HiveQueryResult hiveQueryResult = hiveService.doQuery(datasource, query, userName, storeFlag, limit); String queryid = hiveQueryResult.getQueryId(); retVal.put("queryid", queryid); retVal.put("headers", hiveQueryResult.getColumns()); if(query.toLowerCase().indexOf("show schemas") != -1) { List<String> invisibleDatabases = yanagishimaConfig.getInvisibleDatabases(datasource); retVal.put("results", hiveQueryResult.getRecords().stream().filter(list -> !invisibleDatabases.contains(list.get(0))).collect(Collectors.toList())); } else { retVal.put("results", hiveQueryResult.getRecords()); } retVal.put("lineNumber", Integer.toString(hiveQueryResult.getLineNumber())); retVal.put("rawDataSize", hiveQueryResult.getRawDataSize().toString()); Optional<String> warningMessageOptinal = Optional.ofNullable(hiveQueryResult.getWarningMessage()); warningMessageOptinal.ifPresent(warningMessage -> { retVal.put("warn", warningMessage); }); Optional<Query> queryDataOptional = db.single(Query.class).where("query_id=? and datasource=?", queryid, datasource).execute(); queryDataOptional.ifPresent(queryData -> { LocalDateTime submitTimeLdt = LocalDateTime.parse(queryid.substring(0, "yyyyMMdd_HHmmss".length()), DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); ZonedDateTime submitTimeZdt = submitTimeLdt.atZone(ZoneId.of("GMT", ZoneId.SHORT_IDS)); String fetchResultTimeString = queryData.getFetchResultTimeString(); ZonedDateTime fetchResultTime = ZonedDateTime.parse(fetchResultTimeString); long elapsedTimeMillis = ChronoUnit.MILLIS.between(submitTimeZdt, fetchResultTime); retVal.put("elapsedTimeMillis", elapsedTimeMillis); }); } catch (HiveQueryErrorException e) { LOGGER.error(e.getMessage(), e); retVal.put("queryid", e.getQueryId()); retVal.put("error", e.getMessage()); } } catch (Throwable e) { LOGGER.error(e.getMessage(), e); retVal.put("error", e.getMessage()); } }); JsonUtil.writeJSON(response, retVal); } }
package com.stratio.meta.deep; import com.datastax.driver.core.Session; import com.stratio.deep.config.DeepJobConfigFactory; import com.stratio.deep.config.IDeepJobConfig; import com.stratio.deep.context.DeepSparkContext; import com.stratio.meta.common.data.CassandraResultSet; import com.stratio.meta.common.data.Cell; import com.stratio.meta.common.data.ResultSet; import com.stratio.meta.common.data.Row; import com.stratio.meta.common.result.QueryResult; import com.stratio.meta.common.result.Result; import com.stratio.meta.core.engine.EngineConfig; import com.stratio.meta.core.statements.MetaStatement; import com.stratio.meta.core.statements.SelectStatement; import com.stratio.meta.core.structures.Relation; import com.stratio.meta.core.structures.SelectionClause; import com.stratio.meta.deep.functions.*; import com.stratio.meta.deep.utils.DeepUtils; import org.apache.log4j.Logger; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import java.util.*; /** * Class that performs as a Bridge between Meta and Stratio Deep. */ public class Bridge { /** * Class logger. */ private static final Logger LOG = Logger.getLogger(Bridge.class); /** * Default result size. */ public static final int DEFAULT_RESULT_SIZE = 100000; /** * Deep Spark context. */ private DeepSparkContext deepContext; /** * Datastax Java Driver session. */ private Session session; /** * Global configuration. */ private EngineConfig engineConfig; /** * Brigde Constructor. * @param session Cassandra session. {@link com.datastax.driver.core.Session} * @param deepSparkContext Spark context from Deep * @param config A {@link com.stratio.meta.core.engine.EngineConfig}, contains global configuration */ public Bridge(Session session, DeepSparkContext deepSparkContext, EngineConfig config) { this.deepContext = deepSparkContext; this.session = session; this.engineConfig = config; } /** * Execute a Leaf node in the current plan. * @param stmt Statement which corresponds to this node. * @param isRoot Indicates if this node is root in this plan * @return a {@link com.stratio.meta.common.data.ResultSet} */ public ResultSet executeLeafNode(MetaStatement stmt, boolean isRoot){ SelectStatement ss = (SelectStatement) stmt; // LEAF String[] columnsSet = {}; if(ss.getSelectionClause().getType() == SelectionClause.TYPE_SELECTION){ columnsSet = DeepUtils.retrieveSelectorFields(ss); } IDeepJobConfig config = DeepJobConfigFactory.create().session(session) .host(engineConfig.getRandomCassandraHost()).rpcPort(engineConfig.getCassandraPort()) .keyspace(ss.getKeyspace()).table(ss.getTableName()); config = (columnsSet.length==0)? config.initialize(): config.inputColumns(columnsSet).initialize(); JavaRDD rdd = deepContext.cassandraJavaRDD(config); //If where if(ss.isWhereInc()){ List<Relation> where = ss.getWhere(); for(Relation rel : where){ rdd = doWhere(rdd, rel); } } return returnResult(rdd, isRoot, ss.getSelectionClause().getType() == SelectionClause.TYPE_COUNT, Arrays.asList(columnsSet)); } /** * Executes a root node statement. * @param stmt Statement which corresponds to this node. * @param resultsFromChildren List of results from node children * @return a {@link com.stratio.meta.common.data.ResultSet} */ public ResultSet executeRootNode(MetaStatement stmt, List<Result> resultsFromChildren){ SelectStatement ss = (SelectStatement) stmt; // Retrieve RDDs and selected columns from children List<JavaRDD> children = new ArrayList<>(); List<String> selectedCols = new ArrayList<>(); for (Result child: resultsFromChildren){ QueryResult qResult = (QueryResult) child; CassandraResultSet crset = (CassandraResultSet) qResult.getResultSet(); Map<String, Cell> cells = crset.getRows().get(0).getCells(); // RDD from child Cell cell = cells.get("RDD"); JavaRDD rdd = (JavaRDD) cell.getValue(); children.add(rdd); } // Retrieve selected columns without tablename for(String id: ss.getSelectionClause().getIds()){ if(id.contains(".")){ selectedCols.add(id.split("\\.")[1]); } else { selectedCols.add(id); } } //JOIN Map<String, String> fields = ss.getJoin().getColNames(); Set<String> keys = fields.keySet(); String field1 = keys.iterator().next(); String field2 = fields.get(field1); LOG.debug("INNER JOIN on: " + field1 + " - " + field2); JavaRDD rdd1 = children.get(0); JavaRDD rdd2 = children.get(1); JavaPairRDD rddLeft = rdd1.map(new MapKeyForJoin(field1)); JavaPairRDD rddRight = rdd2.map(new MapKeyForJoin(field2)); JavaPairRDD joinRDD = rddLeft.join(rddRight); JavaRDD result = joinRDD.map(new JoinCells(field1)); // Return MetaResultSet return returnResult(result, true, false, selectedCols); } /** * General execution. Depending on the type execution will divide up. * @param stmt Statement which corresponds to this node. * @param resultsFromChildren List of results from node children * @param isRoot Indicates if this node is root in this plan * @return a {@link com.stratio.meta.common.data.ResultSet} */ public ResultSet execute(MetaStatement stmt, List<Result> resultsFromChildren, boolean isRoot){ LOG.info("Executing deep for: " + stmt.toString()); if(!(stmt instanceof SelectStatement)){ List<Row> oneRow = new ArrayList<>(); oneRow.add(new Row("RESULT", new Cell(String.class, "NOT supported yet"))); return new CassandraResultSet(oneRow); } if(resultsFromChildren.isEmpty()){ // LEAF return executeLeafNode(stmt, isRoot); } else { // (INNER NODE) NO LEAF return executeRootNode(stmt, resultsFromChildren); } } /** * Build a ResultSet from a RDD depending the context. * @param rdd RDD which corresponds to Spark result. * @param isRoot Indicates if this node is root in this plan. * @param isCount Indicates if this query have a COUNT clause. * @param selectedCols List of columns selected in current SelectStatement. * @return ResultSet containing the result of built. */ private ResultSet returnResult(JavaRDD rdd, boolean isRoot, boolean isCount, List<String> selectedCols){ if(isRoot){ if(isCount){ return DeepUtils.buildCountResult(rdd); } return DeepUtils.buildResultSet(rdd.dropTake(0, DEFAULT_RESULT_SIZE), selectedCols); } else { List<Row> partialResult = new ArrayList<>(); Row partialRow = new Row("RDD", new Cell(JavaRDD.class, rdd)); partialResult.add(partialRow); LOG.info("LEAF: rdd.count=" + ((int) rdd.count())); return new CassandraResultSet(partialResult); } } /** * Take a RDD and a Relation and apply suitable filter to the RDD. Execute where clause on Deep. * @param rdd RDD which filter must be applied. * @param rel {@link com.stratio.meta.core.structures.Relation} to apply * @return A new RDD with the result. */ private JavaRDD doWhere(JavaRDD rdd, Relation rel){ String operator = rel.getOperator(); JavaRDD result = null; String cn = rel.getIdentifiers().get(0); if(cn.contains(".")){ String[] ksAndTableName = cn.split("\\."); cn = ksAndTableName[1]; } Object termValue = rel.getTerms().get(0).getTermValue(); LOG.info("Rdd input size: " + rdd.count()); switch (operator){ case "=": result = rdd.filter(new DeepEquals(cn, termValue)); break; case "<>": result = rdd.filter(new NotEquals(cn,termValue)); break; case ">": result = rdd.filter(new GreaterThan(cn,termValue)); break; case ">=": result = rdd.filter(new GreaterEqualThan(cn,termValue)); break; case "<": result = rdd.filter(new LessThan(cn,termValue)); break; case "<=": result = rdd.filter(new LessEqualThan(cn,termValue)); break; default: LOG.error("Operator not supported: " + operator); result = null; } return result; } }
// THIS IS GENERATED CODE, YOU SHOULD COPY THIS FOR YOUR HAND EDITS package com.aterrasys.nevada.provider; public class NevadaSchema extends NevadaSchemaBase { public static final int DATABASE_VERSION = 1; public static class UserpeopleTableSchema extends UserpeopleTableSchemaBase { protected UserpeopleTableSchema() { super(); } /** Add relation constants as appropriate. i.e. public static final String <NAME> = "<sponsor>.provider.<name>.<table>.action.<NAME>"; e.g. public static final String CONSTANT = "com.aterrasys.nevada.provider.nevada.userpeople.action.CONSTANT"; public static final String PRIORITY_SORT_ORDER = UserpeopleTableSchemaBase.EXPIRATION + " DESC, " + UserpeopleTableSchemaBase.MODIFIED_DATE + " DESC "; */ } public static class ChannelsTableSchema extends ChannelsTableSchemaBase { protected ChannelsTableSchema() { super(); } /** Add relation constants as appropriate. i.e. public static final String <NAME> = "<sponsor>.provider.<name>.<table>.action.<NAME>"; e.g. public static final String CONSTANT = "com.aterrasys.nevada.provider.nevada.channels.action.CONSTANT"; public static final String PRIORITY_SORT_ORDER = ChannelsTableSchemaBase.EXPIRATION + " DESC, " + ChannelsTableSchemaBase.MODIFIED_DATE + " DESC "; */ } public static class UnitsTableSchema extends UnitsTableSchemaBase { protected UnitsTableSchema() { super(); } /** Add relation constants as appropriate. i.e. public static final String <NAME> = "<sponsor>.provider.<name>.<table>.action.<NAME>"; e.g. public static final String CONSTANT = "com.aterrasys.nevada.provider.nevada.units.action.CONSTANT"; public static final String PRIORITY_SORT_ORDER = UnitsTableSchemaBase.EXPIRATION + " DESC, " + UnitsTableSchemaBase.MODIFIED_DATE + " DESC "; */ } public static class MembersTableSchema extends MembersTableSchemaBase { protected MembersTableSchema() { super(); } /** Add relation constants as appropriate. i.e. public static final String <NAME> = "<sponsor>.provider.<name>.<table>.action.<NAME>"; e.g. public static final String CONSTANT = "com.aterrasys.nevada.provider.nevada.members.action.CONSTANT"; public static final String PRIORITY_SORT_ORDER = MembersTableSchemaBase.EXPIRATION + " DESC, " + MembersTableSchemaBase.MODIFIED_DATE + " DESC "; */ } public static class LocationsTableSchema extends LocationsTableSchemaBase { protected LocationsTableSchema() { super(); } /** Add relation constants as appropriate. i.e. public static final String <NAME> = "<sponsor>.provider.<name>.<table>.action.<NAME>"; e.g. public static final String CONSTANT = "com.aterrasys.nevada.provider.nevada.locations.action.CONSTANT"; public static final String PRIORITY_SORT_ORDER = LocationsTableSchemaBase.EXPIRATION + " DESC, " + LocationsTableSchemaBase.MODIFIED_DATE + " DESC "; */ } public static class MapannotationTableSchema extends MapannotationTableSchemaBase { protected MapannotationTableSchema() { super(); } /** Add relation constants as appropriate. i.e. public static final String <NAME> = "<sponsor>.provider.<name>.<table>.action.<NAME>"; e.g. public static final String CONSTANT = "com.aterrasys.nevada.provider.nevada.mapannotation.action.CONSTANT"; public static final String PRIORITY_SORT_ORDER = MapannotationTableSchemaBase.EXPIRATION + " DESC, " + MapannotationTableSchemaBase.MODIFIED_DATE + " DESC "; */ } }
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.HashMap; 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.QueryException; 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 StreamingSerializerPlugin ifcSerializerPlugin; private GenerateGeometryResult generateGeometryResult; private ObjectProvider objectProvider; private QueryContext queryContext; private DatabaseSession databaseSession; private RenderEnginePool renderEnginePool; 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; } @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); 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); WrappedVirtualObject minBoundsUntranslated = new HashMapWrappedVirtualObject(queryContext, GeometryPackage.eINSTANCE.getVector3f()); WrappedVirtualObject maxBoundsUntranslated = new HashMapWrappedVirtualObject(queryContext, GeometryPackage.eINSTANCE.getVector3f()); minBoundsUntranslated.set("x", Double.POSITIVE_INFINITY); minBoundsUntranslated.set("y", Double.POSITIVE_INFINITY); minBoundsUntranslated.set("z", Double.POSITIVE_INFINITY); maxBoundsUntranslated.set("x", -Double.POSITIVE_INFINITY); maxBoundsUntranslated.set("y", -Double.POSITIVE_INFINITY); maxBoundsUntranslated.set("z", -Double.POSITIVE_INFINITY); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_MinBoundsUntranslated(), minBoundsUntranslated); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_MaxBoundsUntranslated(), maxBoundsUntranslated); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Area(), renderEngineInstance.getArea()); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Volume(), renderEngineInstance.getVolume()); 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); processExtendsUntranslated(geometryInfo, 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(); // Doing a sync here because probably writing large amounts of data, and db only syncs every 100.000 writes by default databaseSession.getKeyValueStore().sync(); } 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) { LOGGER.warn("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) { if (progressListener != null) { progressListener.updateProgress("Generating geometry...", (int) (100.0 * jobsDone.get() / jobsTotal.get())); } } } @SuppressWarnings("unchecked") 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)); Map<Long, AtomicInteger> counters = new HashMap<>(); 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) { // Set<Long> representationItems = getRepresentationItems(databaseSession, queryContext, next); // for (Long l : representationItems) { // AtomicInteger atomicInteger = counters.get(l); // if (atomicInteger == null) { // atomicInteger = new AtomicInteger(0); // counters.put(l, atomicInteger); // atomicInteger.incrementAndGet(); 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 - 1) { 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")); } if (packageMetaData.getSchema() == Schema.IFC4) { queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":IsTypedBy")); } 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(); } } } // for (Long l : counters.keySet()) { // LOGGER.info(databaseSession.getEClassForOid(l).getName() + "(" + l + "): " + counters.get(l)); 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 Set<Long> getRepresentationItems(DatabaseSession databaseSession, QueryContext queryContext, HashMapVirtualObject next) throws QueryException, IOException { Set<Long> result = new HashSet<>(); Query query = new Query("test", packageMetaData); Include representation = query.createDefine("Representation"); representation.addType(packageMetaData.getEClass("IfcShapeRepresentation"), true); representation.addField("Items"); Include mapped = representation.createInclude(); mapped.addType(packageMetaData.getEClass("IfcMappedItem"), true); mapped.addField("MappingSource"); Include mappingSource = mapped.createInclude(); mappingSource.addType(packageMetaData.getEClass("IfcRepresentationMap"), false); mappingSource.addField("MappedRepresentation"); mappingSource.addInclude(representation); QueryPart queryPart = query.createQueryPart(); queryPart.addOid(next.getOid()); Include include = queryPart.createInclude(); include.addType(next.eClass(), false); include.addField("Representation"); Include representations = include.createInclude(); representations.addType(packageMetaData.getEClass("IfcProductDefinitionShape"), true); representations.addField("Representations"); representations.addInclude(representation); QueryObjectProvider queryObjectProvider = new QueryObjectProvider(databaseSession, bimServer, query, Collections.singleton(queryContext.getRoid()), packageMetaData); try { HashMapVirtualObject next2 = queryObjectProvider.next(); while (next2 != null) { if (packageMetaData.getEClass("IfcRepresentationItem").isSuperTypeOf(next2.eClass())) { result.add(next2.getOid()); } next2 = queryObjectProvider.next(); } } catch (BimserverDatabaseException e) { e.printStackTrace(); } return result; } 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 processExtendsUntranslated(VirtualObject geometryInfo, float[] vertices, int index, GenerateGeometryResult generateGeometryResult2) throws BimserverDatabaseException { double x = vertices[index]; double y = vertices[index + 1]; double z = vertices[index + 2]; HashMapWrappedVirtualObject minBounds = (HashMapWrappedVirtualObject) geometryInfo.eGet(GeometryPackage.eINSTANCE.getGeometryInfo_MinBoundsUntranslated()); HashMapWrappedVirtualObject maxBounds = (HashMapWrappedVirtualObject) geometryInfo.eGet(GeometryPackage.eINSTANCE.getGeometryInfo_MaxBoundsUntranslated()); 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"))); } 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 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()); } }
import static org.junit.Assert.assertEquals; import org.junit.Test; import otognan.Person; public class TestPerson { @Test public void testName() { Person person = new Person("Pete"); assertEquals(person.getName(), "Petes"); } }
package org.voovan.tools.reflect; import org.voovan.Global; import org.voovan.tools.*; import org.voovan.tools.compiler.function.DynamicFunction; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.annotation.NotSerialization; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public class TReflect { private class EmptyClass { private Object emptyField; private EmptyClass() { } private void emptyMethod(){ } } private static Constructor EMPTY_CONSTRUCTOR; private static Field EMPTY_FIELD; private static Method EMPTY_METHOD; static { try { EMPTY_CONSTRUCTOR = EmptyClass.class.getDeclaredConstructor(TReflect.class); EMPTY_FIELD = EmptyClass.class.getDeclaredField("emptyField"); EMPTY_METHOD = EmptyClass.class.getDeclaredMethod("emptyMethod"); } catch (Exception e) { Logger.error("Create empty reflect object failed", e); } } private static Map<String, Field> FIELDS = new ConcurrentHashMap<String ,Field>(); private static Map<String, Method> METHODS = new ConcurrentHashMap<String ,Method>(); private static Map<String, Constructor> CONSTRUCTORS = new ConcurrentHashMap<String ,Constructor>(); private static Map<Class, Field[]> FIELD_ARRAYS = new ConcurrentHashMap<Class ,Field[]>(); private static Map<String, Method[]> METHOD_ARRAYS = new ConcurrentHashMap<String ,Method[]>(); private static Map<String, Constructor[]> CONSTRUCTOR_ARRAYS = new ConcurrentHashMap<String ,Constructor[]>(); private static Map<Class, String> NAME_CLASS = new ConcurrentHashMap<Class ,String>(); private static Map<String, Class> CLASS_NAME = new ConcurrentHashMap<String, Class>(); private static Map<Class, Boolean> CLASS_BASIC_TYPE = new ConcurrentHashMap<Class ,Boolean>(); public static Map<String, DynamicFunction> FIELD_READER = new ConcurrentHashMap<String, DynamicFunction>(); public static Map<String, DynamicFunction> FIELD_WRITER = new ConcurrentHashMap<String, DynamicFunction>(); /** * * @param clazz */ public static void genFieldReader(Class clazz) throws ReflectiveOperationException { // if(fieldName.equals("string")) {return obj.getString();} // else if(fieldName.equals("bint")) {return obj.getBint();} // else if(fieldName.equals("map")) {return obj.getMap();} // else if(fieldName.equals("list")) {return obj.getList();} // else if(fieldName.equals("tb2")) {return obj.getTb2();} // else { return null; } String className = getClassName(clazz); Field[] fields = getFields(clazz); //arg1 obj, arg2 fieldName String code = ""; for(Field field : fields) { code = code + (code.isEmpty() ? "if" : "else if"); code = code + "(fieldName.equals(\"" + field.getName() + "\")) {"; String getMethodName = "get"+TString.upperCaseHead(field.getName())+"();"; code = code + "return obj."+getMethodName + "} \r\n"; } code = code + "else { return null; }"; DynamicFunction dynamicFunction = new DynamicFunction(clazz.getSimpleName()+"Reader", code); dynamicFunction.addImport(clazz); dynamicFunction.addPrepareArg(0, clazz, "obj"); dynamicFunction.addPrepareArg(1, String.class, "fieldName"); dynamicFunction.compileCode(); FIELD_READER.put(className, dynamicFunction); } /** * * @param clazz */ public static void genFieldWriter(Class clazz) throws ReflectiveOperationException { // if(fieldName.equals("string")) {obj.setString((java.lang.String)value);} // else if(fieldName.equals("bint")) {obj.setBint((int)value);} // else if(fieldName.equals("map")) {obj.setMap((java.util.HashMap)value);} // else if(fieldName.equals("list")) {obj.setList((java.util.Vector)value);} // else if(fieldName.equals("tb2")) {obj.setTb2((org.voovan.test.tools.json.TestObject2)value);} String className = getClassName(clazz); Field[] fields = getFields(clazz); //arg1 obj, arg2 fieldName, arg3 value String code = ""; for(Field field : fields) { code = code + (code.isEmpty() ? "if" : "else if"); code = code + "(fieldName.equals(\"" + field.getName() + "\")) {"; String setMethodName = "set"+TString.upperCaseHead(field.getName())+"(("+field.getType().getName()+")value); return true;"; code = code + "obj."+setMethodName + "} \r\n"; } code = code + "else { return false; }"; DynamicFunction dynamicFunction = new DynamicFunction(clazz.getSimpleName()+"Reader", code); dynamicFunction.addImport(clazz); dynamicFunction.addPrepareArg(0, clazz, "obj"); dynamicFunction.addPrepareArg(1, String.class, "fieldName"); dynamicFunction.addPrepareArg(2, Object.class, "value"); dynamicFunction.compileCode(); FIELD_WRITER.put(className, dynamicFunction); } /** * Field * @param obj * @param fieldName field * @param <T> field * @return Field * @throws ReflectiveOperationException */ public static <T> T getFieldValueNatvie(Object obj, String fieldName) throws ReflectiveOperationException { DynamicFunction dynamicFunction = FIELD_READER.get(getClassName(obj.getClass())); if(dynamicFunction == null) { return null; } try { return dynamicFunction.call(obj, fieldName); } catch (Exception e) { if (!(e instanceof ReflectiveOperationException)) { throw new ReflectiveOperationException(e.getMessage(), e); } else { throw (ReflectiveOperationException) e; } } } /** * Field * @param obj * @param field field * @param <T> field * @return Field * @throws Exception */ public static <T> T getFieldValueNatvie(Object obj, Field field) throws ReflectiveOperationException { return getFieldValueNatvie(obj, field.getName()); } /** * Field * @param obj * @param fieldName field * @param value Field * @throws Exception * @return */ public static Boolean setFieldValueNatvie(Object obj, String fieldName, Object value) throws ReflectiveOperationException { DynamicFunction dynamicFunction = FIELD_WRITER.get(getClassName(obj.getClass())); if(dynamicFunction == null) { return false; } try { return dynamicFunction.call(obj, fieldName, value); } catch (Exception e) { if (!(e instanceof ReflectiveOperationException)) { throw new ReflectiveOperationException(e.getMessage(), e); } else { throw (ReflectiveOperationException) e; } } } /** * Field * @param obj * @param field field * @param value Field * @throws Exception */ public static Boolean setFieldValueNatvie(Object obj, Field field, Object value) throws ReflectiveOperationException { return setFieldValueNatvie(obj, field.getName(), value); } /** * Class * @param clazz Class * @return */ public static String getClassName(Class clazz){ String canonicalName = NAME_CLASS.get(clazz); if(canonicalName == null){ canonicalName = clazz.getCanonicalName(); NAME_CLASS.put(clazz, canonicalName); } return canonicalName; } /** * , Class * @param className * @return Class * @throws ClassNotFoundException */ public static Class getClassByName(String className) throws ClassNotFoundException { Class clazz = CLASS_NAME.get(className); if(clazz == null){ clazz = Class.forName(className); CLASS_NAME.put(className, clazz); } return clazz; } /** * Field * * @param clazz * @return Field */ public static Field[] getFields(Class<?> clazz) { Field[] fields = FIELD_ARRAYS.get(clazz); Class loopClazz = clazz; if(fields==null){ LinkedHashSet<Field> fieldArray = new LinkedHashSet<Field>(); for (; loopClazz!=null && loopClazz != Object.class; loopClazz = loopClazz.getSuperclass()) { Field[] tmpFields = loopClazz.getDeclaredFields(); for (Field field : tmpFields){ field.setAccessible(true); } fieldArray.addAll(Arrays.asList(tmpFields)); } fields = fieldArray.toArray(new Field[]{}); if(clazz!=null) { FIELD_ARRAYS.put(clazz, fields); fieldArray.clear(); } } return fields; } /** * Field * * @param clazz * @param fieldName field * @return field */ public static Field findField(Class<?> clazz, String fieldName) { String mark = new StringBuilder(getClassName(clazz)).append(Global.CHAR_SHAPE).append(fieldName).toString(); Field field = FIELDS.get(mark); Class loopClazz = clazz; if(field==null){ for (; loopClazz!=null && loopClazz != Object.class; loopClazz = loopClazz.getSuperclass()) { try { field = loopClazz.getDeclaredField(fieldName); field.setAccessible(true); break; } catch(ReflectiveOperationException e){ field = null; } } if(mark!=null) { field = field == null ? EMPTY_FIELD : field; FIELDS.put(mark, field); } } return field == EMPTY_FIELD ? null : field; } /** * Field * , * @param clazz * @param fieldName Field * @return Field * @throws ReflectiveOperationException */ public static Field findFieldIgnoreCase(Class<?> clazz, String fieldName) { String marker = new StringBuilder(getClassName(clazz)).append(Global.CHAR_SHAPE).append(fieldName).toString(); Field field = FIELDS.get(marker); if (field==null){ for (Field fieldItem : getFields(clazz)) { if (fieldItem.getName().equalsIgnoreCase(fieldName) || fieldItem.getName().equalsIgnoreCase(TString.underlineToCamel(fieldName))) { if(marker!=null) { fieldItem.setAccessible(true); field = fieldItem; break; } } } field = field == null ? (Field) EMPTY_FIELD : field; FIELDS.put(marker, field); } return field == EMPTY_FIELD ? null : field; } /** * * @param type * @return Class[] */ public static Class[] getGenericClass(Type type) { ParameterizedType parameterizedType = null; if(type instanceof ParameterizedType) { parameterizedType = (ParameterizedType) type; } if(parameterizedType==null){ return null; } Class[] result = null; Type[] actualType = parameterizedType.getActualTypeArguments(); result = new Class[actualType.length]; for(int i=0;i<actualType.length;i++){ if(actualType[i] instanceof Class){ result[i] = (Class)actualType[i]; } else if(actualType[i] instanceof Type){ String classStr = actualType[i].toString(); classStr = TString.fastReplaceAll(classStr, "<.*>", ""); try { result[i] = Class.forName(classStr); } catch(Exception e){ result[i] = Object.class; } } else{ result[i] = Object.class; } } return result; } /** * * @param object * @return Class[] */ public static Class[] getGenericClass(Object object) { Class[] genericClazzs = TReflect.getGenericClass(object.getClass()); if (genericClazzs == null) { if (object instanceof Map) { if (((Map) object).size() > 0) { Map.Entry entry = (Map.Entry) ((Map) object).entrySet().iterator().next(); genericClazzs = new Class[]{entry.getKey().getClass(), entry.getValue().getClass()}; } } else if (object instanceof Collection) { if (((Collection) object).size() > 0) { Object obj = ((Collection) object).iterator().next(); genericClazzs = new Class[]{obj.getClass()}; } } } return genericClazzs; } /** * Field * @param field field * @return */ public static Class[] getFieldGenericType(Field field) { Type fieldType = field.getGenericType(); return getGenericClass((ParameterizedType)fieldType); } /** * Field * @param <T> * @param obj * @param fieldName Field * @return Field * @throws ReflectiveOperationException */ @SuppressWarnings("unchecked") static public <T> T getFieldValue(Object obj, String fieldName) throws ReflectiveOperationException { T t = getFieldValueNatvie(obj, fieldName); if(t==null) { Field field = findField(obj.getClass(), fieldName); t = (T) field.get(obj); } return t; } /** * Field * : private * * @param obj * @param field field * @param fieldValue field * @throws ReflectiveOperationException */ public static void setFieldValue(Object obj, Field field, Object fieldValue) throws ReflectiveOperationException { field.set(obj, fieldValue); } /** * Field * : private * * @param obj * @param fieldName field * @param fieldValue field * @throws ReflectiveOperationException */ public static void setFieldValue(Object obj, String fieldName, Object fieldValue) throws ReflectiveOperationException { boolean isSucc = setFieldValueNatvie(obj, fieldName, fieldValue); if(!isSucc) { Field field = findField(obj.getClass(), fieldName); setFieldValue(obj, field, fieldValue); } } /** * fieldMap (static) * * @param obj * @return field - Map * @throws ReflectiveOperationException */ public static Map<Field, Object> getFieldValues(Object obj) throws ReflectiveOperationException { HashMap<Field, Object> result = new HashMap<Field, Object>(); Field[] fields = getFields(obj.getClass()); for (Field field : fields) { if((field.getModifiers() & 0x00000008) != 0){ continue; } Object value = field.get(obj); result.put(field, value); } return result; } /** * * @param clazz * @param name * @param paramTypes * @return */ public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) { StringBuilder markBuilder = new StringBuilder(getClassName(clazz)).append(Global.CHAR_SHAPE).append(name); for(Class<?> paramType : paramTypes){ markBuilder.append("$").append(getClassName(paramType)); } String marker = markBuilder.toString(); Method method = METHODS.get(marker); if (method==null){ for (; clazz!=null && clazz != Object.class; clazz = clazz.getSuperclass()) { try { method = clazz.getDeclaredMethod(name, paramTypes); method.setAccessible(true); break; }catch(ReflectiveOperationException e){ method = null; } } if(marker!=null) { method = method == null ? EMPTY_METHOD : method; METHODS.put(marker, method); } } return method == EMPTY_METHOD ? null : method; } /** * () * @param clazz * @param name * @param paramCount * @return */ public static Method[] findMethod(Class<?> clazz, String name, int paramCount) { String marker = new StringBuilder(getClassName(clazz)).append(Global.CHAR_SHAPE).append(name).append(Global.CHAR_AT).append(paramCount).toString(); Method[] methods = METHOD_ARRAYS.get(marker); if (methods==null){ LinkedHashSet<Method> methodList = new LinkedHashSet<Method>(); Method[] allMethods = getMethods(clazz, name); for (Method method : allMethods) { if (method.getParameterTypes().length == paramCount) { method.setAccessible(true); methodList.add(method); } } methods = methodList.toArray(new Method[]{}); if(marker!=null) { METHOD_ARRAYS.put(marker, methods); methodList.clear(); } } return methods; } /** * * @param clazz * @return Method */ public static Method[] getMethods(Class<?> clazz) { Method[] methods = null; String marker = getClassName(clazz); methods = METHOD_ARRAYS.get(marker); if(methods==null){ LinkedHashSet<Method> methodList = new LinkedHashSet<Method>(); for (; clazz!=null && clazz != Object.class; clazz = clazz.getSuperclass()) { Method[] tmpMethods = clazz.getDeclaredMethods(); for(Method method : tmpMethods){ method.setAccessible(true); } methodList.addAll(Arrays.asList(tmpMethods)); } methods = methodList.toArray(new Method[]{}); if(marker!=null) { METHOD_ARRAYS.put(marker, methods); methodList.clear(); } } return methods; } /** * * * @param clazz * @param name * @return Method */ public static Method[] getMethods(Class<?> clazz, String name) { Method[] methods = null; String marker = new StringBuilder(getClassName(clazz)).append(Global.CHAR_SHAPE).append(name).toString(); methods = METHOD_ARRAYS.get(marker); if(methods==null){ LinkedHashSet<Method> methodList = new LinkedHashSet<Method>(); Method[] allMethods = getMethods(clazz); for (Method method : allMethods) { if (method.getName().equals(name)) methodList.add(method); } methods = methodList.toArray(new Method[0]); if(marker!=null) { METHOD_ARRAYS.put(marker, methods); methodList.clear(); } } return methods; } /** * * @param method method * @param parameterIndex (0)[0,], (-1) * @return */ public static Class[] getMethodParameterGenericType(Method method, int parameterIndex) { Class[] result = null; Type parameterType; if(parameterIndex == -1){ parameterType = method.getGenericReturnType(); }else{ parameterType = method.getGenericParameterTypes()[parameterIndex]; } return getGenericClass(parameterType); } /** * * Method * @param obj * @param method * @param parameters * @param <T> * @return * @throws ReflectiveOperationException */ public static <T> T invokeMethod(Object obj, Method method, Object... parameters) throws ReflectiveOperationException { return (T)method.invoke(obj, parameters); } /** * * , * * @param obj , Class * @param name * @param args * @param <T> * @return * @throws ReflectiveOperationException */ public static <T> T invokeMethod(Object obj, String name, Object... args) throws ReflectiveOperationException { if(args==null){ args = new Object[0]; } Method[] methods = null; Class objClass = (obj instanceof Class) ? (Class)obj : obj.getClass(); methods = findMethod(objClass, name, args.length); Exception exception = null; for(Method method : methods) { try { return (T) method.invoke(obj, args); } catch (Exception e) { } } if (!(exception instanceof ReflectiveOperationException)) { exception = new ReflectiveOperationException(exception.getMessage(), exception); } else { exception = (ReflectiveOperationException) exception; } throw (ReflectiveOperationException)exception; } /** * * @param clazz * @param paramTypes * @return */ public static Constructor findConstructor(Class<?> clazz, Class<?>... paramTypes) { StringBuilder markBuilder = new StringBuilder(getClassName(clazz)); for(Class<?> paramType : paramTypes){ markBuilder.append("$").append(getClassName(paramType)); } String marker = markBuilder.toString(); Constructor constructor = CONSTRUCTORS.get(marker); if (constructor==null){ for (; clazz!=null && clazz != Object.class; clazz = clazz.getSuperclass()) { try { constructor = clazz.getDeclaredConstructor(paramTypes); constructor.setAccessible(true); break; }catch(ReflectiveOperationException e){ constructor = null; } } if(marker!=null) { constructor = constructor == null ? EMPTY_CONSTRUCTOR : constructor; CONSTRUCTORS.put(marker, constructor); } } return constructor == EMPTY_CONSTRUCTOR ? null : constructor; } /** * () * @param clazz * @param paramCount * @return */ public static Constructor[] findConstructor(Class<?> clazz, int paramCount) { String marker = new StringBuilder(getClassName(clazz)).append(Global.CHAR_SHAPE).append(paramCount).toString(); Constructor[] constructors = CONSTRUCTOR_ARRAYS.get(marker); if (constructors==null){ LinkedHashSet<Constructor> constructorList = new LinkedHashSet<Constructor>(); Constructor[] allConstructor = getConstructors(clazz); for (Constructor constructor : allConstructor) { if (constructor.getParameterTypes().length == paramCount) { constructor.setAccessible(true); constructorList.add(constructor); } } constructors = constructorList.toArray(new Constructor[]{}); if(marker!=null) { CONSTRUCTOR_ARRAYS.put(marker, constructors); constructorList.clear(); } } return constructors; } /** * * @param clazz * @return Method */ public static Constructor[] getConstructors(Class<?> clazz) { Constructor[] constructors = null; String marker = getClassName(clazz); constructors = CONSTRUCTOR_ARRAYS.get(marker); if(constructors==null){ LinkedHashSet<Constructor> constructorList = new LinkedHashSet<Constructor>(); Constructor[] allConstructors = clazz.getDeclaredConstructors(); for(Constructor constructor : allConstructors){ constructor.setAccessible(true); } constructorList.addAll(Arrays.asList(allConstructors)); constructors = constructorList.toArray(new Constructor[]{}); if(marker!=null) { CONSTRUCTOR_ARRAYS.put(marker, constructors); CONSTRUCTOR_ARRAYS.clear(); } } return constructors; } /** * * parameters, * @param <T> * @param clazz * @param args * @return * @throws ReflectiveOperationException */ public static <T> T newInstance(Class<T> clazz, Object ...args) throws ReflectiveOperationException { if(args==null){ args = new Object[0]; } Class targetClazz = clazz; if(isImpByInterface(clazz, List.class) && (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers()))){ targetClazz = ArrayList.class; } if(isImpByInterface(clazz, Set.class) && (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers()))){ targetClazz = LinkedHashSet.class; } if(isImpByInterface(clazz, Map.class) && (Modifier.isAbstract(clazz.getModifiers()) && Modifier.isInterface(clazz.getModifiers()))){ targetClazz = LinkedHashMap.class; } if(args==null){ args = new Object[0]; } Constructor[] constructors = null; constructors = findConstructor(targetClazz, args.length); Exception lastException = null; for(Constructor constructor : constructors) { try { return (T) constructor.newInstance(args); } catch (Exception e) { lastException = e; } } // unsafe try { return (T) TUnsafe.getUnsafe().allocateInstance(targetClazz); } catch (Exception e) { if (!(e instanceof ReflectiveOperationException)) { lastException = new ReflectiveOperationException(e.getMessage(), e); } else { lastException = (ReflectiveOperationException) e; } throw (ReflectiveOperationException)lastException; } } /** * * @param <T> * @param className * @param parameters * @return * @throws ReflectiveOperationException */ public static <T> T newInstance(String className, Object ...parameters) throws ReflectiveOperationException { Class<T> clazz = getClassByName(className); return newInstance(clazz, parameters); } /** * Unsafe , * @param clazz * @param <T> * @return * @throws InstantiationException */ public static <T> T allocateInstance(Class<T> clazz) throws InstantiationException { return (T) TUnsafe.getUnsafe().allocateInstance(clazz); } /** * , * @param objs * @return */ public static Class<?>[] getArrayClasses(Object[] objs){ if(objs == null){ return new Class<?>[0]; } Class<?>[] parameterTypes= new Class<?>[objs.length]; for(int i=0;i<objs.length;i++){ if(objs[i]==null){ parameterTypes[i] = Object.class; }else { parameterTypes[i] = objs[i].getClass(); } } return parameterTypes; } /** * Map * * @param type * @param mapArg Map * @param ignoreCase * @return * @param <T> * @throws ReflectiveOperationException * @throws ParseException */ public static <T>T getObjectFromMap(Type type, Map<String, ?> mapArg, boolean ignoreCase) throws ParseException, ReflectiveOperationException { Class[] genericType = null; if(type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; genericType = getGenericClass(parameterizedType); } return getObjectFromMap(type, mapArg, genericType, ignoreCase); } // Map public final static Object SINGLE_VALUE_KEY = new Object(); /** * Map * * @param type * @param mapArg Map * @param genericType * @param ignoreCase * @return * @param <T> * @throws ReflectiveOperationException * @throws ParseException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T>T getObjectFromMap(Type type, Map<String, ?> mapArg, Class[] genericType, boolean ignoreCase) throws ReflectiveOperationException, ParseException { T obj = null; Class<?> clazz = null; if(type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; clazz = (Class)parameterizedType.getRawType(); }else if(type instanceof Class){ clazz = (Class)type; } if(mapArg==null){ return null; } Object singleValue = mapArg; if(mapArg.containsKey(SINGLE_VALUE_KEY)){ singleValue = mapArg.get(SINGLE_VALUE_KEY); } else if(mapArg.size() == 1) { singleValue = mapArg.values().iterator().next(); } if(clazz == Object.class){ if(mapArg.containsKey(SINGLE_VALUE_KEY)) { obj = (T) singleValue; } else { obj = (T) mapArg; } } //java else if (clazz.isPrimitive()){ if(singleValue!=null && singleValue.getClass() != clazz) { obj = TString.toObject(singleValue.toString(), clazz); } else { obj = (T)singleValue; } } //java else if (TReflect.isBasicType(clazz)) { // Map.Values obj = (T)(singleValue==null ? null : newInstance(clazz, singleValue.toString())); } //java BigDecimal else if (clazz == BigDecimal.class) { // Map.Values String value = singleValue==null ? null:singleValue.toString(); obj = (T)(singleValue==null ? null : new BigDecimal(value)); } // Atom else if (clazz == AtomicLong.class || clazz == AtomicInteger.class || clazz == AtomicBoolean.class) { if(singleValue==null){ obj = null; } else { obj = (T) TReflect.newInstance(clazz, singleValue); } } //java else if(isExtendsByClass(clazz, Date.class)){ // Map.Values String value = singleValue == null ? null : singleValue.toString(); SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE); Date dateObj = singleValue != null ? dateFormat.parse(value.toString()) : null; obj = (T)TReflect.newInstance(clazz,dateObj.getTime()); } //Map else if(isImpByInterface(clazz, Map.class)){ Map mapObject = (Map)newInstance(clazz); if(genericType!=null) { Iterator iterator = mapArg.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = (Entry) iterator.next(); Map keyOfMap = null; Map valueOfMap = null; if (entry.getKey() instanceof Map) { keyOfMap = (Map) entry.getKey(); } else { keyOfMap = TObject.asMap(SINGLE_VALUE_KEY, entry.getKey()); } if (entry.getValue() instanceof Map) { valueOfMap = (Map) entry.getValue(); } else { valueOfMap = TObject.asMap(SINGLE_VALUE_KEY, entry.getValue()); } Object keyObj = getObjectFromMap(genericType[0], keyOfMap, ignoreCase); Object valueObj = getObjectFromMap(genericType[1], valueOfMap, ignoreCase); mapObject.put(keyObj, valueObj); } }else{ mapObject.putAll(mapArg); } obj = (T)mapObject; } //Collection else if(isImpByInterface(clazz, Collection.class)){ Collection collectionObject = (Collection)newInstance(clazz); if(singleValue!=null){ if(genericType!=null){ for (Object listItem : (Collection)singleValue) { Map valueOfMap = null; if (listItem instanceof Map) { valueOfMap = (Map) listItem; } else { valueOfMap = TObject.asMap(SINGLE_VALUE_KEY, listItem); } Object item = getObjectFromMap(genericType[0], valueOfMap, ignoreCase); collectionObject.add(item); } }else{ collectionObject.addAll((Collection)singleValue); } } obj = (T)collectionObject; } //Array else if(clazz.isArray()){ Class arrayClass = clazz.getComponentType(); Object tempArrayObj = Array.newInstance(arrayClass, 0); return (T)((Collection)singleValue).toArray((Object[])tempArrayObj); } else { try { obj = (T) newInstance(clazz); } catch (InstantiationException e){ return null; } for(Entry<String,?> argEntry : mapArg.entrySet()){ String key = argEntry.getKey(); Object value = argEntry.getValue(); Field field = null; if(ignoreCase) { field = findFieldIgnoreCase(clazz, key); }else{ field = findField(clazz, key); } if(field!=null && !Modifier.isFinal(field.getModifiers())) { String fieldName = field.getName(); Class fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); try { //value fieldType classvalue if(value != null && fieldType != value.getClass()) { // JSON ,String value, String Collection, Map if( value instanceof String && ( isImpByInterface(fieldType, Map.class) || isImpByInterface(fieldType, Collection.class) || !TReflect.isBasicType(fieldType) ) ){ value = TString.toObject(value.toString(), fieldType); } // Map ,, else if (isImpByInterface(fieldType, Map.class) && value instanceof Map) { value = getObjectFromMap(fieldGenericType, (Map<String,?>)value, ignoreCase); } // Collection ,, else if (isImpByInterface(fieldType, Collection.class) && value instanceof Collection) { value = getObjectFromMap(fieldGenericType, TObject.asMap(SINGLE_VALUE_KEY, value), ignoreCase); } // Map, else if (!isImpByInterface(fieldType, Map.class)) { if (value instanceof Map) { value = getObjectFromMap(fieldType, (Map<String, ?>) value, ignoreCase); } else { value = getObjectFromMap(fieldType, TObject.asMap(SINGLE_VALUE_KEY, value), ignoreCase); } }else{ throw new ReflectiveOperationException("Conver field object error! Exception type: " + fieldType.getName() + ", Object type: "+ value.getClass().getName()); } } setFieldValue(obj, field, value); }catch(Exception e){ throw new ReflectiveOperationException("Fill object " + getClassName(obj.getClass()) + Global.CHAR_SHAPE+fieldName+" failed", e); } } } } return obj; } /** * Map * key * value * @param obj * @return Map * @throws ReflectiveOperationException */ public static Map<String, Object> getMapfromObject(Object obj) throws ReflectiveOperationException{ return getMapfromObject(obj, false); } /** * Map * key * value * @param obj * @param allField * @return Map * @throws ReflectiveOperationException */ public static Map<String, Object> getMapfromObject(Object obj, boolean allField) throws ReflectiveOperationException { LinkedHashMap<String, Object> mapResult = new LinkedHashMap<String, Object>(); if(obj==null || TReflect.isBasicType(obj.getClass())){ mapResult.put(null, obj); return mapResult; } if(obj.getClass().isAnnotationPresent(NotSerialization.class)){ return null; } // java if(TReflect.isBasicType(obj.getClass())){ mapResult.put(null, obj); } //java else if(isExtendsByClass(obj.getClass(),Date.class)){ mapResult.put(null,TDateTime.format((Date) obj, TDateTime.STANDER_DATETIME_TEMPLATE)); } // Collection else if(obj instanceof Collection){ Collection collection = new ArrayList(); for (Object collectionItem : (Collection)obj) { Map<String, Object> item = getMapfromObject(collectionItem, allField); collection.add((item.size() == 1 && item.containsKey(null)) ? item.get(null) : item); } mapResult.put(null, collection); } // Array else if(obj.getClass().isArray()){ Class arrayClass = obj.getClass().getComponentType(); Object targetArray = Array.newInstance(arrayClass, Array.getLength(obj)); for(int i=0;i<Array.getLength(obj);i++) { Object arrayItem = Array.get(obj, i); Map<String, Object> item = getMapfromObject(arrayItem, allField); Array.set(targetArray, i, (item.size()==1 && item.containsKey(null)) ? item.get(null) : item); } mapResult.put(null, targetArray); } // Atom else if (obj instanceof AtomicLong || obj instanceof AtomicInteger || obj instanceof AtomicBoolean) { mapResult.put(null, TReflect.invokeMethod(obj, "get")); } // BigDecimal else if (obj instanceof BigDecimal) { if(BigDecimal.ZERO.compareTo((BigDecimal)obj)==0){ obj = BigDecimal.ZERO; } mapResult.put(null, ((BigDecimal) obj).toPlainString()); } // Map else if(obj instanceof Map){ Map mapObject = (Map)obj; Map map = new HashMap(); Iterator iterator = mapObject.entrySet().iterator(); while (iterator.hasNext()) { Entry<?, ?> entry = (Entry<?, ?>) iterator.next(); Map<String, Object> keyItem = getMapfromObject(entry.getKey(), allField); Map<String, Object> valueItem = getMapfromObject(entry.getValue(), allField); Object key = (keyItem.size() == 1 && keyItem.containsKey(null)) ? keyItem.get(null) : keyItem; Object value = (valueItem.size() == 1 && valueItem.containsKey(null)) ? valueItem.get(null) : valueItem; map.put(key, value); } mapResult.put(null, map); } else { Field[] fields = TReflect.getFields(obj.getClass()); for(Field field : fields){ if (!allField) { if(field.isAnnotationPresent(NotSerialization.class)) { continue; } } String key = field.getName(); Object value = null; try { value = getFieldValue(obj, key); } catch (Exception e) { e.printStackTrace(); } if(value == null){ if(mapResult.get(key) == null) { mapResult.put(key, value); } }else if(!key.contains("$")){ Class valueClass = value.getClass(); if(TReflect.isBasicType(valueClass)){ if(mapResult.get(key) == null) { mapResult.put(key, value); } }else { Map resultMap = getMapfromObject(value, allField); if(resultMap.size()==1 && resultMap.containsKey(null)){ mapResult.put(key, resultMap.get(null)); }else{ mapResult.put(key, resultMap); } } } } } return mapResult; } /** * * * @param type * @param interfaceClass * @return */ public static boolean isImpByInterface(Class<?> type,Class<?> interfaceClass){ if(type==interfaceClass && interfaceClass.isInterface()){ return true; } return interfaceClass.isAssignableFrom(type); } /** * * * @param type * @param extendsClass * @return */ public static boolean isExtendsByClass(Class<?> type,Class<?> extendsClass){ if(type==extendsClass && !extendsClass.isInterface()){ return true; } return extendsClass.isAssignableFrom(type); } /** * * filters , // * @param clazz Class * @param filters * @return true: , false: */ public static boolean classChecker(Class clazz, Class[] filters){ int matchCount = 0; List<Annotation> annotations = TObject.asList(clazz.getAnnotations()); if(clazz.isAnonymousClass()) { return false; } for(Class filterClazz : filters){ if(clazz == filterClazz){ break; } if(filterClazz.isAnnotation() && clazz.isAnnotationPresent(filterClazz)){ matchCount++; }else if(filterClazz.isInterface() && TReflect.isImpByInterface(clazz, filterClazz)){ matchCount++; }else if(TReflect.isExtendsByClass(clazz, filterClazz)){ matchCount++; } } if(matchCount < filters.length){ return false; }else{ return true; } } /** * * @param type Class * @return */ public static List<Class> getAllSuperClass(Class<?> type){ if(type == null){ return null; } ArrayList<Class> classes = new ArrayList<Class>(); Class<?> superClass = type; do{ superClass = superClass.getSuperclass(); classes.addAll(Arrays.asList(superClass.getInterfaces())); classes.add(superClass); }while(superClass!=null && Object.class != superClass); return classes; } /** * json * @param clazz Class * @return json */ public static String getClazzJSONModel(Class clazz){ StringBuilder jsonStrBuilder = new StringBuilder(); if(TReflect.isBasicType(clazz)){ jsonStrBuilder.append(clazz.getName()); } else if(clazz.isArray()){ String clazzName = getClassName(clazz); clazzName = clazzName.substring(clazzName.lastIndexOf(Global.STR_POINT)+1,clazzName.length()-2)+"[]"; jsonStrBuilder.append(clazzName); } else { jsonStrBuilder.append(Global.STR_LC_BRACES); for (Field field : TReflect.getFields(clazz)) { jsonStrBuilder.append(Global.STR_QUOTE); jsonStrBuilder.append(field.getName()); jsonStrBuilder.append(Global.STR_QUOTE).append(Global.STR_COLON); String filedValueModel = getClazzJSONModel(field.getType()); if(filedValueModel.startsWith(Global.STR_LC_BRACES) && filedValueModel.endsWith(Global.STR_RC_BRACES)) { jsonStrBuilder.append(filedValueModel); jsonStrBuilder.append(Global.STR_COMMA); } else if(filedValueModel.startsWith(Global.STR_LS_BRACES) && filedValueModel.endsWith(Global.STR_RS_BRACES)) { jsonStrBuilder.append(filedValueModel); jsonStrBuilder.append(Global.STR_COMMA); } else { jsonStrBuilder.append(Global.STR_QUOTE); jsonStrBuilder.append(filedValueModel); jsonStrBuilder.append(Global.STR_QUOTE).append(Global.STR_COMMA); } } jsonStrBuilder.deleteCharAt(jsonStrBuilder.length()-1); jsonStrBuilder.append("}"); } return jsonStrBuilder.toString(); } /** * , Map * null * @param obj * @param fields * @return Map */ public static Map<String, Object> fieldFilter(Object obj, String ... fields) { Map<String, Object> resultMap = new LinkedHashMap<String, Object>(); for(String fieldFilter : fields){ int firstIndex = fieldFilter.indexOf(Global.STR_LS_BRACES); String field = firstIndex == -1? fieldFilter : fieldFilter.substring(0, firstIndex); ; Object value = null; //Map if(obj instanceof Map){ Map paramMap = (Map)obj; value = paramMap.get(field); } //List/Array else if(obj.getClass().isArray() || obj instanceof List) { if(obj.getClass().isArray()){ obj = TObject.asList((Object[])obj); } for(Object subObj : (List)obj){ fieldFilter(subObj, fields); } } //complex object else { try { value = TReflect.getFieldValue(obj, field); } catch (ReflectiveOperationException e) { value = null; } } if(firstIndex>1) { Map<String, Object> subResultMap = new LinkedHashMap<String, Object>(); String subFieldStr= fieldFilter.substring(firstIndex); subFieldStr = TString.removeSuffix(subFieldStr); subFieldStr = TString.removePrefix(subFieldStr); String[] subFieldArray = subFieldStr.split(","); for(String subField : subFieldArray) { Map<String, Object> data = fieldFilter(value, subField); subResultMap.putAll(data); } value = subResultMap; } resultMap.put(field, value); } return resultMap; } /** * (null, boolean, byte, char, double, float, int, long, short, string) * @param clazz Class * @return true: , false: */ public static boolean isBasicType(Class clazz) { Boolean isBasicType = CLASS_BASIC_TYPE.get(clazz); if(isBasicType==null) { if (clazz == null || clazz.isPrimitive() || clazz.getName().startsWith("java.lang")) { CLASS_BASIC_TYPE.put(clazz, true); isBasicType = true; } else { CLASS_BASIC_TYPE.put(clazz, false); isBasicType = false; } } return isBasicType; } /** * * @param object * @param type * @return true: , false: */ public static boolean isTypeOfArray(Object object, Type type){ return object.getClass().isArray() && object.getClass().getComponentType().equals(type); } private static List<String> systemPackages = TObject.asList("java.","jdk.","sun.","javax.","com.sun","com.oracle","javassist"); /** * JDK (java) * @param clazz Class * @return true: JDK , false:JDK */ public static boolean isSystemType(Class clazz){ if( clazz.isPrimitive()){ return true; } // class for(String systemPackage : systemPackages){ if(getClassName(clazz).startsWith(systemPackage)){ return true; } } return false; } /** * JDK (java) * @param className Class * @return true: JDK , false:JDK */ public static boolean isSystemType(String className) { if(className.indexOf(Global.STR_POINT)==-1){ return true; } // class for(String systemPackage : systemPackages){ if(className.startsWith(systemPackage)){ return true; } } return false; } /** * * @param primitiveType * @return */ public static String getPackageType(String primitiveType){ switch (primitiveType){ case "int": return "java.lang.Integer"; case "byte": return "java.lang.Byte"; case "short": return "java.lang.Short"; case "long": return "java.lang.Long"; case "float": return "java.lang.Float"; case "double": return "java.lang.Double"; case "char": return "java.lang.Character"; case "boolean": return "java.lang.Boolean"; default : return null; } } }
package org.nakedobjects.xat; import org.nakedobjects.object.DummyNakedValue; import org.nakedobjects.object.InternalCollection; import org.nakedobjects.object.control.ActionAbout; import org.nakedobjects.object.control.FieldAbout; import org.nakedobjects.object.control.Validity; import org.nakedobjects.object.defaults.AbstractNakedObject; import org.nakedobjects.object.defaults.value.Money; import org.nakedobjects.object.defaults.value.TextString; public class TestObjectExample extends AbstractNakedObject { private String result = null; private final TextString oneModifiable = new TextString(); private final InternalCollection collection = createInternalCollection(TestElement.class); private TestObjectExample fourDefault; public void actionOneDefault() { result = "one"; } public void actionTwoDefault(TestObjectExample param) { result = "two"; } public void aboutActionThreeInvisible(ActionAbout about) { about.invisible(); } public void aboutActionNineInvisible(ActionAbout about, TestObjectExample object) { about.invisible(); } public void actionThreeInvisible() {} public void actionNineInvisible(TestObjectExample object) {} public void aboutActionFourUnusable(ActionAbout about) { about.unusable(); } public void actionFourUnusable() {} public void aboutActionFiveInvisible(ActionAbout about, TestObjectExample param) { about.invisible(); } public void actionFiveInvisible(TestObjectExample param) {} public void aboutActionSixUnusable(ActionAbout about, TestObjectExample param) { about.unusable(); } public void actionSixUnusable(TestObjectExample param) {} public void aboutActionTenUnusable(ActionAbout about, TestObjectExample param, TestObjectExample param2, TextString param3) { about.unusable(); } public void actionTenUnusable(TestObjectExample param, TestObjectExample param2, TextString param3) {} public void actionSeven(TestObjectExample param1, TestObjectExample param2, TextString value) { result = value.stringValue(); } public void aboutActionEightInvisible(ActionAbout about, TestObjectExample param1, TestObjectExample param2, TextString param3) { about.invisible(); } public void actionEightInvisible(TestObjectExample param1, TestObjectExample param2, TextString param3) {} public TextString getOneModifiable() { return oneModifiable; } public void aboutTwoUnmodifiable(FieldAbout about) { about.unmodifiable(); } public DummyNakedValue getTwoUnmodifiable() { return new DummyNakedValue(); } public void aboutThreeInvisible(FieldAbout about) { about.invisible(); } public DummyNakedValue getThreeInvisible() { return new DummyNakedValue(); } public void associateFourDefault(TestObjectExample e) { result = e.toString(); fourDefault = e; } public InternalCollection getCollection() { return collection; } public TestObjectExample getFourDefault() { return fourDefault; } public void setFourDefault(TestObjectExample e) { throw new NakedAssertionFailedError(); } public void aboutFiveUnmodifiable(FieldAbout about, TestObjectExample e) { about.unmodifiable(); about.invisible(); } public TestObjectExample getFiveUnmodifiable() { // throw new NakedAssertionFailedError(); return null; } public void setFiveUnmodifiable(TestObjectExample e) { throw new NakedAssertionFailedError(); } public TestObjectExample getSixInvisible() { // throw new NakedAssertionFailedError(); return null; } public void setSixInvisible(TestObjectExample e) { throw new NakedAssertionFailedError(); } public void aboutSixInvisible(FieldAbout about, TestObjectExample e) { about.invisible(); } public String result() { return result; } public final Money amount = new Money(); public void validAmount(Validity validity) { validity.invalidOnCondition(amount.doubleValue() < 0.0, "amount must be positive"); } public Money getAmount() { return amount; } }
package nak.nakloidGUI.actions.files; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import nak.nakloidGUI.NakloidGUI; import nak.nakloidGUI.actions.AbstractAction; import nak.nakloidGUI.coredata.CoreData; import nak.nakloidGUI.coredata.CoreData.CoreDataSynthesisListener; import nak.nakloidGUI.coredata.NakloidIni; import nak.nakloidGUI.coredata.NakloidIni.ScoreMode; import nak.nakloidGUI.gui.MainWindow; public class ImportScoreAction extends AbstractAction { final private static String[] scoreExt = {"*.nak;*.ust;*.smf;*.mid","*.nak","*.ust","*.smf;*.mid"}; final private static String[] lyricsExt = {"*.txt"}; final private static String [] scoreFilterNames = {" (*.nak, *.ust, *.smf, *.mid)", "Nakloid Score File (*.nak)", "UTAU Sequence Text (*.ust)", "Standard MIDI File (*.smf, *.mid)"}; final private static String [] lyricsFilterNames = {" (*.txt)"}; public ImportScoreAction(MainWindow mainWindow, CoreData coreData) { super(mainWindow, coreData); setText(""); } @Override public void run() { if (coreData.getVoicesSize() < 1) { MessageDialog.openError(mainWindow.getShell(), "NakloidGUI", ""); return; } FileDialog openScoreDialog = new FileDialog(mainWindow.getShell(), SWT.OPEN); openScoreDialog.setFilterExtensions(scoreExt); openScoreDialog.setFilterNames(scoreFilterNames); String strScorePath = openScoreDialog.open(); if (strScorePath==null || strScorePath.isEmpty()) { return; } Path pathImportScore = Paths.get(strScorePath); if (!strScorePath.endsWith(".nak")) { try { CoreData tmpCoreData = new CoreData.Builder() .loadOtoIni(coreData.getVocalPath()) .build(); tmpCoreData.nakloidIni.input.path_input_score = pathImportScore; if (strScorePath.endsWith(".ust")) { tmpCoreData.nakloidIni.input.score_mode = ScoreMode.score_mode_ust; } else { tmpCoreData.nakloidIni.input.score_mode = ScoreMode.score_mode_smf; FileDialog openSmfDialog = new FileDialog(mainWindow.getShell(), SWT.OPEN); openSmfDialog.setFilterExtensions(lyricsExt); openSmfDialog.setFilterNames(lyricsFilterNames); String strLyricsPath = openSmfDialog.open(); if (strLyricsPath==null || strLyricsPath.isEmpty()) { return; } tmpCoreData.nakloidIni.input.path_lyrics = Paths.get(strLyricsPath); } tmpCoreData.nakloidIni.input.path_input_pitches = null; tmpCoreData.nakloidIni.input.pitches_mode = NakloidIni.PitchesMode.pitches_mode_none; tmpCoreData.nakloidIni.output.path_output_score = Paths.get(NakloidGUI.preferenceStore.getString("ini.input.path_input_score")); tmpCoreData.nakloidIni.output.path_output_pitches = Paths.get(NakloidGUI.preferenceStore.getString("ini.input.path_input_pitches")); Files.deleteIfExists(coreData.nakloidIni.input.path_input_pitches); tmpCoreData.synthesize(new CoreDataSynthesisListener() { @Override public void synthesisFinished() { try { coreData.reloadScoreAndPitches(); } catch (IOException e) { ErrorDialog.openError(mainWindow.getShell(), "NakloidGUI", "", new MultiStatus(".", IStatus.ERROR, Stream.of(e.getStackTrace()) .map(s->new Status(IStatus.ERROR, ".", "at "+s.getClassName()+": "+s.getMethodName())) .collect(Collectors.toList()).toArray(new Status[]{}), e.getLocalizedMessage(), e)); } coreData.reloadSongWaveform(); } }); } catch (IOException e) { ErrorDialog.openError(mainWindow.getShell(), "NakloidGUI", "", new MultiStatus(".", IStatus.ERROR, Stream.of(e.getStackTrace()) .map(s->new Status(IStatus.ERROR, ".", "at "+s.getClassName()+": "+s.getMethodName())) .collect(Collectors.toList()).toArray(new Status[]{}), e.getLocalizedMessage(), e)); } catch (InterruptedException e) { ErrorDialog.openError(mainWindow.getShell(), "NakloidGUI", "", new MultiStatus(".", IStatus.ERROR, Stream.of(e.getStackTrace()) .map(s->new Status(IStatus.ERROR, ".", "at "+s.getClassName()+": "+s.getMethodName())) .collect(Collectors.toList()).toArray(new Status[]{}), e.getLocalizedMessage(), e)); } } else { try { Files.copy(pathImportScore, coreData.getScorePath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { ErrorDialog.openError(mainWindow.getShell(), "NakloidGUI", "naktemporary", new MultiStatus(".", IStatus.ERROR, Stream.of(e.getStackTrace()) .map(s->new Status(IStatus.ERROR, ".", "at "+s.getClassName()+": "+s.getMethodName())) .collect(Collectors.toList()).toArray(new Status[]{}), e.getLocalizedMessage(), e)); } } NakloidGUI.preferenceStore.setValue("workspace.path_nar", ""); mainWindow.updateWindowName(); } }
// LIFReader.java package loci.formats; import java.awt.image.BufferedImage; import java.io.*; import java.util.Vector; /** * LIFReader is the file format reader for Leica LIF files. * * @author Melissa Linkert linkert at cs.wisc.edu */ public class LIFReader extends FormatReader { // -- Fields -- /** Current file. */ protected RandomAccessFile in; /** Flag indicating whether current file is little endian. */ protected boolean littleEndian; /** Number of image planes in the file. */ protected int numImages = 0; /** Offsets to memory blocks, paired with their corresponding description. */ protected Vector offsets; /** * Dimension information for each image. * The first index specifies the image number, and the second specifies * the dimension from the following list: * 0) width * 1) height * 2) Z * 3) T * 4) channels (1 or 3) * 5) bits per pixel */ protected int[][] dims; // -- Constructor -- /** Constructs a new Leica LIF reader. */ public LIFReader() { super("Leica Image File Format", "lif"); } // -- FormatReader API methods -- /** Checks if the given block is a valid header for a LIF file. */ public boolean isThisType(byte[] block) { return block[0] == 0x70; } /** Determines the number of images in the given LIF file. */ public int getImageCount(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); return numImages; } /** Obtains the specified image from the given LIF file. */ public BufferedImage open(String id, int no) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (no < 0 || no >= getImageCount(id)) { throw new FormatException("Invalid image number: " + no); } int ndx = 0; int sum = 0; for (int i=0; i<dims.length; i++) { sum += (dims[i][2] * dims[i][3]); if (no < sum) { ndx = i; i = dims.length; } } int width = dims[ndx][0]; int height = dims[ndx][1]; int bps = dims[ndx][5]; double bytesPerPixel = bps / 8; int offset = ((Long) offsets.get(0)).intValue(); in.seek((long) (offset + (width * height * bytesPerPixel * no))); byte[] data = new byte[(int) (width * height * bytesPerPixel * 3)]; in.read(data); // pack the data appropriately if (bps == 8) { return ImageTools.makeImage(data, width, height, 3, false); } else if (bps == 16) { short[] shortData = new short[width*height*3]; for (int i=0; i<data.length; i+=2) { shortData[i/2] = DataTools.bytesToShort(data, i, littleEndian); } return ImageTools.makeImage(shortData, width, height, 3, false); } else if (bps == 32) { float[] floatData = new float[width*height*3]; for (int i=0; i<data.length; i+=4) { floatData[i/4] = Float.intBitsToFloat(DataTools.bytesToInt(data, i, littleEndian)); } return ImageTools.makeImage(floatData, width, height, 3, false); } else { throw new FormatException("Sorry, bits per sample " + bps + " not supported"); } } /** Closes any open files. */ public void close() throws FormatException, IOException { if (in != null) in.close(); in = null; currentId = null; } /** Initializes the given LIF file. */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); offsets = new Vector(); in = new RandomAccessFile(id, "r"); littleEndian = true; // read the header byte[] header = new byte[8]; in.read(header); if ((header[0] != 0x70) && (header[3] != 0x70)) { throw new FormatException(id + " is not a valid Leica LIF file"); } int chunkLength = DataTools.bytesToInt(header, 4, 4, littleEndian); // read and parse the XML description byte[] xmlChunk = new byte[chunkLength]; in.read(xmlChunk); if (xmlChunk[0] != 0x2a) { throw new FormatException("Invalid XML description"); } // number of Unicode characters in the XML block int nc = DataTools.bytesToInt(xmlChunk, 1, 4, littleEndian); String xml = new String(xmlChunk, 5, nc*2); xml = LeicaReader.stripString(xml); while (in.getFilePointer() < in.length()) { byte[] four = new byte[4]; in.read(four); int check = DataTools.bytesToInt(four, littleEndian); if (check != 0x70) { throw new FormatException("Invalid Memory Block"); } in.read(four); int memLength = DataTools.bytesToInt(four, littleEndian); if (in.read() != 0x2a) { throw new FormatException("Invalid Memory Description"); } in.read(four); int blockLength = DataTools.bytesToInt(four, littleEndian); if (in.read() != 0x2a) { throw new FormatException("Invalid Memory Description"); } in.read(four); int descrLength = DataTools.bytesToInt(four, littleEndian); byte[] memDescr = new byte[2*descrLength]; in.read(memDescr); String descr = new String(memDescr); descr = LeicaReader.stripString(descr); if (blockLength > 0) { offsets.add(new Long(in.getFilePointer())); } in.skipBytes(blockLength); } numImages = offsets.size(); dims = new int[numImages][6]; initMetadata(xml); } // -- Utility methods -- /** Parses a string of XML and puts the values in a Hashtable. */ private void initMetadata(String xml) { Vector elements = new Vector(); // first parse each element in the XML string while (xml.length() > 2) { String el = xml.substring(1, xml.indexOf(">")); xml = xml.substring(xml.indexOf(">") + 1); elements.add(el); } // the first element contains version information String token = (String) elements.get(0); String key = token.substring(0, token.indexOf("\"")); String value = token.substring(token.indexOf("\"") + 1, token.length()-1); metadata.put(key, value); int ndx = 1; int imageCounter = -2; int dimCounter = 0; int lutCounter = 0; while (ndx < elements.size()) { token = (String) elements.get(ndx); // only try to parse the element if we know it // contains a key/value pair if (token.indexOf("=") != -1) { while (token.length() > 2) { if (key.equals("Element Name")) { imageCounter++; dimCounter = 0; lutCounter = 0; } key = token.substring(0, token.indexOf("\"") - 1); value = token.substring(token.indexOf("\"") + 1, token.indexOf("\"", token.indexOf("\"") + 1)); key = key.trim(); value = value.trim(); if (key.equals("NumberOfElements")) { dims[imageCounter][dimCounter] = Integer.parseInt(value); dimCounter++; if (dimCounter == 6) dimCounter = 0; } if (key.equals("Resolution")) { int val = Integer.parseInt(value); if ((val % 8) != 0) val += (8 - (val % 8)); dims[imageCounter][5] = val; } if (key.equals("LUTName")) lutCounter++; if (lutCounter == 3) { dims[imageCounter][4] = lutCounter; lutCounter = 0; } token = token.substring(token.indexOf("\"", token.indexOf("\"") + 1) + 1); metadata.put(key + " (image " + imageCounter + ")", value); } } ndx++; } int originalNumImages = numImages; for (int i=1; i<=originalNumImages; i++) { if (dims[i-1][2] == 0) dims[i-1][2] = 1; if (dims[i-1][3] == 0) dims[i-1][3] = 1; numImages += ((dims[i-1][2]*dims[i-1][3]) - 1); } // initialize OME-XML if (ome != null) { String type = "int8"; switch (dims[dims.length - 1][5]) { case 12: type = "int16"; break; case 16: type = "int16"; break; case 32: type = "float"; break; } int z = 0; int t = 0; for (int i=0; i<dims.length; i++) { z += (dims[i][2] == 1) ? 0 : dims[i][2]; t += (dims[i][3] == 1) ? 0 : dims[i][3]; } if (t == 0) t++; if (z == 0) z++; while ((z*t) < numImages) { z++; } OMETools.setPixels(ome, new Integer(dims[dims.length - 1][0]), // SizeX new Integer(dims[dims.length - 1][1]), // SizeY new Integer(z), // SizeZ new Integer(1), // SizeC new Integer(t), // SizeT type, // PixelType new Boolean(!littleEndian), // BigEndian "XYZTC"); // DimensionOrder } } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { new LIFReader().testRead(args); } }
package xmlviewer; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; import java.io.File; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import static xmlviewer.Utils.XML_FILE_FILTER; /** * * @author Phystem */ public class XmlUI extends javax.swing.JFrame { DefaultListModel xmlListModel; TreePopupMenu popupMenu; Action onValueChangeOnAction; /** * Creates new form XmlUI */ public XmlUI() { initComponents(); popupMenu = new TreePopupMenu(); xmlListModel = new DefaultListModel(); xmlList.setModel(xmlListModel); xmlFileChooser.setMultiSelectionEnabled(true); setSize(700, 700); listTreeSplitpane.setDividerLocation(0.5); treeTableSplitPane.setDividerLocation(0.7); setLocationRelativeTo(null); initListeners(); } private void initListeners() { xmlTree.getCellEditor().addCellEditorListener(new CellEditorListener() { @Override public void editingStopped(ChangeEvent e) { renameNode(); } @Override public void editingCanceled(ChangeEvent e) { } }); xmlTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { int row = xmlTree.getClosestRowForLocation(e.getX(), e.getY()); xmlTree.setSelectionRow(row); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); int shortcut = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); xmlTree.getInputMap(JComponent.WHEN_FOCUSED).put( KeyStroke.getKeyStroke(KeyEvent.VK_N, shortcut), "AddNew"); xmlTree.getActionMap().put("AddNew", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { addNodeActionPerformed(null); } }); xmlTree.getInputMap(JComponent.WHEN_FOCUSED).put( KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "Delete"); xmlTree.getActionMap().put("Delete", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { deleteNodeActionPerformed(null); } }); xmlList.getInputMap(JComponent.WHEN_FOCUSED).put( KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "Delete"); xmlList.getActionMap().put("Delete", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (xmlList.getSelectedIndices().length > 0) { int[] indices = xmlList.getSelectedIndices(); Arrays.sort(indices); for (int i = indices.length - 1; i >= 0; i xmlListModel.remove(indices[i]); } } } }); xmlList.setTransferHandler(new TransferHandler() { @Override public boolean canImport(TransferHandler.TransferSupport info) { return info.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } @Override public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } if (!canImport(info)) { return false; } // Check for FileList flavor if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { displayDropLocation("List doesn't accept a drop of this type."); return false; } // Get the fileList that is being dropped. Transferable t = info.getTransferable(); List<File> data; try { data = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); if (data == null) { return false; } } catch (Exception e) { return false; } checkAndAddFiles((File[]) data.toArray()); return true; } private void displayDropLocation(String string) { System.out.println(string); } }); onValueChangeOnAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (applyChangesMenuItem.isSelected()) { modifyValueInOthers(); } } }; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { xmlFileChooser = new javax.swing.JFileChooser(); listTreeSplitpane = new javax.swing.JSplitPane(); treeTableSplitPane = new javax.swing.JSplitPane(); treePanel = new javax.swing.JPanel(); treeScrollPane = new javax.swing.JScrollPane(); xmlTree = new javax.swing.JTree(); tablePanel = new javax.swing.JPanel(); tableScrollPane = new javax.swing.JScrollPane(); xmlPropTable = new javax.swing.JTable(); listScrollPane = new javax.swing.JScrollPane(); xmlList = new javax.swing.JList(); toolBar = new javax.swing.JToolBar(); loadXml = new javax.swing.JButton(); saveXml = new javax.swing.JButton(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767)); addNode = new javax.swing.JButton(); renameNode = new javax.swing.JButton(); deleteNode = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); loadMenuItem = new javax.swing.JMenuItem(); saveMenuItem = new javax.swing.JMenuItem(); reloadMenuItem = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); quitMenuItem = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); addNodeMenuItem = new javax.swing.JMenuItem(); renameNodeMenuItem = new javax.swing.JMenuItem(); deleteNodesMenuItem = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); applyChangesMenuItem = new javax.swing.JCheckBoxMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); expandNodes = new javax.swing.JMenuItem(); collapseNodes = new javax.swing.JMenuItem(); xmlFileChooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); xmlFileChooser.setDialogTitle("Select any XML files or folder which contains XML"); xmlFileChooser.setFileFilter(new FileNameExtensionFilter("Xml Files","xml")); xmlFileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Simple Xml Viewer"); treeTableSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); treePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Xml Tree View")); treePanel.setLayout(new java.awt.BorderLayout()); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root"); xmlTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); xmlTree.setEditable(true); xmlTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(javax.swing.event.TreeSelectionEvent evt) { xmlTreeValueChanged(evt); } }); treeScrollPane.setViewportView(xmlTree); treePanel.add(treeScrollPane, java.awt.BorderLayout.CENTER); treeTableSplitPane.setTopComponent(treePanel); tablePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Node Details")); tablePanel.setLayout(new java.awt.BorderLayout()); xmlPropTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"Name", null}, {"Value", null}, {"Xpath", null}, {"Atrribute", null} }, new String [] { "Attribute", "Value" } )); tableScrollPane.setViewportView(xmlPropTable); if (xmlPropTable.getColumnModel().getColumnCount() > 0) { xmlPropTable.getColumnModel().getColumn(0).setMinWidth(70); xmlPropTable.getColumnModel().getColumn(0).setPreferredWidth(70); xmlPropTable.getColumnModel().getColumn(0).setMaxWidth(100); } tablePanel.add(tableScrollPane, java.awt.BorderLayout.CENTER); treeTableSplitPane.setRightComponent(tablePanel); listTreeSplitpane.setRightComponent(treeTableSplitPane); xmlList.setBorder(javax.swing.BorderFactory.createTitledBorder("Xml Files")); xmlList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); xmlList.setToolTipText("<html>\nYou can drag and drop xml files/folders in to the list as well.<br/>\nRemove Unwanted Xmls by selecting them and press the Delete key\n</html>"); xmlList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { xmlListValueChanged(evt); } }); listScrollPane.setViewportView(xmlList); listTreeSplitpane.setLeftComponent(listScrollPane); getContentPane().add(listTreeSplitpane, java.awt.BorderLayout.CENTER); toolBar.setFloatable(false); toolBar.setRollover(true); loadXml.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/load.png"))); // NOI18N loadXml.setText("Load Xml"); loadXml.setFocusable(false); loadXml.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); loadXml.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadXmlActionPerformed(evt); } }); toolBar.add(loadXml); saveXml.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/save.png"))); // NOI18N saveXml.setText("Save Xml"); saveXml.setFocusable(false); saveXml.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); saveXml.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveXmlActionPerformed(evt); } }); toolBar.add(saveXml); toolBar.add(filler1); addNode.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/add.png"))); // NOI18N addNode.setText("Add Node"); addNode.setToolTipText("Add a node to the selected Node [Ctrl/Cmd + N]"); addNode.setFocusable(false); addNode.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); addNode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addNodeActionPerformed(evt); } }); toolBar.add(addNode); renameNode.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/edit.png"))); // NOI18N renameNode.setText("Rename Node"); renameNode.setToolTipText("Rename the selected Node [F2]"); renameNode.setFocusable(false); renameNode.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); renameNode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renameNodeActionPerformed(evt); } }); toolBar.add(renameNode); deleteNode.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delete.png"))); // NOI18N deleteNode.setText("Delete Node"); deleteNode.setToolTipText("Delete the selected nodes [Delete]"); deleteNode.setFocusable(false); deleteNode.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); deleteNode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteNodeActionPerformed(evt); } }); toolBar.add(deleteNode); getContentPane().add(toolBar, java.awt.BorderLayout.NORTH); jMenu1.setText("File"); loadMenuItem.setText("Load"); loadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadMenuItemActionPerformed(evt); } }); jMenu1.add(loadMenuItem); saveMenuItem.setText("Save"); saveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveMenuItemActionPerformed(evt); } }); jMenu1.add(saveMenuItem); reloadMenuItem.setText("Reload"); reloadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { reloadMenuItemActionPerformed(evt); } }); jMenu1.add(reloadMenuItem); jMenu1.add(jSeparator2); quitMenuItem.setText("Quit"); quitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { quitMenuItemActionPerformed(evt); } }); jMenu1.add(quitMenuItem); jMenuBar1.add(jMenu1); jMenu2.setText("Options"); addNodeMenuItem.setText("Add Node"); addNodeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addNodeMenuItemActionPerformed(evt); } }); jMenu2.add(addNodeMenuItem); renameNodeMenuItem.setText("Rename Node"); renameNodeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renameNodeMenuItemActionPerformed(evt); } }); jMenu2.add(renameNodeMenuItem); deleteNodesMenuItem.setText("Delete Nodes"); deleteNodesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteNodesMenuItemActionPerformed(evt); } }); jMenu2.add(deleteNodesMenuItem); jMenu2.add(jSeparator1); applyChangesMenuItem.setText("Apply NLC to All"); applyChangesMenuItem.setToolTipText("Apply Node Level Changes like Node Text change,Attribute value changes to other loaded xmls"); jMenu2.add(applyChangesMenuItem); jMenu2.add(jSeparator3); expandNodes.setText("Expand All"); expandNodes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { expandNodesActionPerformed(evt); } }); jMenu2.add(expandNodes); collapseNodes.setText("Collapse All"); collapseNodes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { collapseNodesActionPerformed(evt); } }); jMenu2.add(collapseNodes); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); pack(); }// </editor-fold>//GEN-END:initComponents private void loadXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadXmlActionPerformed int val = xmlFileChooser.showOpenDialog(this); if (val == JFileChooser.APPROVE_OPTION) { File[] selectedFile = xmlFileChooser.getSelectedFiles(); checkAndAddFiles(selectedFile); } }//GEN-LAST:event_loadXmlActionPerformed private void xmlListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_xmlListValueChanged if (!evt.getValueIsAdjusting()) { if (xmlList.getSelectedIndex() != -1) { SimpleXmlModel model = (SimpleXmlModel) xmlListModel.get(xmlList.getSelectedIndex()); xmlTree.setModel(model.treeModel); XmlTreeNode root = (XmlTreeNode) model.treeModel.getRoot(); xmlTree.setSelectionPath(new TreePath(root.getFirstLeaf().getPath())); } } }//GEN-LAST:event_xmlListValueChanged private void xmlTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_xmlTreeValueChanged Object previous = evt.getOldLeadSelectionPath(); if (previous != null) { if (previous instanceof XmlTreeNode) { XmlTreeNode previousNode = (XmlTreeNode) previous; previousNode.setOnValueChangeAction(null); } } Object selected = evt.getPath().getLastPathComponent(); if (selected instanceof XmlTreeNode) { XmlTreeNode selectedNode = (XmlTreeNode) selected; xmlPropTable.setModel(selectedNode); selectedNode.setOnValueChangeAction(onValueChangeOnAction); } }//GEN-LAST:event_xmlTreeValueChanged private void addNodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNodeActionPerformed XmlTreeNode node = getSelectedNode(); if (node != null) { DefaultTreeModel model = (DefaultTreeModel) xmlTree.getModel(); XmlTreeNode nNode = new XmlTreeNode("New Node"); model.insertNodeInto(nNode, node, node.getChildCount()); addNodeInOthers(node.getXpath(), nNode.getXpath()); } }//GEN-LAST:event_addNodeActionPerformed private void deleteNodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteNodeActionPerformed XmlTreeNode[] nodes = getSelectedNodes(); if (nodes != null) { DefaultTreeModel model = (DefaultTreeModel) xmlTree.getModel(); for (XmlTreeNode node : nodes) { deleteNodeInOthers(node.getXpath()); model.removeNodeFromParent(node); } } }//GEN-LAST:event_deleteNodeActionPerformed private void renameNodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameNodeActionPerformed XmlTreeNode node = getSelectedNode(); if (node != null) { xmlTree.startEditingAtPath(new TreePath(node.getPath())); } }//GEN-LAST:event_renameNodeActionPerformed private void saveXmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveXmlActionPerformed xmlTree.stopEditing(); for (int i = 0; i < xmlListModel.size(); i++) { SimpleXmlModel sModel = (SimpleXmlModel) xmlListModel.get(i); sModel.save(); } System.out.println("Saved successfully"); }//GEN-LAST:event_saveXmlActionPerformed private void loadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMenuItemActionPerformed loadXmlActionPerformed(evt); }//GEN-LAST:event_loadMenuItemActionPerformed private void saveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMenuItemActionPerformed saveXmlActionPerformed(evt); }//GEN-LAST:event_saveMenuItemActionPerformed private void reloadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reloadMenuItemActionPerformed xmlTree.stopEditing(); for (int i = 0; i < xmlListModel.size(); i++) { SimpleXmlModel sModel = (SimpleXmlModel) xmlListModel.get(i); sModel.reload(); } xmlList.setSelectedIndex(xmlListModel.getSize() - 1); }//GEN-LAST:event_reloadMenuItemActionPerformed private void quitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitMenuItemActionPerformed this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); }//GEN-LAST:event_quitMenuItemActionPerformed private void addNodeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNodeMenuItemActionPerformed addNodeActionPerformed(evt); }//GEN-LAST:event_addNodeMenuItemActionPerformed private void renameNodeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renameNodeMenuItemActionPerformed renameNodeActionPerformed(evt); }//GEN-LAST:event_renameNodeMenuItemActionPerformed private void deleteNodesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteNodesMenuItemActionPerformed deleteNodeActionPerformed(evt); }//GEN-LAST:event_deleteNodesMenuItemActionPerformed private void expandNodesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_expandNodesActionPerformed Utils.expandTree(xmlTree, true); }//GEN-LAST:event_expandNodesActionPerformed private void collapseNodesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_collapseNodesActionPerformed Utils.expandTree(xmlTree, false); }//GEN-LAST:event_collapseNodesActionPerformed private void checkAndAddFiles(File[] files) { for (File file : files) { if (file.isDirectory()) { File[] xmlFiles = file.listFiles(XML_FILE_FILTER); if (xmlFiles != null) { for (File xmlFile : xmlFiles) { checkAndAdd(xmlFile); } xmlList.setSelectedIndex(xmlListModel.getSize() - 1); } } else if (file.getName().endsWith(".xml")) { checkAndAdd(file); xmlList.setSelectedIndex(xmlListModel.getSize() - 1); } } } private void addNodeInOthers(String parentXpath, String childXpath) { int index = xmlList.getSelectedIndex(); for (int i = 0; i < xmlListModel.size(); i++) { if (i != index) { DefaultTreeModel model = ((SimpleXmlModel) xmlListModel.get(i)).treeModel; XmlTreeNode node = getMatchingNodeByXpath(model, parentXpath); if (node != null) { Boolean doContinue = false; for (int j = 0; j < node.getChildCount(); j++) { if (((XmlTreeNode) node.getChildAt(j)).getXpath() .equals(childXpath)) { doContinue = true; break; } } if (doContinue) { continue; } while (true) { XmlTreeNode nNode = new XmlTreeNode("New Node"); model.insertNodeInto(nNode, node, node.getChildCount()); if (nNode.getXpath().equals(childXpath)) { break; } } } } } } private XmlTreeNode getMatchingNodeByXpath(DefaultTreeModel model, String xpath) { XmlTreeNode root = (XmlTreeNode) model.getRoot(); Enumeration e = root.preorderEnumeration(); while (e.hasMoreElements()) { XmlTreeNode node = (XmlTreeNode) e.nextElement(); if (node.getXpath().equals(xpath)) { return node; } } return null; } private void deleteNodeInOthers(String xpath) { int index = xmlList.getSelectedIndex(); for (int i = 0; i < xmlListModel.size(); i++) { if (i != index) { DefaultTreeModel model = ((SimpleXmlModel) xmlListModel.get(i)).treeModel; XmlTreeNode node = getMatchingNodeByXpath(model, xpath); if (node != null) { model.removeNodeFromParent(node); } } } } private void renameNode() { XmlTreeNode node = getSelectedNode(); String value = xmlTree.getCellEditor().getCellEditorValue().toString(); if (!node.getName().equals(value)) { renameNodeInOthers(node.getXpath(), value); node.setName(value); ((DefaultTreeModel) xmlTree.getModel()).reload(node); } } private void renameNodeInOthers(String xpath, String newVal) { int index = xmlList.getSelectedIndex(); for (int i = 0; i < xmlListModel.size(); i++) { if (i != index) { DefaultTreeModel model = ((SimpleXmlModel) xmlListModel.get(i)).treeModel; XmlTreeNode node = getMatchingNodeByXpath(model, xpath); if (node != null) { node.setName(newVal); } } } } private void modifyValueInOthers() { XmlTreeNode node = getSelectedNode(); modifyValueInOthers(node.getXpath()); } private void modifyValueInOthers(String xpath) { int index = xmlList.getSelectedIndex(); for (int i = 0; i < xmlListModel.size(); i++) { if (i != index) { DefaultTreeModel model = ((SimpleXmlModel) xmlListModel.get(i)).treeModel; XmlTreeNode node = getMatchingNodeByXpath(model, xpath); if (node != null) { node.modifyValueByAction(onValueChangeOnAction); } } } } private XmlTreeNode getSelectedNode() { XmlTreeNode[] nodes = getSelectedNodes(); if (nodes != null) { return nodes[0]; } return null; } private XmlTreeNode[] getSelectedNodes() { TreePath[] paths = xmlTree.getSelectionPaths(); if (paths != null && paths.length > 0) { XmlTreeNode[] nodes = new XmlTreeNode[paths.length]; int i = 0; for (TreePath path : paths) { Object node = path.getLastPathComponent(); if (node instanceof XmlTreeNode) { nodes[i++] = (XmlTreeNode) node; } } return nodes; } return null; } private void checkAndAdd(File file) { SimpleXmlModel sFile = new SimpleXmlModel(file); for (int i = 0; i < xmlListModel.size(); i++) { if (xmlListModel.get(i).equals(sFile)) { System.out.println(file + " - File Already Loaded"); return; } } xmlListModel.addElement(sFile); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(XmlUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(XmlUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(XmlUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(XmlUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { XmlUI xml = new XmlUI(); xml.setVisible(true); xml.loadXmlActionPerformed(null); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addNode; private javax.swing.JMenuItem addNodeMenuItem; private javax.swing.JCheckBoxMenuItem applyChangesMenuItem; private javax.swing.JMenuItem collapseNodes; private javax.swing.JButton deleteNode; private javax.swing.JMenuItem deleteNodesMenuItem; private javax.swing.JMenuItem expandNodes; private javax.swing.Box.Filler filler1; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JScrollPane listScrollPane; private javax.swing.JSplitPane listTreeSplitpane; private javax.swing.JMenuItem loadMenuItem; private javax.swing.JButton loadXml; private javax.swing.JMenuItem quitMenuItem; private javax.swing.JMenuItem reloadMenuItem; private javax.swing.JButton renameNode; private javax.swing.JMenuItem renameNodeMenuItem; private javax.swing.JMenuItem saveMenuItem; private javax.swing.JButton saveXml; private javax.swing.JPanel tablePanel; private javax.swing.JScrollPane tableScrollPane; private javax.swing.JToolBar toolBar; private javax.swing.JPanel treePanel; private javax.swing.JScrollPane treeScrollPane; private javax.swing.JSplitPane treeTableSplitPane; private javax.swing.JFileChooser xmlFileChooser; private javax.swing.JList xmlList; private javax.swing.JTable xmlPropTable; private javax.swing.JTree xmlTree; // End of variables declaration//GEN-END:variables class TreePopupMenu extends JPopupMenu implements ActionListener { public TreePopupMenu() { int shortcut = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); create("Add Node", KeyStroke.getKeyStroke(KeyEvent.VK_N, shortcut)); create("Rename Node", KeyStroke.getKeyStroke(KeyEvent.VK_F2, shortcut)); create("Delete Nodes", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); addSeparator(); create("Expand All", null); create("Collapse All", null); } private void create(String text, KeyStroke key) { JMenuItem item = new JMenuItem(text); item.setAccelerator(key); item.addActionListener(this); add(item); } @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "Add Node": addNodeActionPerformed(null); break; case "Rename Node": renameNodeActionPerformed(null); break; case "Delete Nodes": deleteNodeActionPerformed(null); break; case "Expand All": Utils.expandTree(xmlTree, true); break; case "Collapse All": Utils.expandTree(xmlTree, false); break; } } } }
/* 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.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.templates.Autons.*; import java.util.Calendar; /** * 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 { public static String cumulativeErrorList = ""; public static void handleException(Exception e, String from) { cumulativeErrorList += "{EXCEPTION FROM " + from + "}\n"; DriverStation ds = null; try { ds = DriverStation.getInstance(); } catch (Exception u) { } if (ds != null) { cumulativeErrorList += "\tmatch time\t" + ds.getMatchTime() + "\n"; } cumulativeErrorList += e.getClass() + "\n\t" + e.getMessage() + "\n" + "\t" + e + "\n\n\n"; try { FileWrite.writeFile("exceptions.txt", cumulativeErrorList); } catch (Exception u) { } System.out.println("EXCEPTIONZ!!!!!!"); System.out.println(cumulativeErrorList); } public static String logData = ""; public static boolean shooterInManualMode = false; public static boolean targetInManualMode = true; public static boolean previousShooterLeft = false; public static boolean previousShooterRight = false; public static Timer timer; public static int frames; /** * 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(); RobotDrive.initialize(); RobotPickup.initialize(); RobotShoot.initialize(); RobotVision.initialize(); RobotAuton.initialize(); ControlBox.initialize(); System.out.println("Initialized"); //// ADDED: UNDERGLOW FROM THE LINE BELOW RobotLights.underglowOn(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { try { RobotShoot.useAutomatic(); runCompressor(); RobotAuton.update(); RobotDrive.update(); RobotPickup.update(); // TODO: UNDISABLE WHEN IT CAN DRIVE AGAIN RobotShoot.update(); DashboardPut.put(); } catch (Exception e) { handleException(e, "autonomousPeriodic"); } } public void teleopInit() { SmartDashboard.putNumber("Target Ticks", 1200); RobotDrive.enableSmoothing(); RobotLights.underglowOn(); timer = new Timer(); timer.start(); frames = 0; } public void disabledInit() { StandardOneBallAuton.timer.stop(); StandardOneBallAuton.timer.reset(); StandardOneBallAuton.secondTimer.stop(); StandardOneBallAuton.secondTimer.reset(); RobotLights.underglowOn(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { try { frames++; //System.out.println("FPS: " + frames / timer.get()); if (RobotShoot.gameTime.get() == 0) { RobotShoot.gameTime.start(); } //SmartDashboard.putBoolean("shooter AUTO ENCODER", ControlBox.getTopSwitch(3)); if (!targetInManualMode) { //Automatic targetting Mode (Using camera to figure out encoder) RobotShoot.setTargetTicks(RobotVision.getEncoder()); // reinstated the vision's encoder //RobotShoot.setTargetTicks(1300); } else { //Manual targetting mode (using driver to tap left and right) if (Gamepad.secondary.getA()) { RobotShoot.setTargetTicks(1000); } if (Gamepad.secondary.getB()) { RobotShoot.setTargetTicks(1300); } if (Gamepad.secondary.getDPadLeft()) { if (!previousShooterLeft) { RobotShoot.adjustTargetDown(); } previousShooterLeft = true; } else { previousShooterLeft = false; } if (Gamepad.secondary.getDPadRight()) { if (!previousShooterRight) { RobotShoot.adjustTargetUp(); } previousShooterRight = true; } else { previousShooterRight = false; } } ControlBox.update(); RobotDrive.update(); RobotPickup.update(); RobotShoot.update(); RobotPickup.moveToShootPosition(); RobotTeleop.update(); //SmartDashboard.putBoolean("TOP SWITCH TWO", ControlBox.getTopSwitch(2)); if (!shooterInManualMode) { RobotShoot.useAutomatic(); } else { RobotShoot.useManual(); } if (Gamepad.secondary.getBack()) { shooterInManualMode = true; } if (Gamepad.secondary.getStart()) { shooterInManualMode = false; } if (Gamepad.primary.getBack()) { targetInManualMode = true; } if (Gamepad.primary.getStart()) { targetInManualMode = false; } if (Gamepad.primary.getX() && Gamepad.primary.getY()) { RobotShoot.zeroedBefore = false; } runCompressor(); DashboardPut.put(); } catch (Exception e) { handleException(e, "teleopPeriodic"); } } private int counterOnTest; //Used in testPeriodic, testInit for debug. /** * This function is called periodically during test mode */ public void testPeriodic() { runCompressor(); DashboardPut.put(); RobotPickup.closeRollerArm(); if (counterOnTest <= 15) { RobotActuators.shooterWinch.set(-0.3); RobotActuators.latchRelease.set(false); if (!RobotSensors.shooterAtBack.get()) { counterOnTest++; } } else { RobotActuators.latchRelease.set(true); } if (counterOnTest >= 16 && counterOnTest <= 50) { RobotActuators.shooterWinch.set(0.3); counterOnTest++; RobotActuators.latchRelease.set(true); } if (counterOnTest >= 51) { RobotActuators.shooterWinch.set(0.0); } // CHANGED: from RobotDrive.stopDrive(); RobotActuators.leftDrive.set(0.0); RobotActuators.rightDrive.set(0.0); System.out.println("counterOnTest: " + counterOnTest); } public void testInit() { counterOnTest = 0; } private void runCompressor() { SmartDashboard.putBoolean("Pressure Switch", RobotSensors.pressureSwitch.get()); 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"); } public void disabledPeriodic() { try { RobotDrive.stopDrive(); RobotShoot.stopMotors(); AutonZero.reset(); DashboardPut.put(); //maxTrueCount = 0; if (logData.length() != 0) { FileWrite.writeFile("log" + Calendar.HOUR + "_" + Calendar.MINUTE + ".txt", logData); } logData = ""; } catch (Exception e) { handleException(e, "disabledPeriodic"); } } public void autonomousInit() { RobotShoot.reset(); RobotAuton.initialize(); RobotLights.underglowOn(); } }
package example; //-*- mode:java; encoding:utf8n; coding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class MainPanel extends JPanel{ private final JTextArea log = new JTextArea(); private final JTextField field = new JTextField(24); private final JCheckBox check1 = new JCheckBox("Change !dir.exists() case"); private final JCheckBox check2 = new JCheckBox("isParent reset?"); private final JPanel p = new JPanel(new GridBagLayout()); private final JFileChooser fc0 = new JFileChooser(); private final JFileChooser fc1 = new JFileChooser(); private final JFileChooser fc2 = new JFileChooser() { @Override public void setCurrentDirectory(File dir) { if(dir!=null && !dir.exists()) { this.setCurrentDirectory(dir.getParentFile()); } super.setCurrentDirectory(dir); } }; @Override public void updateUI() { super.updateUI(); if(fc0!=null) SwingUtilities.updateComponentTreeUI(fc0); if(fc1!=null) SwingUtilities.updateComponentTreeUI(fc1); if(fc2!=null) SwingUtilities.updateComponentTreeUI(fc2); } public MainPanel() { super(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder("JFileChooser.DIRECTORIES_ONLY")); fc0.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); try{ field.setText(new File(".").getCanonicalPath()); }catch(Exception ex) { ex.printStackTrace(); } GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.gridheight = 1; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 0, 0, 0); p.add(field, c); c.gridy++; c.gridwidth = 1; p.add(new JButton(new AbstractAction("setCurrentDirectory") { @Override public void actionPerformed(ActionEvent e) { File f = new File(field.getText().trim()); JFileChooser fc = check1.isSelected()?fc2:fc0; fc.setCurrentDirectory(f); int retvalue = fc.showOpenDialog(p); if(retvalue==JFileChooser.APPROVE_OPTION) { log.setText(fc.getSelectedFile().getAbsolutePath()); } } }), c); c.gridx++; p.add(check1, c); c.gridy++; c.gridx = 0; p.add(new JButton(new AbstractAction("setSelectedFile") { @Override public void actionPerformed(ActionEvent e) { File f = new File(field.getText().trim()); JFileChooser fc = fc1; System.out.format("isAbsolute: %s, isParent: %s%n", f.isAbsolute(), !fc.getFileSystemView().isParent(fc.getCurrentDirectory(), f)); fc.setSelectedFile(f); int retvalue = fc.showOpenDialog(p); if(retvalue==JFileChooser.APPROVE_OPTION) { log.setText(fc.getSelectedFile().getAbsolutePath()); } if(check2.isSelected()) fc.setSelectedFile(f.getParentFile()); //XXX: reset??? } }), c); c.gridx++; p.add(check2, c); add(p, BorderLayout.NORTH); add(new JScrollPane(log)); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //UIManager.put("FileChooser.readOnly", Boolean.TRUE); }catch(Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args){ if (args.length != 1) { System.err.println("Usage: java Server <port number>"); System.exit(1); } int portNumber = Integer.parseInt(args[0]); boolean listening = true; try { ServerSocket serverSocket = new ServerSocket(Integer.valueOf(System.getenv("PORT"))); System.out.println("Server started at " + Integer.valueOf(System.getenv("PORT")); while (listening) { new MultiServerThread(serverSocket.accept()).start(); } } catch (IOException e) { System.err.println("Could not listen on port " + portNumber); System.exit(-1); } } }
package cx2x.xcodeml.xelement; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.xnode.Xattr; import cx2x.xcodeml.xnode.Xcode; import cx2x.xcodeml.xnode.Xnode; import org.w3c.dom.Element; import java.util.ArrayList; import java.util.List; import cx2x.xcodeml.helper.*; /** * The XbasicType represents the basicType (3.3) element in XcodeML intermediate * representation. * * Elements: (kind?, (len | (arrayIndex | indexRange)+)?, coShape?) * - Optional: * - kind (Xkind) * - len (Xlength) * - arrayIndex (XarrayIndex) * - indexRange (XindexRange) * - coShape TODO not needed for the moment * Attributes: * - Required: type (text), ref (text) * - Optional: is_public (bool), is_private (bool), is_pointer (bool), * is_target (bool), is_external (bool),is_intrinsic (bool), * is_optional (bool), is_save (bool), is_parameter (bool), * is_allocatable (bool), intent (text: in, out, inout) * * The type attribute is defined in the Xtype base class. * * @author clementval */ public class XbasicType extends Xtype { private boolean _isArray = false; // Optional elements private List<Xnode> _dimensions = null; private Xnode _kind = null; private Xnode _length = null; // XbasicType required attributes (type is declared in Xtype) private String _ref; // XbasicType optional attributes private boolean _is_public = false; private boolean _is_private = false; private boolean _is_pointer = false; private boolean _is_target = false; private boolean _is_external = false; private boolean _is_intrinsic = false; private boolean _is_optional = false; private boolean _is_save = false; private boolean _is_parameter = false; private boolean _is_allocatable = false; private Xintent _intent = null; /** * Xelement standard ctor. Pass the base element to the base class and read * inner information (elements and attributes). * @param baseElement The root element of the Xelement */ public XbasicType(Element baseElement){ super(baseElement); readBasicTypeInformation(); } /** * Read inner element information. */ private void readBasicTypeInformation(){ readRequiredAttributes(); readOptionalAttributes(); _dimensions = XelementHelper.findIndexes(this); // is array ? if (_dimensions.size() > 0){ _isArray = true; } // has length ? _length = find(Xcode.LEN); // has kind ? _kind = find(Xcode.KIND); } /** * Read all required attributes. */ private void readRequiredAttributes() { // Attribute type is read in Xtype _ref = getAttribute(Xattr.REF); } /** * Read all optional attributes */ private void readOptionalAttributes() { _is_public = getBooleanAttribute(Xattr.IS_PUBLIC); _is_private = getBooleanAttribute(Xattr.IS_PRIVATE); _is_pointer = getBooleanAttribute(Xattr.IS_POINTER); _is_target = getBooleanAttribute(Xattr.IS_TARGET); _is_external = getBooleanAttribute(Xattr.IS_EXTERNAL); _is_intrinsic = getBooleanAttribute(Xattr.IS_INTRINSIC); _is_optional = getBooleanAttribute(Xattr.IS_OPTIONAL); _is_save = getBooleanAttribute(Xattr.IS_SAVE); _is_parameter = getBooleanAttribute(Xattr.IS_PARAMETER); _is_allocatable = getBooleanAttribute(Xattr.IS_ALLOCATABLE); _intent = Xintent.fromString(getAttribute(Xattr.INTENT)); } /** * Get the indexRange object for the given dimension. * @param index The position of the dimension. For the first dimension, index * is 0, for the second is 1 and so on. * @return A XindexRange object representing the index range of a specific * dimension. */ public Xnode getDimensions(int index){ if(index >= _dimensions.size() || index < 0){ return null; } return _dimensions.get(index); } /** * Check whether the type is an array type. * @return True if the type is an array type. False otherwise. */ public boolean isArray(){ return _isArray; } /** * Check whether the type has a length element. * @return True if the type has a length element. False otherwise. */ public boolean hasLength(){ return _length != null; } /** * Get the len element. * @return Len element. Null if the basic type has no len element. */ public Xnode getLength(){ return _length; } /** * Check whether the type has a kind element. * @return True if the type has a kind element. False otherwise. */ public boolean hasKind(){ return _kind != null; } /** * Get the kind element. * @return Kind element. Null if the basic type has no kind element. */ public Xnode getKind(){ return _kind; } /** * Get the array dimensions. * @return The dimensions of the array type. */ public int getDimensions(){ return _dimensions.size(); } /** * Get ref attribute value. * @return The ref attribute value as String. */ public String getRef(){ return _ref; } /** * Set the value of ref attribute. * @param value New value of ref attribute. */ public void setRef(String value){ setAttribute(Xattr.REF, value); } /** * Check whether the type is public. * @return True if the type is public. False otherwise. */ public boolean isPublic() { return _is_public; } /** * Check whether the type is private. * @return True if the type is private. False otherwise. */ public boolean isPrivate() { return _is_private; } /** * Check whether the type is a pointer. * @return True if the type is a pointer. False otherwise. */ public boolean isPointer() { return _is_pointer; } /** * Check whether the type is a target. * @return True if the type is a target. False otherwise. */ public boolean isTarget() { return _is_target; } /** * Check whether the type is external. * @return True if the type is external. False otherwise. */ public boolean isExternal() { return _is_external; } /** * Check whether the type is intrinsic. * @return True if the type is intrinsic. False otherwise. */ public boolean isIntrinsic() { return _is_intrinsic; } /** * Check whether the type is optional. * @return True if the type is optional. False otherwise. */ public boolean isOptional(){ return _is_optional; } /** * Check whether the type is save. * @return True if the type is save. False otherwise. */ public boolean isSave() { return _is_save; } /** * Check whether the type is a parameter. * @return True if the type is a parameter. False otherwise. */ public boolean isParameter() { return _is_parameter; } /** * Check whether the type is allocatable. * @return True if the type is allocatable. False otherwise. */ public boolean isAllocatable() { return _is_allocatable; } /** * Check whether the type has an intent. * @return True if the type has an intent. False otherwise. */ public boolean hasIntent(){ return _intent != Xintent.NONE; } /** * Get the intent of the type. * @return Intent. Null if the type has no intent. */ public Xintent getIntent(){ return _intent; } /** * Set the intent of the type. * @param value Intent value to be set. */ public void setIntent(Xintent value){ setAttribute(Xattr.INTENT, value.toString()); _intent = value; } /** * Remove intent attribute from the element. */ public void removeIntent(){ if(hasIntent()) { _baseElement.removeAttribute(XelementName.ATTR_INTENT); _intent = null; } } /** * Remove is_allocatable attribute from the element. */ public void removeAllocatable(){ if(isAllocatable()){ _baseElement.removeAttribute(XelementName.ATTR_IS_ALLOCATABLE); _is_allocatable = false; } } /** * Remove all dimension from the type */ public void resetDimension(){ for(Xnode idx : _dimensions){ idx.delete(); } _dimensions.clear(); _isArray = false; } /** * Remove the dimensions not in the given list. Dimension index starts at 1. * @param keptDimensions List of dimension index to be kept. */ public void removeDimension(List<Integer> keptDimensions){ List<Xnode> keptDim = new ArrayList<>(); for(int i = 0; i < _dimensions.size(); i++){ if(keptDimensions.contains(i+1)){ keptDim.add(_dimensions.get(i)); } else { _dimensions.get(i).delete(); } } if(keptDim.size() == 0){ _isArray = false; } _dimensions = keptDim; } /** * Add a dimension to the basic type. * @param index Index element to add as the new dimension. * @param position Position compared to already existing element. */ public void addDimension(Xnode index, int position){ if(_dimensions.size() == 0){ appendToChildren(index, false); _dimensions.add(index); _isArray = true; } else { if(position == _dimensions.size() - 1){ // Add at the end Xnode last = _dimensions.get(_dimensions.size()-1); XelementHelper.insertAfter(last, index); _dimensions.add(index); } else { Xnode crtPos = _dimensions.get(position); XelementHelper.insertBefore(crtPos, index); _dimensions.add(position, index); } } } @Override public XbasicType cloneObject() { Element element = (Element)cloneNode(); return new XbasicType(element); } }
package generator; import com.trolltech.qt.*; import com.trolltech.qt.core.*; class QObject___ extends QObject { @com.trolltech.qt.QtBlockedSlot public final java.util.List<QObject> findChildren() { return findChildren(null, (QRegExp) null); } @com.trolltech.qt.QtBlockedSlot public final java.util.List<QObject> findChildren(Class<?> cl) { return findChildren(cl, (QRegExp) null); } @com.trolltech.qt.QtBlockedSlot public final java.util.List<QObject> findChildren(Class<?> cl, String name) { return com.trolltech.qt.internal.QtJambiInternal.findChildren(this, cl, name); } @com.trolltech.qt.QtBlockedSlot public final java.util.List<QObject> findChildren(Class<?> cl, QRegExp name) { return com.trolltech.qt.internal.QtJambiInternal.findChildren(this, cl, name); } @com.trolltech.qt.QtBlockedSlot public final QObject findChild() { return findChild(null, null); } @com.trolltech.qt.QtBlockedSlot public final QObject findChild(Class<?> cl) { return findChild(cl, null); } @com.trolltech.qt.QtBlockedSlot public final QObject findChild(Class<?> cl, String name) { return com.trolltech.qt.internal.QtJambiInternal.findChild(this, cl, name); } @com.trolltech.qt.QtBlockedSlot public final void setProperty(String name, Object value) { setProperty(QNativePointer.createCharPointer(name), value); } @com.trolltech.qt.QtBlockedSlot public final Object property(String name) { return property(QNativePointer.createCharPointer(name)); } @com.trolltech.qt.QtBlockedSlot public final QtProperty userProperty() { return com.trolltech.qt.internal.QtJambiInternal.userProperty(nativeId()); } @com.trolltech.qt.QtBlockedSlot public final java.util.List<com.trolltech.qt.QtProperty> properties() { return com.trolltech.qt.internal.QtJambiInternal.properties(nativeId()); } @com.trolltech.qt.QtBlockedSlot public final int indexOfProperty(String name) { return com.trolltech.qt.internal.QtJambiInternal.indexOfProperty(nativeId(), name); } @com.trolltech.qt.QtBlockedSlot public final void connectSlotsByName() { com.trolltech.qt.internal.QtJambiInternal.connectSlotsByName(this); } }// class abstract class QAbstractItemModel___ extends QAbstractItemModel { private native boolean setData_native(long id, int row, int col, Object value, int role); public final boolean setData(int row, int col, Object value) { return setData_native(nativeId(), row, col, value, com.trolltech.qt.core.Qt.ItemDataRole.DisplayRole); } public final boolean setData(int row, int col, Object value, int role) { return setData_native(nativeId(), row, col, value, role); } private native Object data_native(long id, int row, int col, int role); public final Object data(int row, int col, int role) { return data_native(nativeId(), row, col, role); } public final Object data(int row, int col) { return data_native(nativeId(), row, col, Qt.ItemDataRole.DisplayRole); } }// class class QTimer___ extends QTimer { static private class QSingleShotTimer extends QObject { private int timerId = -1; public Signal0 timeout = new Signal0(); public QSingleShotTimer(int msec, QObject obj, String method) { super(obj); timeout.connect(obj, method); timerId = startTimer(msec); } protected void disposed() { if (timerId > 0) killTimer(timerId); super.disposed(); } protected void timerEvent(QTimerEvent e) { if (timerId > 0) killTimer(timerId); timerId = -1; timeout.emit(); disposeLater(); } } public static void singleShot(int msec, QObject obj, String method) { new QSingleShotTimer(msec, obj, method); } }// class class QCoreApplication___ extends QCoreApplication { protected static QCoreApplication m_instance = null; public QCoreApplication(String args[]) { this(argc(args), argv(args)); } public static String translate(String context, String sourceText, String comment) { QTextCodec codec = QTextCodec.codecForName("UTF-8"); return translate(context != null ? codec.fromUnicode(context).data() : null, sourceText != null ? codec.fromUnicode(sourceText).data() : null, comment != null ? codec.fromUnicode(comment).data() : null, Encoding.CodecForTr); } public static String translate(String context, String sourceText) { return translate(context, sourceText, null); } public static String translate(String context, String sourceText, String comment, int n) { QTextCodec codec = QTextCodec.codecForName("UTF-8"); return translate(context != null ? codec.fromUnicode(context).data() : null, sourceText != null ? codec.fromUnicode(sourceText).data() : null, comment != null ? codec.fromUnicode(comment).data() : null, Encoding.CodecForTr, n); } public static void initialize(String args[]) { if (m_instance != null) throw new RuntimeException("QCoreApplication can only be initialized once"); String path = Utilities.unpackPlugins(); if (path != null) addLibraryPath(path); else com.trolltech.qt.internal.QtJambiInternal.setupDefaultPluginPath(); m_instance = new QCoreApplication(args); m_instance.aboutToQuit.connect(m_instance, "disposeOfMyself()"); } private void disposeOfMyself() { m_instance = null; System.gc(); this.dispose(); } protected final static com.trolltech.qt.QNativePointer argv(String args[]) { String newArgs[] = new String[args.length + 1]; System.arraycopy(args, 0, newArgs, 1, args.length); newArgs[0] = "Qt Jambi application"; argv = com.trolltech.qt.QNativePointer.createCharPointerPointer(newArgs); return argv; } protected final static com.trolltech.qt.QNativePointer argc(String args[]) { if (argc != null) { throw new RuntimeException("There can only exist one QCoreApplication instance"); } argc = new com.trolltech.qt.QNativePointer(com.trolltech.qt.QNativePointer.Type.Int); argc.setIntValue(args.length + 1); return argc; } @Override protected void disposed() { argc = null; argv = null; m_instance = null; super.disposed(); } public static void invokeLater(java.lang.Runnable runnable) { postEvent(new QInvokable(runnable), new QEvent(QInvokable.INVOKABLE_EVENT)); } /** * Executes the runnable's run() method in the main thread and waits for it * to return. If the current thread is not the main thread, an event loop * must be running in the main thread, or this method will wait * indefinitely. */ public static void invokeAndWait(Runnable runnable) { // Specialcase invoke and wait for the case of running on the current thread... if (Thread.currentThread() == instance().thread()) { runnable.run(); return; } QSynchronousInvokable invokable = new QSynchronousInvokable(runnable); QCoreApplication.postEvent(invokable, new QEvent(QSynchronousInvokable.SYNCHRONOUS_INVOKABLE_EVENT)); invokable.waitForInvoked(); invokable.disposeLater(); } /** * Executes the task in the application's main thread after the * specified timeout. This is done by starting a timer so this * method does not block. * @param timeout The time to wait, in milliseconds * @param task The task to perform... */ public static void invokeLater(int timeout, final Runnable task) { QTimer.singleShot(timeout, new QObject() { public void todo() { task.run(); disposeLater(); } }, "todo()"); } private static com.trolltech.qt.QNativePointer argc, argv; }// class class QTranslator___ extends QTranslator { public final boolean load(byte data[]) { return load(com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data), data.length); } }// class class QProcess___ extends QProcess { public static class DetachedProcessInfo { public DetachedProcessInfo(boolean success, long pid) { this.success = success; this.pid = pid; } public boolean success; public long pid; } public static DetachedProcessInfo startDetached(String program, java.util.List<String> arguments, String workingDirectory) { QNativePointer pid = new QNativePointer(QNativePointer.Type.Long); boolean success = startDetached(program, arguments, workingDirectory, pid); return new DetachedProcessInfo(success, pid.longValue()); } }// class class QDataStream___ extends QDataStream { private QNativePointer srb = new QNativePointer(QNativePointer.Type.Byte, 32) { { setVerificationEnabled(false); } }; public final boolean readBoolean() { operator_shift_right_boolean(srb); return srb.booleanValue(); } public final byte readByte() { operator_shift_right_byte(srb); return srb.byteValue(); } public final short readShort() { operator_shift_right_short(srb); return srb.shortValue(); } public final int readInt() { operator_shift_right_int(srb); return srb.intValue(); } public final long readLong() { operator_shift_right_long(srb); return srb.longValue(); } public final char readChar() { operator_shift_right_char(srb); return srb.charValue(); } public final float readFloat() { operator_shift_right_float(srb); return srb.floatValue(); } public final double readDouble() { operator_shift_right_double(srb); return srb.doubleValue(); } public final QDataStream writeShort(short s) { writeShort_char((char) s); return this; } private native String readString_private(long nativeId); private native void writeString_private(long nativeId, String string); public final String readString() { if (nativeId() == 0) throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName()); return readString_private(nativeId()); } public final void writeString(String string) { if (nativeId() == 0) throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName()); writeString_private(nativeId(), string); } private native int writeBytes(long id, byte buffer[], int length); private native int readBytes(long id, byte buffer[], int length); public final int writeBytes(byte buffer[]) { return writeBytes(buffer, buffer.length); } public final int writeBytes(byte buffer[], int length) { return writeBytes(nativeId(), buffer, length); } public final int readBytes(byte buffer[]) { return readBytes(buffer, buffer.length); } public final int readBytes(byte buffer[], int length) { return readBytes(nativeId(), buffer, length); } }// class class QTextStream___ extends QTextStream { public final void setCodec(String codecName) { setCodec(QNativePointer.createCharPointer(codecName)); if (codec() != __rcCodec) __rcCodec = null; } private QNativePointer srb = new QNativePointer(QNativePointer.Type.Byte, 32) { { setVerificationEnabled(false); } }; public final byte readByte() { operator_shift_right_byte(srb); return srb.byteValue(); } public final short readShort() { operator_shift_right_short(srb); return srb.shortValue(); } public final int readInt() { operator_shift_right_int(srb); return srb.intValue(); } public final long readLong() { operator_shift_right_long(srb); return srb.longValue(); } public final float readFloat() { operator_shift_right_float(srb); return srb.floatValue(); } public final double readDouble() { operator_shift_right_double(srb); return srb.doubleValue(); } public final QTextStream writeShort(short s) { writeShort_char((char) s); return this; } public final QTextStream writeChar(char c) { writeShort_char(c); return this; } public final char readChar() { operator_shift_right_short(srb); return srb.charValue(); } public final String readString() { return readString_native(nativeId()); } public final void writeString(String string) { writeString_native(nativeId(), string); } private final native String readString_native(long id); private final native void writeString_native(long id, String string); }// class class QBitArray___ extends QBitArray { @com.trolltech.qt.QtBlockedSlot public final void xor(QBitArray other) { operator_xor_assign(other); } @com.trolltech.qt.QtBlockedSlot public final void and(QBitArray other) { operator_and_assign(other); } @com.trolltech.qt.QtBlockedSlot public final void or(QBitArray other) { operator_or_assign(other); } @com.trolltech.qt.QtBlockedSlot public final void set(QBitArray other) { operator_assign(other); } @com.trolltech.qt.QtBlockedSlot public final QBitArray inverted() { return operator_negate(); } }// class // hfr class QDate___ extends QDate { public final int weekNumber() { return weekNumber(null); } public final int yearOfWeekNumber() { QNativePointer np = new QNativePointer(QNativePointer.Type.Int); weekNumber(np); return np.intValue(); } }// class class QDir___ extends QDir { @com.trolltech.qt.QtBlockedSlot public String at(int i) { return operator_subscript(i); } }// class class QByteArray___ extends QByteArray { public QByteArray(String s) { this(); append(s); } public QByteArray(byte data[]) { this(com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data), data.length); } public final boolean contains(String str) { return contains(new QByteArray(str)); } public final int count(String str) { return count(new QByteArray(str)); } public final boolean endsWith(String str) { return endsWith(new QByteArray(str)); } public final QByteArray prepend(String str) { return prepend(new QByteArray(str)); } public final QByteArray replace(QByteArray before, String after) { return replace(before, new QByteArray(after)); } public final QByteArray replace(String before, String after) { return replace(new QByteArray(before), new QByteArray(after)); } public final boolean startsWith(String str) { return startsWith(new QByteArray(str)); } public final byte[] toByteArray() { byte[] res = new byte[size()]; for (int i = 0; i < size(); i++) { res[i] = at(i); } return res; } @com.trolltech.qt.QtBlockedSlot public final QByteArray set(QByteArray other) { operator_assign(other); return this; } }// class class QFile___ extends QFile { public static String decodeName(String localFileName) { return decodeName(com.trolltech.qt.QNativePointer.createCharPointer(localFileName)); } }// class class QIODevice___ extends QIODevice { /** * Gets a byte from the device. * * @return -1 on failure, or the value of the byte on success */ public final int getByte() { QNativePointer np = new QNativePointer(QNativePointer.Type.Byte); boolean success = getByte(np); return success ? np.byteValue() : -1; } }// class class QCryptographicHash___ extends QCryptographicHash { public final void addData(byte data[]) { QNativePointer np = com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data); addData(np, data.length); } }// class class QTextCodec___ extends QTextCodec { static { setCodecForTr(QTextCodec.codecForName("UTF-8")); } public static QTextCodec codecForName(String name) { return codecForName(com.trolltech.qt.QNativePointer.createCharPointer(name)); } }// class class QBuffer___ extends QBuffer { // retain a reference to avoid gc private Object strongDataReference = null; public QBuffer(QByteArray byteArray, QObject parent) { this(byteArray.nativePointer(), parent); strongDataReference = byteArray; } public QBuffer(QByteArray byteArray) { this(byteArray, null); } public final void setBuffer(QByteArray byteArray) { setBuffer(byteArray.nativePointer()); strongDataReference = byteArray; } public final void setData(byte data[]) { QNativePointer np = com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data); setData(np, data.length); } }// class class QSignalMapper___ extends QSignalMapper { private java.util.Hashtable<QObject, QObject> __rcObjectForObject = new java.util.Hashtable<QObject, QObject>(); private java.util.Hashtable<QObject, Object> __rcWidgetForObject = new java.util.Hashtable<QObject, Object>(); }// class class QAbstractFileEngine_MapExtensionReturn___ extends QAbstractFileEngine_MapExtensionReturn { private QNativePointer currentAddressNativePointer; // don't garbage collect while in use public final void setAddress(String address) { currentAddressNativePointer = address != null ? QNativePointer.createCharPointer(address) : null; address_private(currentAddressNativePointer); } public final String address() { QNativePointer np = address_private(); return np != null ? com.trolltech.qt.internal.QtJambiInternal.charPointerToString(np) : null; } }// class class QAbstractFileEngine___ extends QAbstractFileEngine { /** * Adds <tt>path</tt> to the set of paths in which Qt Jambi should search for resources. Resources * can be accessed using the "classpath:" scheme. */ public static void addSearchPathForResourceEngine(String path) { com.trolltech.qt.internal.QClassPathEngine.addSearchPath(path); } /** * Removes <tt>path</tt> from the set of paths in which Qt Jambi searches * for resources. */ public static void removeSearchPathForResourceEngine(String path) { com.trolltech.qt.internal.QClassPathEngine.removeSearchPath(path); } }// class class QAbstractFileEngine_UnMapExtensionOption___ extends QAbstractFileEngine_UnMapExtensionOption { private QNativePointer currentAddressNativePointer; // don't garbage collect while in use public final void setAddress(String address) { currentAddressNativePointer = address != null ? QNativePointer.createCharPointer(address) : null; address_private(currentAddressNativePointer); } public final String address() { QNativePointer np = address_private(); return np != null ? com.trolltech.qt.internal.QtJambiInternal.charPointerToString(np) : null; } }// class class QFutureWatcher___ extends QFutureWatcher { public final QFuture<T> future() { if (nativeId() == 0) throw new QNoNativeResourcesException("Function call on incomplete object of type: " +getClass().getName()); return __qt_future(nativeId()); } private native QFuture<T> __qt_future(long nativeId); }// class class QFutureWatcherVoid___ extends QFutureWatcherVoid { public final QFutureVoid future() { if (nativeId() == 0) throw new QNoNativeResourcesException("Function call on incomplete object of type: " +getClass().getName()); return __qt_future(nativeId()); } private native QFutureVoid __qt_future(long nativeId); }// class class QFutureSynchronizer___ extends QFutureSynchronizer { public final java.util.List<QFuture<T>> futures() { if (nativeId() == 0) throw new QNoNativeResourcesException("Function call on incomplete object of type: " +getClass().getName()); return __qt_futures(nativeId()); } private native java.util.List<QFuture<T>> __qt_futures(long nativeId); }// class class QFutureSynchronizerVoid___ extends QFutureSynchronizerVoid { public final java.util.List<QFutureVoid> futures() { if (nativeId() == 0) throw new QNoNativeResourcesException("Function call on incomplete object of type: " +getClass().getName()); return __qt_futures(nativeId()); } private native java.util.List<QFutureVoid> __qt_futures(long nativeId); }// class /** The QtConcurrent class contains static methods for running computations in parallel (using separate threads) on the items in a java.util.Collection, such as a Vector or LinkedList. We will now describe these methods. The QtConcurrent::map(), QtConcurrent::mapped() and QtConcurrent::mappedReduced() functions run computations in parallel on the items in a sequence such as a QList or a QVector. QtConcurrent::map() modifies a sequence in-place, QtConcurrent::mapped() returns a new sequence containing the modified content, and QtConcurrent::mappedReduced() returns a single result. Concurrent Map <p> QtConcurrent::mapped() takes an input sequence and a map function. This map function is then called for each item in the sequence, and a new sequence containing the return values from the map function is returned. <p> The map function must be of the form: <pre> U function(const T &amp;t); </pre> T and U can be any type (and they can even be the same type), but T must match the type stored in the sequence. The function returns the modified or mapped content. <p> This example shows how to apply a scale function to all the items in a sequence: <pre> QImage scaled(const QImage &amp;image) { return image.scaled(100, 100); } QList &lt;QImage&gt; images = ...; QFuture&lt;QImage&gt; thumbnails = QtConcurrent::mapped(images, scaled); </pre> The results of the map are made available through QFuture. See the QFuture and QFutureWatcher documentation for more information on how to use QFuture in your applications. <p> If you want to modify a sequence in-place, use QtConcurrent::map(). The map function must then be of the form: <pre> U function(T &amp;t); </pre> Note that the return value and return type of the map function are not used. <p> Using QtConcurrent::map() is similar to using QtConcurrent::mapped(): <pre> void scale(QImage &amp;image) { image = image.scaled(100, 100); } QList&lt;QImage&gt; images = ...; QFuture&lt;void&gt; future = QtConcurrent::map(images, scale); </pre> Since the sequence is modified in place, QtConcurrent::map() does not return any results via QFuture. However, you can still use QFuture and QFutureWatcher to monitor the status of the map. Concurrent Map-Reduce <p> QtConcurrent::mappedReduced() is similar to QtConcurrent::mapped(), but instead of returning a sequence with the new results, the results are combined into a single value using a reduce function. <p> The reduce function must be of the form: <pre> V function(T &amp;result, const U &amp;intermediate) </pre> T is the type of the final result, U is the return type of the map function. Note that the return value and return type of the reduce function are not used. <p> Call QtConcurrent::mappedReduced() like this: <pre> void addToCollage(QImage &amp;collage, const QImage &amp;thumbnail) { QPainter p(&amp;collage); static QPoint offset = QPoint(0, 0); p.drawImage(offset, thumbnail); offset += ...; } QList&lt;QImage&gt; images = ...; QFuture&lt;QImage&gt; collage = QtConcurrent::mappedReduced(images, scaled, addToCollage); </pre> The reduce function will be called once for each result returned by the map function, and should merge the intermediate into the result variable. QtConcurrent::mappedReduced() guarantees that only one thread will call reduce at a time, so using a mutex to lock the result variable is not neccesary. The QtConcurrent::ReduceOptions enum provides a way to control the order in which the reduction is done. If QtConcurrent::UnorderedReduce is used (the default), the order is undefined, while QtConcurrent::OrderedReduce ensures that the reduction is done in the order of the original sequence. Additional API Features Using Iterators instead of Sequence <p> Each of the above functions has a variant that takes an iterator range instead of a sequence. You use them in the same way as the sequence variants: <pre> QList&lt;QImage&gt; images = ...; QFuture&lt;QImage&gt; thumbnails = QtConcurrent::mapped(images.constBegin(), images.constEnd(), scaled); // map in-place only works on non-const iterators QFuture&lt;void&gt; future = QtConcurrent::map(images.begin(), images.end(), scale); QFuture&lt;QImage&gt; collage = QtConcurrent::mappedReduced(images.constBegin(), images.constEnd(), scaled, addToCollage); </pre> Blocking Variants <p> Each of the above functions has a blocking variant that returns the final result instead of a QFuture. You use them in the same way as the asynchronous variants. <pre> QList&lt;QImage&gt; images = ...; // each call blocks until the entire operation is finished QList&lt;QImage&gt; future = QtConcurrent::blockingMapped(images, scaled); QtConcurrent::blockingMap(images, scale); QImage collage = QtConcurrent::blockingMappedReduced(images, scaled, addToCollage); </pre> Note that the result types above are not QFuture objects, but real result types (in this case, QList&lt;QImage&gt; and QImage). Using Member Functions <p> QtConcurrent::map(), QtConcurrent::mapped(), and QtConcurrent::mappedReduced() accept pointers to member functions. The member function class type must match the type stored in the sequence: <pre> // squeeze all strings in a QStringList QStringList strings = ...; QFuture&lt;void&gt; squeezedStrings = QtConcurrent::map(strings, &amp;QString::squeeze); // swap the rgb values of all pixels on a list of images QList&lt;QImage&gt; images = ...; QFuture&lt;QImage&gt; bgrImages = QtConcurrent::mapped(images, &amp;QImage::rgbSwapped); // create a set of the lengths of all strings in a list QStringList strings = ...; QFuture&lt;QSet&lt;int&gt; &gt; wordLengths = QtConcurrent::mappedReduced(string, &amp;QString::length, &amp;QSet&lt;int&gt;::insert); </pre> Note that when using QtConcurrent::mappedReduced(), you can mix the use of normal and member functions freely: <p> <pre> // can mix normal functions and member functions with QtConcurrent::mappedReduced() // compute the average length of a list of strings extern void computeAverage(int &amp;average, int length); QStringList strings = ...; QFuture&lt;int&gt; averageWordLength = QtConcurrent::mappedReduced(strings, &amp;QString::length, computeAverage); // create a set of the color distribution of all images in a list extern int colorDistribution(const QImage &amp;string); QList&lt;QImage&gt; images = ...; QFuture&lt;QSet&lt;int&gt; &gt; totalColorDistribution = QtConcurrent::mappedReduced(images, colorDistribution, QSet&lt;int&gt;::insert); </pre> Using Function Objects <p> QtConcurrent::map(), QtConcurrent::mapped(), and QtConcurrent::mappedReduced() accept function objects, which can be used to add state to a function call. The result_type typedef must define the result type of the function call operator: <pre> struct Scaled { Scaled(int size) : m_size(size) { } typedef QImage result_type; QImage operator()(const QImage &amp;image) { return image.scaled(m_size, m_size); } int m_size; }; QList&lt;QImage&gt; images = ...; QFuture&lt;QImage&gt; thumbnails = QtConcurrent::mapped(images, Scaled(100)); </pre> Using Bound Function Arguments <p> Note that Qt does not provide support for bound functions. This is provided by 3rd party libraries like Boost or C++ TR1 Library Extensions. <p> If you want to use a map function that takes more than one argument you can use boost::bind() or std::tr1::bind() to transform it onto a function that takes one argument. <p> As an example, we'll use QImage::scaledToWidth(): <pre> QImage QImage::scaledToWidth(int width, Qt::TransformationMode) const; </pre> scaledToWidth takes three arguments (including the "this" pointer) and can't be used with QtConcurrent::mapped() directly, because QtConcurrent::mapped() expects a function that takes one argument. To use QImage::scaledToWidth() with QtConcurrent::mapped() we have to provide a value for the width and the transformation mode: <pre> boost::bind(&amp;QImage::scaledToWidth, 100 Qt::SmoothTransformation) </pre> The return value from boost::bind() is a function object (functor) with the following signature: <pre> QImage scaledToWith(const QImage &amp;image) </pre> This matches what QtConcurrent::mapped() expects, and the complete example becomes: <pre> QList&gt;QImage&lt; images = ...; QFuture&gt;QImage&lt; thumbnails = QtConcurrent::mapped(images, boost::bind(&amp;QImage::scaledToWidth, 100 Qt::SmoothTransformation)); </pre> */ class QtConcurrent___ extends QtConcurrent { static { com.trolltech.qt.QtJambi_LibraryInitializer.init(); com.trolltech.qt.core.QtJambi_LibraryInitializer.init(); } /** * An implemetation of this interface is given one to QtConcurrent's map() methods. * The map() method of this interface is called for each object in a java.util.Collection. * */ public interface MapFunctor<T> { /** * This function is called for each item in the Collection. The function is then free to alter <tt>object</tt> as it see fit. */ public void map(T object); } /** * Calls function once for each item in sequence. The function is passed a reference to the item, so that any modifications done to the item will appear in sequence. */ public static native <T> QFutureVoid map(java.util.Collection<T> sequence, MapFunctor<T> functor); /** * Calls function once for each item in sequence. The function is passed a reference to the item, so that any modifications done to the item will appear in sequence. */ public static native <T> void blockingMap(java.util.Collection<T> sequence, MapFunctor<T> functor); /** * Implement this interface to perform a mapped operation. An implementation of the interface is sendt * to ome of the mapped methods of QtConcurrent, which applies the MappedFunctor.map() method to all elements in a collection, * and returns the result. */ public interface MappedFunctor<U, T> { /** * This method is called for each object in a collection. It should returned a new altered * object. */ public U map(T object); } /** * Calls function once for each item in sequence and returns a future with each mapped item as a result. You can QFutureIterator to iterate through the results. * */ public static native <U, T> QFuture<U> mapped(java.util.Collection<T> sequence, MappedFunctor<U, T> functor); /** * Calls function once for each item in sequence and returns a future with each mapped item as a result. You can QFutureIterator to iterate through the results. */ public static native <U, T> java.util.List<U> blockingMapped(java.util.Collection<T> sequence, MappedFunctor<U, T> functor); /** * Implement this interface in order to perform a reduce operation. * <p> * The reduce method will be called once per intermediate result (the result of the mapping of the data) * and the very first time the reduce() method is called for the particular data set, the result is set to * the returned value of the defaultResult() method. */ public interface ReducedFunctor<U, T> { public U defaultResult(); /** * Performs a reduce operation on <tt>intermediate</tt>. <tt>result</tt> is the result of the reduction. */ public void reduce(U result, T intermediate); } /** * This is an overloaded method provided for convenience. * <p> * It is equivalent of mappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce) */ public static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor) { return mappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce); } /** * This is an overloaded method provided for convenience. * <p> * Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions. * */ public static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOption ... options) { return mappedReduced(sequence, functor, reducedFunctor, new ReduceOptions(options)); } /** * Calls mapFunction once for each item in sequence. The return value of each mapFunction is passed to reduceFunction. * <p> * Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions. * */ public static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOptions options) { return mappedReduced(sequence, functor, reducedFunctor, options.value()); } private native static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, int options); /** * This is an overloaded method provided for convenience. * <p> * It is equivalent of calling blockingMappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce) * */ public static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor) { return blockingMappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce); } /** * Calls mapFunction once for each item in sequence. The return value of each mapFunction is passed to reduceFunction. * <p> * Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions. * <p> * Note: This function will block until all items in the sequence have been processed. */ public static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOption ... options) { return blockingMappedReduced(sequence, functor, reducedFunctor, new ReduceOptions(options)); } /** * Calls mapFunction once for each item in sequence. The return value of each mapFunction is passed to reduceFunction. * <p> * Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions. * <p> * Note: This function will block until all items in the sequence have been processed. */ public static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOptions options) { return blockingMappedReduced(sequence, functor, reducedFunctor, options.value()); } private native static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, int options); /** * An implementation of this interface is given to one of QtConcurrent's filtered() methods. * The filter method if this interface is called for each item in a java.util.Collection. * */ public interface FilteredFunctor<T> { /** * This method is called for each item in a java.util.Collection. The items for which * this method returns true are removed from the collection. */ public boolean filter(T object); } /** * Calls filterFunctor's filtered() method once for each item in sequence and returns a new Sequence of kept items. If filterFunction returns true, a copy of the item is put in the new Sequence. Otherwise, the item will not appear in the new Sequence. */ public native static <T> QFuture<T> filtered(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor); /** * Calls filterFunctor's filtered() method once for each item in sequence and returns a new Sequence of kept items. If filterFunction returns true, a copy of the item is put in the new Sequence. Otherwise, the item will not appear in the new Sequence. */ public native static <T> java.util.List<T> blockingFiltered(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor); /** * This is an overloaded method provided for convenience. It is equivalent of calling filteredReduced(sequence, filteredFunctor, ReduceOption.UnorderedReduce, ReduceOption.Seq This is an overloaded method provided for convenience. It is equivalent of calling filteredReduced) */ public static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor) { return filteredReduced(sequence, filteredFunctor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce); } /** * Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true. * <p> * Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence. */ public static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOption ... options) { return filteredReduced(sequence, filteredFunctor, reducedFunctor, new ReduceOptions(options)); } /** * Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true. * <p> * Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence. */ public static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOptions options) { return filteredReduced(sequence, filteredFunctor, reducedFunctor, options.value()); } private native static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, int options); /** * This is an overloaded method provided for convenience. It is the equivalent of calling blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce) */ public static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor) { return blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce); } /** * Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true. * <p> * Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence. */ public static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOption ... options) { return blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, new ReduceOptions(options)); } /** * Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true. * <p> * Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence. */ public static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOptions options) { return blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, options.value()); } private native static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, int options); /** * Executes the method <tt>m</tt> through the QtConcurrent framework with the given arguments. The returned QFuture object's result wil be the * return value of <tt>m</tt>. Note that this method does not accept function that return void. use runVoidMethod() for this. */ public static <T> QFuture<T> run(Object _this, java.lang.reflect.Method m, Object ... args) { if (m.getReturnType() == null || m.getReturnType().equals(Void.TYPE)) throw new IllegalArgumentException("Cannot call run on method returning void. Use 'runVoidMethod' instead."); return runPrivate(_this, m.getDeclaringClass(), m, args, com.trolltech.qt.internal.QtJambiInternal.resolveConversionSchema(m.getParameterTypes(), m.getParameterTypes()), com.trolltech.qt.internal.QtJambiInternal.typeConversionCode(m.getReturnType())); } private native static <T> QFuture<T> runPrivate(Object _this, Class<?> declaringClass, java.lang.reflect.Method m, Object args[], int conversionScheme[], byte returnType); /** * Executes the method <tt>m</tt> with the given arguments using the QtConcurrent framework. Notice that runVoidMethod() does not * accept methods that has a return value. Use the run() method for this purpose. */ public static QFutureVoid runVoidMethod(Object _this, java.lang.reflect.Method m, Object ... args) { if (m.getReturnType() != null && !m.getReturnType().equals(Void.TYPE)) throw new IllegalArgumentException("Cannot call runVoidMethod on method returning non-void type. Use 'run' instead."); return runVoidMethodPrivate(_this, m.getDeclaringClass(), m, args, com.trolltech.qt.internal.QtJambiInternal.resolveConversionSchema(m.getParameterTypes(), m.getParameterTypes())); } private native static QFutureVoid runVoidMethodPrivate(Object _this, Class<?> declaringClass, java.lang.reflect.Method m, Object args[], int conversionScheme[]); }// class
package org.apollo.net.update; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.Optional; import org.apollo.cache.IndexedFileSystem; import org.apollo.net.update.resource.CombinedResourceProvider; import org.apollo.net.update.resource.HypertextResourceProvider; import org.apollo.net.update.resource.ResourceProvider; import org.apollo.net.update.resource.VirtualResourceProvider; import com.google.common.base.Charsets; /** * A worker which services HTTP requests. * * @author Graham */ public final class HttpRequestWorker extends RequestWorker<HttpRequest, ResourceProvider> { /** * The default character set. */ private static final Charset CHARACTER_SET = Charsets.ISO_8859_1; /** * The value of the server header. */ private static final String SERVER_IDENTIFIER = "JAGeX/3.1"; /** * The directory with web files. */ private static final Path WWW_DIRECTORY = Paths.get("data/www"); /** * Creates the HTTP request worker. * * @param dispatcher The dispatcher. * @param fs The file system. */ public HttpRequestWorker(UpdateDispatcher dispatcher, IndexedFileSystem fs) { super(dispatcher, new CombinedResourceProvider(new VirtualResourceProvider(fs), new HypertextResourceProvider(WWW_DIRECTORY))); } /** * Creates an error page. * * @param status The HTTP status. * @param description The error description. * @return The error page as a buffer. */ private static ByteBuf createErrorPage(HttpResponseStatus status, String description) { String title = status.code() + " " + status.reasonPhrase(); StringBuilder builder = new StringBuilder("<!DOCTYPE html><html><head><title>"); builder.append(title); builder.append("</title></head><body><h1>"); builder.append(title); builder.append("</h1><p>"); builder.append(description); builder.append("</p><hr /><address>"); builder.append(SERVER_IDENTIFIER); builder.append(" Server</address></body></html>"); return Unpooled.copiedBuffer(builder.toString(), Charset.defaultCharset()); } /** * Gets the MIME type of a file by its name. * * @param name The file name. * @return The MIME type. */ private static String getMimeType(String name) { if (name.endsWith("/")) { name = name.concat("index.html"); } if (name.endsWith(".htm") || name.endsWith(".html")) { return "text/html"; } else if (name.endsWith(".css")) { return "text/css"; } else if (name.endsWith(".js")) { return "text/javascript"; } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) { return "image/jpeg"; } else if (name.endsWith(".gif")) { return "image/gif"; } else if (name.endsWith(".png")) { return "image/png"; } else if (name.endsWith(".txt")) { return "text/plain"; } return "application/octet-stream"; } @Override protected ChannelRequest<HttpRequest> nextRequest(UpdateDispatcher dispatcher) throws InterruptedException { return dispatcher.nextHttpRequest(); } @Override protected void service(ResourceProvider provider, Channel channel, HttpRequest request) throws IOException { String path = request.getUri(); Optional<ByteBuffer> buf = provider.get(path); HttpResponseStatus status = HttpResponseStatus.OK; String mime = getMimeType(request.getUri()); if (!buf.isPresent()) { status = HttpResponseStatus.NOT_FOUND; mime = "text/html"; } ByteBuf wrapped = buf.isPresent() ? Unpooled.wrappedBuffer(buf.get()) : createErrorPage(status, "The page you requested could not be found."); HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), status); response.headers().set("Date", new Date()); response.headers().set("Server", SERVER_IDENTIFIER); response.headers().set("Content-type", mime + ", charset=" + CHARACTER_SET.name()); response.headers().set("Cache-control", "no-cache"); response.headers().set("Pragma", "no-cache"); response.headers().set("Expires", new Date(0)); response.headers().set("Connection", "close"); response.headers().set("Content-length", wrapped.readableBytes()); channel.write(response); channel.writeAndFlush(wrapped).addListener(ChannelFutureListener.CLOSE); } }
package io.bitsquare.p2p.seed; import com.google.common.annotations.VisibleForTesting; import io.bitsquare.app.Log; import io.bitsquare.app.Version; import io.bitsquare.common.Clock; import io.bitsquare.common.UserThread; import io.bitsquare.p2p.NodeAddress; import io.bitsquare.p2p.P2PService; import io.bitsquare.p2p.P2PServiceListener; import io.bitsquare.p2p.peers.PeerManager; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; public class SeedNode { private static final Logger log = LoggerFactory.getLogger(SeedNode.class); public static final int MAX_CONNECTIONS_LIMIT = 1000; public static final int MAX_CONNECTIONS_DEFAULT = 50; private NodeAddress mySeedNodeAddress = new NodeAddress("localhost:8001"); private boolean useLocalhost = false; private Set<NodeAddress> progArgSeedNodes; private P2PService seedNodeP2PService; private boolean stopped; private final String defaultUserDataDir; public SeedNode(String defaultUserDataDir) { Log.traceCall("defaultUserDataDir=" + defaultUserDataDir); this.defaultUserDataDir = defaultUserDataDir; } // API // args: myAddress (incl. port) bitcoinNetworkId maxConnections useLocalhost seedNodes (separated with |) // 2. and 3. args are optional // eg. lmvdenjkyvx2ovga.onion:8001 0 20 false eo5ay2lyzrfvx2nr.onion:8002|si3uu56adkyqkldl.onion:8003 // or when using localhost: localhost:8001 2 20 true localhost:8002|localhost:8003 // BitcoinNetworkId: The id for the bitcoin network (Mainnet = 0, TestNet = 1, Regtest = 2) public void processArgs(String[] args) { try { if (args.length > 0) { String arg0 = args[0]; checkArgument(arg0.contains(":") && arg0.split(":").length == 2 && arg0.split(":")[1].length() > 3, "Wrong program argument: " + arg0); mySeedNodeAddress = new NodeAddress(arg0); log.info("From processArgs: mySeedNodeAddress=" + mySeedNodeAddress); if (args.length > 1) { String arg1 = args[1]; int networkId = Integer.parseInt(arg1); log.info("From processArgs: networkId=" + networkId); checkArgument(networkId > -1 && networkId < 3, "networkId out of scope (Mainnet = 0, TestNet = 1, Regtest = 2)"); Version.setBtcNetworkId(networkId); if (args.length > 2) { String arg2 = args[2]; int maxConnections = Integer.parseInt(arg2); log.info("From processArgs: maxConnections=" + maxConnections); checkArgument(maxConnections < MAX_CONNECTIONS_LIMIT, "maxConnections seems to be a bit too high..."); PeerManager.setMaxConnections(maxConnections); } else { // we keep default a higher connection size for seed nodes PeerManager.setMaxConnections(MAX_CONNECTIONS_DEFAULT); } if (args.length > 3) { String arg3 = args[3]; checkArgument(arg3.equals("true") || arg3.equals("false")); useLocalhost = ("true").equals(arg3); log.info("From processArgs: useLocalhost=" + useLocalhost); } if (args.length > 4) { String arg4 = args[4]; checkArgument(arg4.contains(":") && arg4.split(":").length > 1 && arg4.split(":")[1].length() > 3, "Wrong program argument"); List<String> list = Arrays.asList(arg4.split("\\|")); progArgSeedNodes = new HashSet<>(); list.forEach(e -> { checkArgument(e.contains(":") && e.split(":").length == 2 && e.split(":")[1].length() == 4, "Wrong program argument"); progArgSeedNodes.add(new NodeAddress(e)); }); log.info("From processArgs: progArgSeedNodes=" + progArgSeedNodes); progArgSeedNodes.remove(mySeedNodeAddress); } else if (args.length > 5) { log.error("Too many program arguments." + "\nProgram arguments: myAddress (incl. port) bitcoinNetworkId " + "maxConnections useLocalhost seedNodes (separated with |)"); } } } } catch (Throwable t) { shutDown(); } } public void createAndStartP2PService(boolean useDetailedLogging) { createAndStartP2PService(mySeedNodeAddress, useLocalhost, Version.getBtcNetworkId(), useDetailedLogging, progArgSeedNodes, null); } @VisibleForTesting public void createAndStartP2PService(NodeAddress mySeedNodeAddress, boolean useLocalhost, int networkId, boolean useDetailedLogging, @Nullable Set<NodeAddress> progArgSeedNodes, @Nullable P2PServiceListener listener) { Path appPath = Paths.get(defaultUserDataDir, "Bitsquare_seed_node_" + String.valueOf(mySeedNodeAddress.getFullAddress().replace(":", "_"))); String logPath = Paths.get(appPath.toString(), "logs").toString(); Log.setup(logPath, useDetailedLogging); log.info("Log files under: " + logPath); SeedNodesRepository seedNodesRepository = new SeedNodesRepository(); if (progArgSeedNodes != null && !progArgSeedNodes.isEmpty()) { if (useLocalhost) seedNodesRepository.setLocalhostSeedNodeAddresses(progArgSeedNodes); else seedNodesRepository.setTorSeedNodeAddresses(progArgSeedNodes); } File storageDir = Paths.get(appPath.toString(), "db").toFile(); if (storageDir.mkdirs()) log.info("Created storageDir at " + storageDir.getAbsolutePath()); File torDir = Paths.get(appPath.toString(), "tor").toFile(); if (torDir.mkdirs()) log.info("Created torDir at " + torDir.getAbsolutePath()); seedNodesRepository.setNodeAddressToExclude(mySeedNodeAddress); seedNodeP2PService = new P2PService(seedNodesRepository, mySeedNodeAddress.port, torDir, useLocalhost, networkId, storageDir, new Clock(), null, null); seedNodeP2PService.start(listener); } @VisibleForTesting public P2PService getSeedNodeP2PService() { return seedNodeP2PService; } private void shutDown() { shutDown(null); } public void shutDown(@Nullable Runnable shutDownCompleteHandler) { if (!stopped) { stopped = true; seedNodeP2PService.shutDown(() -> { if (shutDownCompleteHandler != null) UserThread.execute(shutDownCompleteHandler); }); } } }
package com.moczul.ok2curl; import com.squareup.okhttp.Headers; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okio.Buffer; import static com.moczul.ok2curl.StringUtil.join; public class CurlBuilder { private static final String FORMAT_HEADER = "-H \"%1$s:%2$s\""; private static final String FORMAT_METHOD = "-X %1$s"; private static final String FORMAT_BODY = "-d \"%1$s\""; private final String url; private String method; private String contentType; private String body; private Map<String, String> headers = new HashMap<>(); public CurlBuilder(Request request) { this.url = request.urlString(); this.method = request.method(); final RequestBody body = request.body(); if (body != null) { this.contentType = body.contentType().toString(); this.body = getBodyAsString(body); } final Headers headers = request.headers(); for (int i = 0; i < headers.size(); i++) { this.headers.put(headers.name(i), headers.value(i)); } } private String getBodyAsString(RequestBody body) { try { final Buffer sink = new Buffer(); final Charset charset = body.contentType().charset(Charset.defaultCharset()); body.writeTo(sink); return sink.readString(charset); } catch (IOException e) { throw new RuntimeException(e); } } public String build() { List<String> parts = new ArrayList<>(); parts.add("curl"); parts.add(String.format(FORMAT_METHOD, method.toUpperCase())); for (String key : headers.keySet()) { final String headerPart = String.format(FORMAT_HEADER, key, headers.get(key)); parts.add(headerPart); } if (body != null) { parts.add(String.format(FORMAT_HEADER, "Content-Type", contentType)); parts.add(String.format(FORMAT_BODY, body)); } parts.add(url); return join(" ", parts); } }
package org.jgroups.tests.perf; import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.Version; import org.jgroups.util.Util; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; import java.text.NumberFormat; /** You start the test by running this class. * Use parameters -Xbatch -Xconcurrentio (Solaris specific) * @author Bela Ban (belaban@yahoo.com) */ public class Test implements Receiver { String props=null; Properties config; boolean sender=false; Transport transport=null; Object local_addr=null; /** Map<Object,MemberInfo> members. Keys=member addresses, value=MemberInfo */ Map senders=new ConcurrentReaderHashMap(10); /** Keeps track of members. ArrayList<SocketAddress> */ ArrayList members=new ArrayList(); /** Set when first message is received */ long start=0; /** Set when last message is received */ long stop=0; int num_members=0; int num_senders=0; long num_msgs_expected=0; long num_msgs_received=0; // from everyone long num_bytes_received=0; // from everyone Log log=LogFactory.getLog(getClass()); boolean all_received=false; boolean final_results_received=false; /** Map<Object, MemberInfo>. A hashmap of senders, each value is the 'senders' hashmap */ Map results=new HashMap(); ResultsPublisher publisher=new ResultsPublisher(); List heard_from=new ArrayList(); /** Dump info in gnuplot format */ boolean gnuplot_output=false; boolean dump_transport_stats=false; /** Log every n msgs received (if gnuplot_output == true) */ long log_interval=1000; /** Last time we dumped info */ long last_dump=0; long counter=1; long msg_size=1000; boolean jmx=false; transient static NumberFormat f; static { f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); f.setMaximumFractionDigits(2); } public void start(Properties c, boolean verbose, boolean jmx) throws Exception { String config_file="config.txt"; BufferedReader fileReader; String line; String key, val; StringTokenizer st; Properties tmp=new Properties(); config_file=c.getProperty("config"); fileReader=new BufferedReader(new FileReader(config_file)); while((line=fileReader.readLine()) != null) { if(line.startsWith(" continue; line=line.trim(); if(line.length() == 0) continue; st=new StringTokenizer(line, "=", false); key=st.nextToken().toLowerCase(); val=st.nextToken(); tmp.put(key, val); } fileReader.close(); // 'tmp' now contains all properties from the file, now we need to override the ones // passed to us by 'c' tmp.putAll(c); this.config=tmp; StringBuffer sb=new StringBuffer(); sb.append("\n\n sb.append("Date: ").append(new Date()).append('\n'); sb.append("Run by: ").append(System.getProperty("user.name")).append("\n\n"); if(verbose) sb.append("Properties: ").append(printProperties()).append("\n for(Iterator it=this.config.entrySet().iterator(); it.hasNext();) { Map.Entry entry=(Map.Entry)it.next(); sb.append(entry.getKey()).append(":\t").append(entry.getValue()).append('\n'); } sb.append("JGroups version: ").append(Version.printVersion()).append('\n'); System.out.println("Configuration is: " + sb); log.info(sb.toString()); props=this.config.getProperty("props"); num_members=Integer.parseInt(this.config.getProperty("num_members")); num_senders=Integer.parseInt(this.config.getProperty("num_senders")); long num_msgs=Long.parseLong(this.config.getProperty("num_msgs")); this.num_msgs_expected=num_senders * num_msgs; sender=Boolean.valueOf(this.config.getProperty("sender")).booleanValue(); msg_size=Long.parseLong(this.config.getProperty("msg_size")); String tmp2=this.config.getProperty("gnuplot_output", "false"); if(Boolean.valueOf(tmp2).booleanValue()) this.gnuplot_output=true; tmp2=this.config.getProperty("dump_transport_stats", "false"); if(Boolean.valueOf(tmp2).booleanValue()) this.dump_transport_stats=true; tmp2=this.config.getProperty("log_interval"); if(tmp2 != null) log_interval=Long.parseLong(tmp2); if(gnuplot_output) { sb=new StringBuffer(); sb.append("\n sb.append(", free_mem [KB] "); sb.append(", total_mem [KB] "); sb.append(", total_msgs_sec [msgs/sec] "); sb.append(", total_throughput [KB/sec] "); sb.append(", rolling_msgs_sec (last ").append(log_interval).append(" msgs) "); sb.append(" [msgs/sec] "); sb.append(", rolling_throughput (last ").append(log_interval).append(" msgs) "); sb.append(" [KB/sec]\n"); if(log.isInfoEnabled()) log.info(sb.toString()); } if(jmx) { this.config.setProperty("jmx", "true"); } this.jmx=new Boolean(this.config.getProperty("jmx")).booleanValue(); String transport_name=this.config.getProperty("transport"); transport=(Transport)Util.loadClass(transport_name, this.getClass()).newInstance(); transport.create(this.config); transport.setReceiver(this); transport.start(); local_addr=transport.getLocalAddress(); } private String printProperties() { StringBuffer sb=new StringBuffer(); Properties p=System.getProperties(); for(Iterator it=p.entrySet().iterator(); it.hasNext();) { Map.Entry entry=(Map.Entry)it.next(); sb.append(entry.getKey()).append(": ").append(entry.getValue()).append('\n'); } return sb.toString(); } public void stop() { if(transport != null) { transport.stop(); transport.destroy(); } } public void receive(Object sender, byte[] payload) { if(payload == null || payload.length == 0) { System.err.println("payload is incorrect: " + payload); return; } try { int type=payload[0]; if(type == 1) { // DATA int len=payload.length -1; handleData(sender, len); return; } byte[] tmp=new byte[payload.length-1]; System.arraycopy(payload, 1, tmp, 0, tmp.length); Data d=(Data)Util.streamableFromByteBuffer(Data.class, tmp); switch(d.getType()) { case Data.DISCOVERY_REQ: sendDiscoveryResponse(); break; case Data.DISCOVERY_RSP: synchronized(this.members) { if(!this.members.contains(sender)) { this.members.add(sender); System.out.println("-- " + sender + " joined"); if(d.sender) { synchronized(this.members) { if(!this.senders.containsKey(sender)) { this.senders.put(sender, new MemberInfo(d.num_msgs)); } } } this.members.notify(); } } break; case Data.FINAL_RESULTS: publisher.stop(); if(!final_results_received) { dumpResults(d.results); final_results_received=true; } synchronized(this) { this.notify(); } break; case Data.RESULTS: results.put(sender, d.result); heard_from.remove(sender); if(heard_from.size() == 0) { sendFinalResults(); } break; default: log.error("received invalid data type: " + payload[0]); break; } } catch(Exception e) { e.printStackTrace(); } } private void handleData(Object sender, int num_bytes) { if(all_received) return; if(start == 0) { start=System.currentTimeMillis(); last_dump=start; } num_msgs_received++; num_bytes_received+=num_bytes; if(num_msgs_received >= num_msgs_expected) { if(stop == 0) stop=System.currentTimeMillis(); all_received=true; } if(num_msgs_received % log_interval == 0) System.out.println(new StringBuffer("-- received ").append(num_msgs_received).append(" messages")); if(counter % log_interval == 0) { if(log.isInfoEnabled()) log.info(dumpStats(counter)); } MemberInfo info=(MemberInfo)this.senders.get(sender); if(info != null) { if(info.start == 0) info.start=System.currentTimeMillis(); info.num_msgs_received++; counter++; info.total_bytes_received+=num_bytes; if(info.num_msgs_received >= info.num_msgs_expected) { info.done=true; if(info.stop == 0) info.stop=System.currentTimeMillis(); } } else { log.error("-- sender " + sender + " not found in senders hashmap"); } if(all_received) { if(!this.sender) dumpSenders(); publisher.start(); } } private void sendResults() throws Exception { Data d=new Data(Data.RESULTS); byte[] buf; MemberInfo info=new MemberInfo(num_msgs_expected); info.done=true; info.num_msgs_received=num_msgs_received; info.start=start; info.stop=stop; info.total_bytes_received=this.num_bytes_received; d.result=info; buf=generatePayload(d, null); transport.send(null, buf); } private void sendFinalResults() throws Exception { Data d=new Data(Data.FINAL_RESULTS); byte[] buf; d.results=new ConcurrentReaderHashMap(this.results); buf=generatePayload(d, null); transport.send(null, buf); } boolean allReceived() { return all_received; } void sendMessages() throws Exception { long total_msgs=0; int msgSize=Integer.parseInt(config.getProperty("msg_size")); int num_msgs=Integer.parseInt(config.getProperty("num_msgs")); // int logInterval=Integer.parseInt(config.getProperty("log_interval")); // boolean gnuplot_output=Boolean.getBoolean(config.getProperty("gnuplot_output", "false")); byte[] buf=new byte[msgSize]; for(int k=0; k < msgSize; k++) buf[k]='.'; Data d=new Data(Data.DATA); byte[] payload=generatePayload(d, buf); for(int i=0; i < num_msgs; i++) { transport.send(null, payload); total_msgs++; if(total_msgs % log_interval == 0) { System.out.println("++ sent " + total_msgs); } } } byte[] generatePayload(Data d, byte[] buf) throws Exception { byte[] tmp=buf != null? buf : Util.streamableToByteBuffer(d); byte[] payload=new byte[tmp.length +1]; payload[0]=intToByte(d.getType()); System.arraycopy(tmp, 0, payload, 1, tmp.length); return payload; } private byte intToByte(int type) { switch(type) { case Data.DATA: return 1; case Data.DISCOVERY_REQ: return 2; case Data.DISCOVERY_RSP: return 3; case Data.RESULTS: return 4; case Data.FINAL_RESULTS: return 5; default: return 0; } } // private void dumpResults(Map final_results) { // Object member; // Map.Entry entry; // Map map; // StringBuffer sb=new StringBuffer(); // sb.append("\n-- results:\n\n"); // for(Iterator it=final_results.entrySet().iterator(); it.hasNext();) { // entry=(Map.Entry)it.next(); // member=entry.getKey(); // map=(Map)entry.getValue(); // sb.append("-- results from ").append(member); // if(member.equals(local_addr)) // sb.append(" (myself)"); // sb.append(":\n"); // dump(map, sb); // sb.append('\n'); // System.out.println(sb.toString()); // if(log.isInfoEnabled()) log.info(sb.toString()); private void dumpResults(Map final_results) { Object member; Map.Entry entry; MemberInfo val; double combined_msgs_sec, tmp=0; StringBuffer sb=new StringBuffer(); sb.append("\n-- results:\n"); for(Iterator it=final_results.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); member=entry.getKey(); val=(MemberInfo)entry.getValue(); tmp+=val.getMessageSec(); sb.append("\n").append(member); if(member.equals(local_addr)) sb.append(" (myself)"); sb.append(":\n"); sb.append(val); sb.append('\n'); } combined_msgs_sec=tmp / final_results.size(); sb.append("\ncombined: ").append(f.format(combined_msgs_sec)). append(" msgs/sec averaged over all receivers\n"); System.out.println(sb.toString()); if(log.isInfoEnabled()) log.info(sb.toString()); } private void dumpSenders() { StringBuffer sb=new StringBuffer(); dump(this.senders, sb); System.out.println(sb.toString()); } private void dump(Map map, StringBuffer sb) { Map.Entry entry; Object mySender; MemberInfo mi; MemberInfo combined=new MemberInfo(0); combined.start = Long.MAX_VALUE; combined.stop = Long.MIN_VALUE; sb.append("\n-- local results:\n"); for(Iterator it2=map.entrySet().iterator(); it2.hasNext();) { entry=(Map.Entry)it2.next(); mySender=entry.getKey(); mi=(MemberInfo)entry.getValue(); combined.start=Math.min(combined.start, mi.start); combined.stop=Math.max(combined.stop, mi.stop); combined.num_msgs_expected+=mi.num_msgs_expected; combined.num_msgs_received+=mi.num_msgs_received; combined.total_bytes_received+=mi.total_bytes_received; sb.append("sender: ").append(mySender).append(": ").append(mi).append('\n'); } } private String dumpStats(long received_msgs) { StringBuffer sb=new StringBuffer(); if(gnuplot_output) sb.append(received_msgs).append(' '); else sb.append("\nmsgs_received=").append(received_msgs); if(gnuplot_output) sb.append(Runtime.getRuntime().freeMemory() / 1000.0).append(' '); else sb.append(", free_mem=").append(Runtime.getRuntime().freeMemory() / 1000.0); if(gnuplot_output) sb.append(Runtime.getRuntime().totalMemory() / 1000.0).append(' '); else sb.append(", total_mem=").append(Runtime.getRuntime().totalMemory() / 1000.0).append('\n'); dumpThroughput(sb, received_msgs); if(dump_transport_stats) { Map stats=transport.dumpStats(); if(stats != null) { print(stats, sb); } } return sb.toString(); } private void print(Map stats, StringBuffer sb) { sb.append("\ntransport stats:\n"); Map.Entry entry; Object key, val; for(Iterator it=stats.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=entry.getKey(); val=entry.getValue(); sb.append(key).append(": ").append(val).append("\n"); } } private void dumpThroughput(StringBuffer sb, long received_msgs) { double tmp; long current=System.currentTimeMillis(); if(current - start == 0 || current - last_dump == 0) return; tmp=(1000 * received_msgs) / (current - start); if(gnuplot_output) sb.append(tmp).append(' '); else sb.append("total_msgs_sec=").append(tmp).append(" [msgs/sec]"); tmp=(received_msgs * msg_size) / (current - start); if(gnuplot_output) sb.append(tmp).append(' '); else sb.append("\ntotal_throughput=").append(tmp).append(" [KB/sec]"); tmp=(1000 * log_interval) / (current - last_dump); if(gnuplot_output) sb.append(tmp).append(' '); else { sb.append("\nrolling_msgs_sec (last ").append(log_interval).append(" msgs)="); sb.append(tmp).append(" [msgs/sec]"); } tmp=(log_interval * msg_size) / (current - last_dump); if(gnuplot_output) sb.append(tmp).append(' '); else { sb.append("\nrolling_throughput (last ").append(log_interval).append(" msgs)="); sb.append(tmp).append(" [KB/sec]\n"); } last_dump=current; } void runDiscoveryPhase() throws Exception { sendDiscoveryRequest(); sendDiscoveryResponse(); synchronized(this.members) { System.out.println("-- waiting for " + num_members + " members to join"); while(this.members.size() < num_members) { this.members.wait(2000); sendDiscoveryRequest(); sendDiscoveryResponse(); } heard_from.addAll(members); System.out.println("-- members: " + this.members.size()); } } void sendDiscoveryRequest() throws Exception { Data d=new Data(Data.DISCOVERY_REQ); transport.send(null, generatePayload(d, null)); } void sendDiscoveryResponse() throws Exception { Data d2=new Data(Data.DISCOVERY_RSP); if(sender) { d2.sender=true; d2.num_msgs=Long.parseLong(config.getProperty("num_msgs")); } transport.send(null, generatePayload(d2, null)); } public static void main(String[] args) { Properties config=new Properties(); boolean sender=false, verbose=false, jmx=false; Test t=null; for(int i=0; i < args.length; i++) { if("-sender".equals(args[i])) { config.put("sender", "true"); sender=true; continue; } if("-receiver".equals(args[i])) { config.put("sender", "false"); sender=false; continue; } if("-config".equals(args[i])) { String config_file=args[++i]; config.put("config", config_file); continue; } if("-props".equals(args[i])) { String props=args[++i]; config.put("props", props); continue; } if("-verbose".equals(args[i])) { verbose=true; continue; } if("-jmx".equals(args[i])) { jmx=true; continue; } help(); return; } try { t=new Test(); t.start(config, verbose, jmx); t.runDiscoveryPhase(); if(sender) { t.sendMessages(); } synchronized(t) { int i=0; while(t.allReceived() == false) { t.wait(2000); // if(i > 5 && i % 10 == 0) { // t.dumpSenders(); } } if(t.jmx) { System.out.println("jmx=true: not terminating"); if(t != null) { t.stop(); t=null; } while(true) { Util.sleep(60000); } } } catch(Exception e) { e.printStackTrace(); } finally { if(t != null) { t.stop(); } } } static void help() { System.out.println("Test [-help] ([-sender] | [-receiver]) " + "[-config <config file>] [-props <stack config>] [-verbose] [-jmx]"); } private class ResultsPublisher implements Runnable { final long interval=1000; boolean running=true; Thread t; void start() { if(t == null) { t=new Thread(this, "ResultsPublisher"); t.setDaemon(true); t.start(); } } void stop() { if(t != null && t.isAlive()) { Thread tmp=t; t=null; tmp.interrupt(); } } public void run() { try { while(t != null) { sendResults(); Util.sleep(interval); } } catch(Exception e) { e.printStackTrace(); } } } }
package org.hawk.osgiserver; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.hawk.core.IAbstractConsole; import org.hawk.core.IHawk; import org.hawk.core.IHawkFactory; import org.hawk.core.IMetaModelResourceFactory; import org.hawk.core.IMetaModelUpdater; import org.hawk.core.IModelIndexer; import org.hawk.core.IModelIndexer.ShutdownRequestType; import org.hawk.core.IModelResourceFactory; import org.hawk.core.IModelUpdater; import org.hawk.core.IVcsManager; import org.hawk.core.graph.IGraphChangeListener; import org.hawk.core.graph.IGraphDatabase; import org.hawk.core.query.IQueryEngine; import org.hawk.core.util.HawkConfig; import org.hawk.core.util.HawkProperties; import org.hawk.core.util.HawksConfig; import org.osgi.service.prefs.BackingStoreException; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class HModel { private static IAbstractConsole CONSOLE = new SLF4JConsole(); public static IAbstractConsole getConsole() { if (CONSOLE == null) CONSOLE = new SLF4JConsole(); return CONSOLE; } public static void setConsole(IAbstractConsole c) { CONSOLE = c; } public static HModel create(IHawkFactory hawkFactory, String name, File storageFolder, String location, String dbType, List<String> plugins, HManager manager, char[] apw, int minDelay, int maxDelay) throws Exception { if (minDelay > maxDelay) { throw new IllegalArgumentException("minimum delay must be less than or equal to maximum delay"); } else if (minDelay < 0) { throw new IllegalArgumentException("minimum delay must not be negative"); } else if (maxDelay < 0) { throw new IllegalArgumentException("maximum delay must not be negative"); } HModel hm = new HModel(manager, hawkFactory, name, storageFolder, location); if (dbType != null) { hm.hawk.setDbtype(dbType); } // TODO use plugins list to enable only these plugins IGraphDatabase db = null; final IAbstractConsole console = getConsole(); try { // create the indexer with relevant database console.println("Creating Hawk indexer..."); if (hawkFactory.instancesCreateGraph()) { console.println("Setting up hawk's back-end store:"); db = manager.createGraph(hm.hawk); db.run(storageFolder, console); hm.hawk.getModelIndexer().setDB(db, true); } // hard coded metamodel updater? IMetaModelUpdater metaModelUpdater = manager.getMetaModelUpdater(); console.println("Setting up hawk's metamodel updater:\n" + metaModelUpdater.getName()); hm.hawk.getModelIndexer().setMetaModelUpdater(metaModelUpdater); hm.hawk.getModelIndexer().setAdminPassword(apw); hm.hawk.getModelIndexer().init(minDelay, maxDelay); manager.addHawk(hm); manager.saveHawkToMetadata(hm); console.println("Created Hawk indexer!"); return hm; } catch (Exception e) { console.printerrln("Adding of indexer aborted, please try again.\n" + "Shutting down and removing back-end (if it was created)"); console.printerrln(e); try { if (db != null) { db.delete(); } } catch (Exception e2) { throw e2; } console.printerrln("aborting finished."); throw e; } } /** * Loads a previously existing Hawk instance from its {@link HawkConfig}. */ public static HModel load(HawkConfig config, HManager manager) throws Exception { try { final IHawkFactory hawkFactory = manager.createHawkFactory(config.getHawkFactory()); HModel hm = new HModel(manager, hawkFactory, config.getName(), new File(config.getStorageFolder()), config.getLocation()); // hard coded metamodel updater? IMetaModelUpdater metaModelUpdater = manager.getMetaModelUpdater(); hm.hawk.getModelIndexer().setMetaModelUpdater(metaModelUpdater); return hm; } catch (Throwable e) { System.err.println("Exception in trying to add create Indexer from folder:"); System.err.println(e.getMessage()); e.printStackTrace(); System.err.println("Adding of indexer aborted, please try again"); return null; } } private List<String> allowedPlugins = new ArrayList<String>(); private final IHawk hawk; private final IHawkFactory hawkFactory; private final HManager manager; private final String hawkLocation; /** * Constructor for loading existing local Hawk instances and * creating/loading custom {@link IHawk} implementations. */ public HModel(HManager manager, IHawkFactory hawkFactory, String name, File storageFolder, String location) throws Exception { this.hawkFactory = hawkFactory; this.hawk = hawkFactory.create(name, storageFolder, location, getConsole()); this.manager = manager; this.hawkLocation = location; if (hawkFactory.instancesAreExtensible()) { final IAbstractConsole console = getConsole(); // set up plugins // first get all of type (static callto HawkOSGIConfigManager) // check each one has the an ID that was selected // create VCS // call m.add console.println("adding metamodel resource factories:"); for (IConfigurationElement mmparse : manager.getMmps()) { IMetaModelResourceFactory f = (IMetaModelResourceFactory) mmparse .createExecutableExtension("MetaModelParser"); this.hawk.getModelIndexer().addMetaModelResourceFactory(f); console.println(f.getHumanReadableName()); } console.println("adding model resource factories:"); for (IConfigurationElement mparse : manager.getMps()) { IModelResourceFactory f = (IModelResourceFactory) mparse.createExecutableExtension("ModelParser"); this.hawk.getModelIndexer().addModelResourceFactory(f); console.println(f.getHumanReadableName()); } console.println("adding query engines:"); for (IConfigurationElement ql : manager.getLanguages()) { IQueryEngine q = (IQueryEngine) ql.createExecutableExtension("query_language"); this.hawk.getModelIndexer().addQueryEngine(q); console.println(q.getType()); } console.println("adding model updaters:"); for (IConfigurationElement updater : manager.getUps()) { IModelUpdater u = (IModelUpdater) updater.createExecutableExtension("ModelUpdater"); this.hawk.getModelIndexer().addModelUpdater(u); console.println(u.getName()); } console.println("adding graph change listeners:"); for (IConfigurationElement listener : manager.getGraphChangeListeners()) { IGraphChangeListener l = (IGraphChangeListener) listener.createExecutableExtension("class"); l.setModelIndexer(this.hawk.getModelIndexer()); this.hawk.getModelIndexer().addGraphChangeListener(l); console.println(l.getName()); } } } public void addDerivedAttribute(String metamodeluri, String typename, String attributename, String attributetype, Boolean isMany, Boolean isOrdered, Boolean isUnique, String derivationlanguage, String derivationlogic) throws Exception { hawk.getModelIndexer().addDerivedAttribute(metamodeluri, typename, attributename, attributetype, isMany, isOrdered, isUnique, derivationlanguage, derivationlogic); } private void loadEncryptedVCS(String loc, String type, String user, String pass) throws Exception { if (!this.getLocations().contains(loc)) { String decryptedUser = user; if (decryptedUser != null && !"".equals(decryptedUser)) { decryptedUser = hawk.getModelIndexer().decrypt(user); } String decryptedPass = pass; if (decryptedPass != null && !"".equals(decryptedPass)) { decryptedPass = hawk.getModelIndexer().decrypt(pass); } IVcsManager mo = manager.createVCSManager(type); mo.run(loc, decryptedUser, decryptedPass, getConsole()); hawk.getModelIndexer().addVCSManager(mo, false); } } public void addIndexedAttribute(String metamodeluri, String typename, String attributename) throws Exception { hawk.getModelIndexer().addIndexedAttribute(metamodeluri, typename, attributename); } public void addVCS(String loc, String type, String user, String pass) { try { if (!this.getLocations().contains(loc)) { IVcsManager mo = manager.createVCSManager(type); mo.run(loc, user, pass, getConsole()); hawk.getModelIndexer().addVCSManager(mo, true); } } catch (Exception e) { getConsole().printerrln(e); } } /** * Registers a new graph change listener into the model indexer, if it * wasn't already registered. Otherwise, it does nothing. */ public boolean addGraphChangeListener(IGraphChangeListener changeListener) { return hawk.getModelIndexer().addGraphChangeListener(changeListener); } /** * Removes a new graph change listener from the model indexer, if it was * already registered. Otherwise, it does nothing. */ public boolean removeGraphChangeListener(IGraphChangeListener changeListener) { return hawk.getModelIndexer().removeGraphChangeListener(changeListener); } /** * Performs a context-aware query and returns its result. The result must be * a Double, a String, an Integer, a ModelElement, the null reference or an * Iterable of these things. * * @throws NoSuchElementException * Unknown query language. */ public Object contextFullQuery(File query, String ql, Map<String, String> context) throws Exception { IQueryEngine q = hawk.getModelIndexer().getKnownQueryLanguages().get(ql); if (q == null) { throw new NoSuchElementException(); } return q.contextfullQuery(hawk.getModelIndexer().getGraph(), query, context); } /** * Performs a context-aware query and returns its result. For the result * types, see {@link #contextFullQuery(File, String, Map)}. * * @throws NoSuchElementException * Unknown query language. */ public Object contextFullQuery(String query, String ql, Map<String, String> context) throws Exception { IQueryEngine q = hawk.getModelIndexer().getKnownQueryLanguages().get(ql); if (q == null) { throw new NoSuchElementException(); } return q.contextfullQuery(hawk.getModelIndexer().getGraph(), query, context); } public void delete() throws BackingStoreException { removeHawkFromMetadata(getHawkConfig()); File f = hawk.getModelIndexer().getParentFolder(); while (this.isRunning()) { try { hawk.getModelIndexer().shutdown(ShutdownRequestType.ONLY_LOCAL); } catch (Exception e) { e.printStackTrace(); } } if (f.exists()) { System.err.println("hawk removed from ui but persistence remains at: " + f); } } /** * Returns a {@link HawkConfig} from which this instance can be reloaded. */ public HawkConfig getHawkConfig() { return new HawkConfig(getName(), getFolder(), hawkLocation, hawkFactory.getClass().getName()); } public boolean exists() { return hawk != null && hawk.exists(); } public List<String> getAllowedPlugins() { return allowedPlugins; } public Collection<String> getDerivedAttributes() { return hawk.getModelIndexer().getDerivedAttributes(); } public String getFolder() { return hawk.getModelIndexer().getParentFolder().toString(); } public IGraphDatabase getGraph() { return hawk.getModelIndexer().getGraph(); } public Collection<String> getIndexedAttributes() { return hawk.getModelIndexer().getIndexedAttributes(); } public Collection<String> getIndexes() { return hawk.getModelIndexer().getIndexes(); } public Set<String> getKnownQueryLanguages() { return hawk.getModelIndexer().getKnownQueryLanguages().keySet(); } public Collection<String> getLocations() { List<String> locations = new ArrayList<String>(); for (IVcsManager o : getRunningVCSManagers()) { locations.add(o.getLocation()); } return locations; } public Collection<IVcsManager> getRunningVCSManagers() { return hawk.getModelIndexer().getRunningVCSManagers(); } public String getName() { return hawk.getModelIndexer().getName(); } public ArrayList<String> getRegisteredMetamodels() { return new ArrayList<String>(hawk.getModelIndexer().getKnownMMUris()); } public List<IVcsManager> getVCSInstances() { return manager.getVCSInstances(); } public boolean isRunning() { return hawk.getModelIndexer().isRunning(); } /** * For the result types, see {@link #contextFullQuery(File, String, Map)}. */ public Object query(File query, String ql) throws Exception { IQueryEngine q = hawk.getModelIndexer().getKnownQueryLanguages().get(ql); return q.contextlessQuery(hawk.getModelIndexer().getGraph(), query); } /** * For the result types, see {@link #contextFullQuery(File, String, Map)}. */ public Object query(String query, String ql) throws Exception { IQueryEngine q = hawk.getModelIndexer().getKnownQueryLanguages().get(ql); return q.contextlessQuery(hawk.getModelIndexer().getGraph(), query); } public boolean registerMeta(File... f) { try { hawk.getModelIndexer().registerMetamodel(f); } catch (Exception e) { getConsole().printerrln(e); return false; } return true; } public void removeHawkFromMetadata(HawkConfig config) throws BackingStoreException { IEclipsePreferences preferences = HManager.getPreferences(); String xml = preferences.get("config", null); if (xml != null) { XStream stream = new XStream(new DomDriver()); stream.processAnnotations(HawksConfig.class); stream.processAnnotations(HawkConfig.class); stream.setClassLoader(HawksConfig.class.getClassLoader()); HawksConfig hc = (HawksConfig) stream.fromXML(xml); hc.removeLoc(config); xml = stream.toXML(hc); preferences.put("config", xml); preferences.flush(); } else { getConsole().printerrln("removeHawkFromMetadata tried to load preferences but it could not."); } } public boolean start(HManager manager, char[] apw) { try { hawk.getModelIndexer().setAdminPassword(apw); final HawkProperties hp = loadIndexerMetadata(); if (hawkFactory.instancesCreateGraph()) { // create the indexer with relevant database IGraphDatabase db = manager.createGraph(hawk); db.run(new File(this.getFolder()), getConsole()); hawk.getModelIndexer().setDB(db, false); } hawk.getModelIndexer().init(hp.getMinDelay(), hp.getMaxDelay()); } catch (Exception e) { getConsole().printerrln(e); } return hawk.getModelIndexer().isRunning(); } public void stop(ShutdownRequestType requestType) { try { hawk.getModelIndexer().shutdown(requestType); } catch (Exception e) { getConsole().printerrln(e); } } public void sync() throws Exception { hawk.getModelIndexer().requestImmediateSync(); } @Override public String toString() { String ret = ""; try { ret = getName() + " [" + this.getFolder() + "] "; } catch (Exception e) { e.printStackTrace(); } return ret; } public List<String> validateExpression(String derivationlanguage, String derivationlogic) { return hawk.getModelIndexer().validateExpression(derivationlanguage, derivationlogic); } private HawkProperties loadIndexerMetadata() throws Exception { XStream stream = new XStream(new DomDriver()); stream.processAnnotations(HawkProperties.class); stream.setClassLoader(HawkProperties.class.getClassLoader()); String path = hawk.getModelIndexer().getParentFolder() + File.separator + "properties.xml"; HawkProperties hp = (HawkProperties) stream.fromXML(new File(path)); hawk.setDbtype(hp.getDbType()); for (String[] s : hp.getMonitoredVCS()) { loadEncryptedVCS(s[0], s[1], s[2], s[3]); } return hp; } public void removeDerivedAttribute(String metamodelUri, String typeName, String attributeName) { // TODO Auto-generated method stub } public void removeIndexedAttribute(String metamodelUri, String typename, String attributename) { // TODO Auto-generated method stub } public void removeRepository(String uri) throws Exception { // TODO Auto-generated method stub } public IModelIndexer getIndexer() { return hawk.getModelIndexer(); } public void configurePolling(int base, int max) { // TODO Auto-generated method stub } public void removeMetamodels(String[] selectedMetamodels) { try { hawk.getModelIndexer().removeMetamodels(selectedMetamodels); } catch (Exception e) { System.err.println("error in removemetamodel:"); e.printStackTrace(); } } }
/* * $Log: SoapWrapperPipe.java,v $ * Revision 1.6 2011-12-23 16:02:40 europe\m168309 * added soapBodyStyleSheet attribute * * Revision 1.5 2011/12/15 10:52:11 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * added soapHeaderStyleSheet, removeOutputNamespaces and outputNamespace attribute * * Revision 1.4 2011/11/30 13:52:00 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * adjusted/reversed "Upgraded from WebSphere v5.1 to WebSphere v6.1" * * Revision 1.1 2011/10/19 14:49:53 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * Upgraded from WebSphere v5.1 to WebSphere v6.1 * * Revision 1.2 2011/09/23 11:33:25 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * added attributes encodingStyle and serviceNamespace * * Revision 1.1 2011/09/14 14:14:01 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * first version * * */ package nl.nn.adapterframework.soap; import java.io.IOException; import java.util.Map; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.lang.StringUtils; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.core.PipeStartException; import nl.nn.adapterframework.parameters.ParameterResolutionContext; import nl.nn.adapterframework.pipes.FixedForwardPipe; import nl.nn.adapterframework.util.DomBuilderException; import nl.nn.adapterframework.util.TransformerPool; import nl.nn.adapterframework.util.XmlUtils; /** * Pipe to wrap or unwrap a message from/into a SOAP Envelope. * * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Pipe</td><td>&nbsp;</td></tr> * <tr><td>{@link #setDirection(String) direction}</td><td>either <code>wrap</code> or <code>unwrap</code></td><td>wrap</td></tr> * <tr><td>{@link #setSoapHeaderSessionKey(String) soapHeaderSessionKey}</td><td> * <table> * <tr><td><code>direction=unwrap</code></td><td>name of the session key to store the content of the SOAP Header from the request in</td></tr> * <tr><td><code>direction=wrap</code></td><td>name of the session key to retrieve the content of the SOAP Header for the response from. If the attribute soapHeaderStyleSheet is not empty, the attribute soapHeaderStyleSheet precedes this attribute</td></tr> * </table> * </td><td>&nbsp;</td></tr> * <tr><td>{@link #setEncodingStyle(String) encodingStyle}</td><td>the encodingStyle to be set in the SOAP Header</td><td>&nbsp;</td></tr> * <tr><td>{@link #setServiceNamespace(String) serviceNamespace}</td><td>the namespace of the message sent. Identifies the service to be called. May be overriden by an actual namespace setting in the message to be sent</td><td>&nbsp;</td></tr> * <tr><td>{@link #setSoapHeaderStyleSheet(String) soapHeaderStyleSheet}</td><td>(only used when <code>direction=wrap</code>) stylesheet to create the content of the SOAP Header. As input for this stylesheet a dummy xml string is used. Note: outputType=<code>xml</code> and xslt2=<code>true</code></td><td>&nbsp;</td></tr> * <tr><td>{@link #setSoapBodyStyleSheet(String) soapBodyStyleSheet}</td><td>(only used when <code>direction=wrap</code>) stylesheet to apply to the input message. Note: outputType=<code>xml</code> and xslt2=<code>true</code></td><td>&nbsp;</td></tr> * <tr><td>{@link #setRemoveOutputNamespaces(boolean) removeOutputNamespaces}</td><td>(only used when <code>direction=unwrap</code>) when <code>true</code>, namespaces (and prefixes) in the content of the SOAP Body are removed</td><td>false</td></tr> * <tr><td>{@link #setOutputNamespace(String) outputNamespace}</td><td>(only used when <code>direction=wrap</code>) when not empty, this namespace is added to the root element in the SOAP Body</td><td>&nbsp;</td></tr> * <table> * <table border="1"> * <tr><th>nested elements</th><th>description</th></tr> * <tr><td>{@link nl.nn.adapterframework.parameters.Parameter param}</td><td>any parameters defined on the pipe will be applied to the created transformer</td></tr> * </table> * </p> * <p><b>Exits:</b> * <table border="1"> * <tr><th>state</th><th>condition</th></tr> * <tr><td>"success"</td><td>default</td></tr> * <tr><td><i>{@link #setForwardName(String) forwardName}</i></td><td>if specified</td></tr> * </table> * </p> * @version Id * @author Peter Leeuwenburgh */ public class SoapWrapperPipe extends FixedForwardPipe { private String direction = "wrap"; private String soapHeaderSessionKey = null; private String encodingStyle = null; private String serviceNamespace = null; private String soapHeaderStyleSheet = null; private String soapBodyStyleSheet = null; private boolean removeOutputNamespaces = false; private String outputNamespace = null; private SoapWrapper soapWrapper = null; private TransformerPool soapHeaderTp = null; private TransformerPool soapBodyTp = null; private TransformerPool removeOutputNamespacesTp = null; private TransformerPool outputNamespaceTp = null; public void configure() throws ConfigurationException { super.configure(); soapWrapper = SoapWrapper.getInstance(); if (StringUtils.isNotEmpty(getSoapHeaderStyleSheet())) { soapHeaderTp = TransformerPool.configureTransformer0(getLogPrefix(null), null, null, getSoapHeaderStyleSheet(), "xml", false, getParameterList(), true); } if (StringUtils.isNotEmpty(getSoapBodyStyleSheet())) { soapBodyTp = TransformerPool.configureTransformer0(getLogPrefix(null), null, null, getSoapBodyStyleSheet(), "xml", false, getParameterList(), true); } try { if (isRemoveOutputNamespaces()) { String removeOutputNamespaces_xslt = XmlUtils.makeRemoveNamespacesXslt(true, false); removeOutputNamespacesTp = new TransformerPool(removeOutputNamespaces_xslt); } if (StringUtils.isNotEmpty(getOutputNamespace())) { String outputNamespace_xslt = XmlUtils.makeAddRootNamespaceXslt(getOutputNamespace(), true, false); outputNamespaceTp = new TransformerPool(outputNamespace_xslt); } } catch (TransformerConfigurationException e) { throw new ConfigurationException(getLogPrefix(null) + "cannot create transformer", e); } } public void start() throws PipeStartException { super.start(); if (soapHeaderTp != null) { try { soapHeaderTp.open(); } catch (Exception e) { throw new PipeStartException(getLogPrefix(null)+"cannot start SOAP Header TransformerPool", e); } } if (soapBodyTp != null) { try { soapBodyTp.open(); } catch (Exception e) { throw new PipeStartException(getLogPrefix(null)+"cannot start SOAP Body TransformerPool", e); } } if (removeOutputNamespacesTp != null) { try { removeOutputNamespacesTp.open(); } catch (Exception e) { throw new PipeStartException(getLogPrefix(null)+"cannot start Remove Output Namespaces TransformerPool", e); } } if (outputNamespaceTp != null) { try { outputNamespaceTp.open(); } catch (Exception e) { throw new PipeStartException(getLogPrefix(null)+"cannot start Output Namespace TransformerPool", e); } } } public void stop() { super.stop(); if (soapHeaderTp != null) { soapHeaderTp.close(); } if (soapBodyTp != null) { soapBodyTp.close(); } if (removeOutputNamespacesTp != null) { removeOutputNamespacesTp.close(); } if (outputNamespaceTp != null) { outputNamespaceTp.close(); } } public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException { String result; try { if ("wrap".equalsIgnoreCase(getDirection())) { String soapHeader = null; if (soapHeaderTp != null) { ParameterResolutionContext prc = new ParameterResolutionContext("<dummy/>", session); Map parameterValues = null; if (getParameterList()!=null) { parameterValues = prc.getValueMap(getParameterList()); } soapHeader = soapHeaderTp.transform(prc.getInputSource(), parameterValues); } else { if (StringUtils.isNotEmpty(getSoapHeaderSessionKey())) { soapHeader = (String) session.get(getSoapHeaderSessionKey()); } } String payload; if (outputNamespaceTp != null) { payload = outputNamespaceTp.transform(input.toString(), null, true); } else { payload = input.toString(); } if (soapBodyTp != null) { ParameterResolutionContext prc = new ParameterResolutionContext(payload, session); Map parameterValues = null; if (getParameterList()!=null) { parameterValues = prc.getValueMap(getParameterList()); } payload = soapBodyTp.transform(prc.getInputSource(), parameterValues); } result = wrapMessage(payload, soapHeader); } else { result = unwrapMessage(input.toString()); if (StringUtils.isEmpty(result)) { throw new PipeRunException(this, getLogPrefix(session) + "SOAP Body is empty or message is not a SOAP Message"); } if (soapWrapper.getFaultCount(input.toString()) > 0) { throw new PipeRunException(this, getLogPrefix(session) + "SOAP Body contains SOAP Fault"); } if (StringUtils.isNotEmpty(getSoapHeaderSessionKey())) { String soapHeader = soapWrapper.getHeader(input.toString()); session.put(getSoapHeaderSessionKey(), soapHeader); } if (removeOutputNamespacesTp != null) { result = removeOutputNamespacesTp.transform(result, null, true); } } } catch (Throwable t) { throw new PipeRunException(this, getLogPrefix(session) + " Unexpected exception during (un)wrapping ", t); } return new PipeRunResult(getForward(), result); } protected String unwrapMessage(String messageText) throws DomBuilderException, TransformerException, IOException { return soapWrapper.getBody(messageText); } protected String wrapMessage(String message, String soapHeader) throws DomBuilderException, TransformerException, IOException { return soapWrapper.putInEnvelope(message, getEncodingStyle(), getServiceNamespace(), soapHeader); } public String getDirection() { return direction; } public void setDirection(String string) { direction = string; } public void setSoapHeaderSessionKey(String string) { soapHeaderSessionKey = string; } public String getSoapHeaderSessionKey() { return soapHeaderSessionKey; } public void setEncodingStyle(String string) { encodingStyle = string; } public String getEncodingStyle() { return encodingStyle; } public void setServiceNamespace(String string) { serviceNamespace = string; } public String getServiceNamespace() { return serviceNamespace; } public void setSoapHeaderStyleSheet(String string){ this.soapHeaderStyleSheet = string; } public String getSoapHeaderStyleSheet() { return soapHeaderStyleSheet; } public void setSoapBodyStyleSheet(String string){ this.soapBodyStyleSheet = string; } public String getSoapBodyStyleSheet() { return soapBodyStyleSheet; } public void setRemoveOutputNamespaces(boolean b) { removeOutputNamespaces = b; } public boolean isRemoveOutputNamespaces() { return removeOutputNamespaces; } public void setOutputNamespace(String string) { outputNamespace = string; } public String getOutputNamespace() { return outputNamespace; } }
package josuezelaya_lab3; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JOptionPane; public class JosueZelaya_Lab3 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); String opcion = " "; while (!opcion.equals("d")) { opcion = JOptionPane.showInputDialog("Menu\n" + "a- Agregar\n" + "b- Modificar\n" + "c- Eliminar\n" + "d- Salir!\n"); } } }
package nu.nerd.easyrider; import java.util.function.BooleanSupplier; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.Horse; import org.bukkit.inventory.ItemStack; import nu.nerd.easyrider.db.SavedHorse; /** * A task that scans all horses in all currently loaded chunks in a specified * world. */ public class ScanLoadedChunksTask implements BooleanSupplier { /** * Constructor. * * @param world the world whose loaded chunks are scanned. */ public ScanLoadedChunksTask(World world) { _world = world; } /** * @see java.util.function.BooleanSupplier#getAsBoolean() */ @Override public boolean getAsBoolean() { long start = System.nanoTime(); long elapsed; if (_chunks == null) { _chunks = _world.getLoadedChunks(); if (EasyRider.CONFIG.DEBUG_SCANS) { elapsed = System.nanoTime() - start; EasyRider.PLUGIN.getLogger().info("Get " + _world.getName() + " loaded chunks: " + elapsed * 0.001 + " microseconds."); } return true; } int startIndex = _index; while (_index < _chunks.length) { Chunk chunk = _chunks[_index++]; if (chunk.isLoaded()) { for (Entity entity : chunk.getEntities()) { if (entity instanceof Horse) { Horse horse = (Horse) entity; SavedHorse savedHorse = EasyRider.DB.findHorse(horse); if (savedHorse != null) { EasyRider.DB.observe(savedHorse, horse); if (savedHorse.isAbandoned()) { EasyRider.DB.freeHorse(savedHorse, horse); } } else if (horse.getOwner() != null) { // Version 1.7.3 wrongly dropped the record for // abandoned horses. Those horses need their owner // cleared. Their inv will be empty, at least. horse.setOwner(null); horse.setTamed(false); horse.setDomestication(1); if (horse.isCarryingChest()) { horse.setCarryingChest(false); horse.getWorld().dropItemNaturally(horse.getLocation(), new ItemStack(Material.CHEST)); } } } } } elapsed = System.nanoTime() - start; if (elapsed > EasyRider.CONFIG.SCAN_TIME_LIMIT_MICROS * 1000) { if (EasyRider.CONFIG.DEBUG_SCANS) { EasyRider.PLUGIN.getLogger().info("Processed " + (_index - startIndex) + " chunks in " + elapsed * 0.001 + " microseconds."); } return true; } } if (EasyRider.CONFIG.DEBUG_SCANS) { EasyRider.PLUGIN.getLogger().info("Scan of " + _world.getName() + " complete."); } return false; } /** * The World whose chunks are scanned. */ protected World _world; /** * Array of loaded chunks at the start of the scan. */ protected Chunk[] _chunks; /** * Index of next chunk to process in _chunks. */ protected int _index; } // class ScanLoadedChunksTask
package org.apache.fop.rtf.renderer; import org.apache.fop.apps.StructureHandler; import org.apache.fop.layout.FontInfo; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.pagination.PageSequence; import org.apache.fop.fo.pagination.LayoutMasterSet; import org.apache.fop.fo.pagination.SimplePageMaster; import org.apache.fop.fo.Title; import org.apache.fop.fo.flow.Block; import org.apache.fop.fo.flow.Flow; import org.jfor.jfor.rtflib.rtfdoc.RtfFile; import org.jfor.jfor.rtflib.rtfdoc.RtfSection; import org.jfor.jfor.rtflib.rtfdoc.RtfParagraph; import org.jfor.jfor.rtflib.rtfdoc.RtfDocumentArea; import org.xml.sax.SAXException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.IOException; /** * RTF Handler: generates RTF output using the structure events from * the FO Tree sent to this structure handler. * * @author bdelacretaz@apache.org */ public class RTFHandler extends StructureHandler { private FontInfo _fontInfo = new FontInfo(); private RtfFile _rtfFile; private final OutputStream _os; private RtfSection _sect; private RtfDocumentArea _docArea; private RtfParagraph _para; private boolean _warned = false; private static final String ALPHA_WARNING = "WARNING: RTF renderer is veryveryalpha at this time, see class org.apache.fop.rtf.renderer.RTFHandler"; public RTFHandler(OutputStream os) { _os = os; // use pdf fonts for now, this is only for resolving names org.apache.fop.render.pdf.FontSetup.setup(_fontInfo, null); System.err.println(ALPHA_WARNING); } public FontInfo getFontInfo() { return _fontInfo; } public void startDocument() throws SAXException { // FIXME sections should be created try { _rtfFile = new RtfFile(new OutputStreamWriter(_os)); _docArea = _rtfFile.startDocumentArea(); } catch(IOException ioe) { // FIXME could we throw Exception in all StructureHandler events? throw new SAXException("IOException: " + ioe); } } public void endDocument() throws SAXException { try { _rtfFile.flush(); } catch(IOException ioe) { // FIXME could we throw Exception in all StructureHandler events? throw new SAXException("IOException: " + ioe); } } public void startPageSequence(PageSequence pageSeq, Title seqTitle, LayoutMasterSet lms) { try { _sect = _docArea.newSection(); if(!_warned) { _sect.newParagraph().newText(ALPHA_WARNING); _warned = true; } } catch(IOException ioe) { // FIXME could we throw Exception in all StructureHandler events? throw new Error("IOException: " + ioe); } } public void endPageSequence(PageSequence pageSeq) throws FOPException { } public void startFlow(Flow fl) { } public void endFlow(Flow fl) { } public void startBlock(Block bl) { try { _para = _sect.newParagraph(); } catch(IOException ioe) { // FIXME could we throw Exception in all StructureHandler events? throw new Error("IOException: " + ioe); } } public void endBlock(Block bl) { } public void characters(char data[], int start, int length) { try { _para.newText(new String(data,start,length)); } catch(IOException ioe) { // FIXME could we throw Exception in all StructureHandler events? throw new Error("IOException: " + ioe); } } }
package org.apache.xerces.readers; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.xml.sax.Locator; import org.xml.sax.InputSource; import java.io.IOException; /** * Reader for processing internal entity replacement text. * <p> * This reader processes data contained within strings kept * in the string pool. It provides the support for both * general and parameter entities. The location support * as we are processing the replacement text is somewhat * poor and needs to be updated when "nested locations" * have been implemented. * <p> * For efficiency, we return instances of this class to a * free list and reuse those instances to process other * strings. * * @version $id$ */ final class StringReader extends XMLEntityReader { /** * Allocate a string reader * * @param entityHandler The current entity handler. * @param errorReporter The current error reporter. * @param sendCharDataAsCharArray true if char data should be reported using * char arrays instead of string handles. * @param lineNumber The line number to return as our position. * @param columnNumber The column number to return as our position. * @param stringHandle The StringPool handle for the data to process. * @param stringPool The string pool. * @param addEnclosingSpaces If true, treat the data to process as if * there were a leading and trailing space * character enclosing the string data. * @return The reader that will process the string data. */ public static StringReader createStringReader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, int lineNumber, int columnNumber, int stringHandle, StringPool stringPool, boolean addEnclosingSpaces) { StringReader reader = null; synchronized (StringReader.class) { reader = fgFreeReaders; if (reader == null) { return new StringReader(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber, stringHandle, stringPool, addEnclosingSpaces); } fgFreeReaders = reader.fNextFreeReader; } reader.init(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber, stringHandle, stringPool, addEnclosingSpaces); return reader; } private StringReader(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, int lineNumber, int columnNumber, int stringHandle, StringPool stringPool, boolean addEnclosingSpaces) { super(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber); fStringPool = stringPool; fData = fStringPool.toString(stringHandle); fCurrentOffset = 0; fEndOffset = fData.length(); if (addEnclosingSpaces) { fMostRecentChar = ' '; fCurrentOffset oweTrailingSpace = hadTrailingSpace = true; } else { fMostRecentChar = fEndOffset == 0 ? -1 : fData.charAt(0); } } private void init(XMLEntityHandler entityHandler, XMLErrorReporter errorReporter, boolean sendCharDataAsCharArray, int lineNumber, int columnNumber, int stringHandle, StringPool stringPool, boolean addEnclosingSpaces) { super.init(entityHandler, errorReporter, sendCharDataAsCharArray, lineNumber, columnNumber); fStringPool = stringPool; fData = fStringPool.toString(stringHandle); fCurrentOffset = 0; fEndOffset = fData.length(); fNextFreeReader = null; if (addEnclosingSpaces) { fMostRecentChar = ' '; fCurrentOffset oweTrailingSpace = hadTrailingSpace = true; } else { fMostRecentChar = fEndOffset == 0 ? -1 : fData.charAt(0); oweTrailingSpace = hadTrailingSpace = false; } } public int addString(int offset, int length) { if (length == 0) return 0; return fStringPool.addString(fData.substring(offset, offset + length)); } public int addSymbol(int offset, int length) { if (length == 0) return 0; return fStringPool.addSymbol(fData.substring(offset, offset + length)); } public void append(XMLEntityHandler.CharBuffer charBuffer, int offset, int length) { boolean addSpace = false; for (int i = 0; i < length; i++) { try { charBuffer.append(fData.charAt(offset++)); } catch (StringIndexOutOfBoundsException ex) { if (offset == fEndOffset + 1 && hadTrailingSpace) { charBuffer.append(' '); } else { System.err.println("StringReader.append()"); throw ex; } } } } private int loadNextChar() { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } return fMostRecentChar; } public XMLEntityHandler.EntityReader changeReaders() throws Exception { XMLEntityHandler.EntityReader nextReader = super.changeReaders(); synchronized (StringReader.class) { fNextFreeReader = fgFreeReaders; fgFreeReaders = this; } return nextReader; } public boolean lookingAtChar(char chr, boolean skipPastChar) throws Exception { int ch = fMostRecentChar; if (ch != chr) { if (ch == -1) { return changeReaders().lookingAtChar(chr, skipPastChar); } return false; } if (skipPastChar) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } } return true; } public boolean lookingAtValidChar(boolean skipPastChar) throws Exception { int ch = fMostRecentChar; if (ch < 0xD800) { if (ch < 0x20 && ch != 0x09 && ch != 0x0A && ch != 0x0D) { if (ch == -1) return changeReaders().lookingAtValidChar(skipPastChar); return false; } if (skipPastChar) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } } return true; } if (ch > 0xFFFD) { return false; } if (ch < 0xDC00) { if (fCurrentOffset + 1 >= fEndOffset) { return false; } ch = fData.charAt(fCurrentOffset + 1); if (ch < 0xDC00 || ch >= 0xE000) { return false; } else if (!skipPastChar) { return true; } else { fCurrentOffset++; } } else if (ch < 0xE000) { return false; } if (skipPastChar) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } } else { fMostRecentChar = fData.charAt(fCurrentOffset); } } return true; } public boolean lookingAtSpace(boolean skipPastChar) throws Exception { int ch = fMostRecentChar; if (ch > 0x20) return false; if (ch == 0x20 || ch == 0x0A || ch == 0x0D || ch == 0x09) { if (skipPastChar) { loadNextChar(); } return true; } if (ch == -1) { return changeReaders().lookingAtSpace(skipPastChar); } return false; } public void skipToChar(char chr) throws Exception { // REVISIT - this will skip invalid characters without reporting them. int ch = fMostRecentChar; while (true) { if (ch == chr) return; if (ch == -1) { changeReaders().skipToChar(chr); return; } ch = loadNextChar(); } } public void skipPastSpaces() throws Exception { int ch = fMostRecentChar; if (ch == -1) { changeReaders().skipPastSpaces(); return; } while (true) { if (ch > 0x20 || (ch != 0x20 && ch != 0x0A && ch != 0x09 && ch != 0x0D)) { fMostRecentChar = ch; return; } if (++fCurrentOffset >= fEndOffset) { changeReaders().skipPastSpaces(); return; } ch = fData.charAt(fCurrentOffset); } } public void skipPastName(char fastcheck) throws Exception { int ch = fMostRecentChar; if (ch < 0x80) { if (ch == -1 || XMLCharacterProperties.fgAsciiInitialNameChar[ch] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) return; } while (true) { ch = loadNextChar(); if (fastcheck == ch) return; if (ch < 0x80) { if (ch == -1 || XMLCharacterProperties.fgAsciiNameChar[ch] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) return; } } } public void skipPastNmtoken(char fastcheck) throws Exception { int ch = fMostRecentChar; while (true) { if (fastcheck == ch) return; if (ch < 0x80) { if (ch == -1 || XMLCharacterProperties.fgAsciiNameChar[ch] == 0) return; } else { if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) return; } ch = loadNextChar(); } } public boolean skippedString(char[] s) throws Exception { int ch = fMostRecentChar; if (ch != s[0]) { if (ch == -1) return changeReaders().skippedString(s); return false; } if (fCurrentOffset + s.length > fEndOffset) return false; for (int i = 1; i < s.length; i++) { if (fData.charAt(fCurrentOffset + i) != s[i]) return false; } fCurrentOffset += (s.length - 1); loadNextChar(); return true; } public int scanInvalidChar() throws Exception { int ch = fMostRecentChar; if (ch == -1) return changeReaders().scanInvalidChar(); loadNextChar(); return ch; } public int scanCharRef(boolean hex) throws Exception { int ch = fMostRecentChar; if (ch == -1) return changeReaders().scanCharRef(hex); int num = 0; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); } else { if (ch < '0' || ch > '9') return XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR; num = ch - '0'; } boolean toobig = false; while (true) { ch = loadNextChar(); if (ch == -1) return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED; if (hex) { if (ch > 'f' || XMLCharacterProperties.fgAsciiXDigitChar[ch] == 0) break; } else { if (ch < '0' || ch > '9') break; } if (hex) { int dig = ch - (ch < 'A' ? '0' : (ch < 'a' ? 'A' : 'a') - 10); num = (num << 4) + dig; } else { int dig = ch - '0'; num = (num * 10) + dig; } if (num > 0x10FFFF) { toobig = true; num = 0; } } if (ch != ';') return XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED; loadNextChar(); if (toobig) return XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE; return num; } public int scanStringLiteral() throws Exception { boolean single; if (!(single = lookingAtChar('\'', true)) && !lookingAtChar('\"', true)) { return XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED; } int offset = fCurrentOffset; char qchar = single ? '\'' : '\"'; while (!lookingAtChar(qchar, false)) { if (!lookingAtValidChar(true)) { return XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR; } } int stringIndex = addString(offset, fCurrentOffset - offset); lookingAtChar(qchar, true); // move past qchar return stringIndex; } // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" public int scanAttValue(char qchar, boolean asSymbol) throws Exception { int offset = fCurrentOffset; while (true) { if (lookingAtChar(qchar, false)) { break; } if (lookingAtChar(' ', true)) { continue; } if (lookingAtSpace(false)) { return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX; } if (lookingAtChar('&', false)) { return XMLEntityHandler.ATTVALUE_RESULT_COMPLEX; } if (lookingAtChar('<', false)) { return XMLEntityHandler.ATTVALUE_RESULT_LESSTHAN; } if (!lookingAtValidChar(true)) { return XMLEntityHandler.ATTVALUE_RESULT_INVALID_CHAR; } } int result = asSymbol ? addSymbol(offset, fCurrentOffset - offset) : addString(offset, fCurrentOffset - offset); lookingAtChar(qchar, true); return result; } // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' // | "'" ([^%&'] | PEReference | Reference)* "'" // The values in the following table are defined as: // 0 - not special // 1 - quote character // 2 - reference // 3 - peref // 4 - invalid public static final byte fgAsciiEntityValueChar[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 0, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public int scanEntityValue(int qchar, boolean createString) throws Exception { int offset = fCurrentOffset; int ch = fMostRecentChar; while (true) { if (ch == -1) { changeReaders(); // do not call next reader, our caller may need to change the parameters return XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT; } if (ch < 0x80) { switch (fgAsciiEntityValueChar[ch]) { case 1: // quote char if (ch == qchar) { if (!createString) return XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED; int length = fCurrentOffset - offset; int result = length == 0 ? StringPool.EMPTY_STRING : addString(offset, length); loadNextChar(); return result; } // the other quote character is not special // fall through case 0: // non-special char if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; ch = fMostRecentChar = ' '; } else { ch = fMostRecentChar = -1; } } else { ch = fMostRecentChar = fData.charAt(fCurrentOffset); } continue; case 2: // reference return XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE; case 3: // peref return XMLEntityHandler.ENTITYVALUE_RESULT_PEREF; case 4: // invalid return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } } else if (ch < 0xD800) { ch = loadNextChar(); } else if (ch >= 0xE000 && (ch <= 0xFFFD || (ch >= 0x10000 && ch <= 0x10FFFF))) { // REVISIT - needs more code to check surrogates. ch = loadNextChar(); } else { return XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR; } } } public boolean scanExpectedName(char fastcheck, StringPool.CharArrayRange expectedName) throws Exception { int ch = fMostRecentChar; if (ch == -1) { return changeReaders().scanExpectedName(fastcheck, expectedName); } if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int nameOffset = fCurrentOffset; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) return false; while (true) { ch = loadNextChar(); if (fastcheck == ch) break; if (ch == -1) break; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } int nameIndex = fStringPool.addSymbol(fData.substring(nameOffset, fCurrentOffset)); // DEFECT !! check name against expected name return true; } public void scanQName(char fastcheck, QName qname) throws Exception { int ch = fMostRecentChar; if (ch == -1) { changeReaders().scanQName(fastcheck, qname); return; } if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int nameOffset = fCurrentOffset; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) { qname.clear(); return; } while (true) { ch = loadNextChar(); if (fastcheck == ch) break; if (ch == -1) break; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } qname.clear(); qname.rawname = fStringPool.addSymbol(fData.substring(nameOffset, fCurrentOffset)); int index = fData.indexOf(':', nameOffset); if (index != -1) { qname.prefix = fStringPool.addSymbol(fData.substring(nameOffset, index)); int indexOfSpaceChar = fData.indexOf( ' ', index + 1 );//one past : look for blank String localPart; if( indexOfSpaceChar != -1 ){//found one localPart = fData.substring(index+1, indexOfSpaceChar ); qname.localpart = fStringPool.addSymbol(localPart); } else{//then get up to end of String int lenfData = fData.length(); localPart = fData.substring( index + 1, fData.length ); qname.localpart = fStringPool.addSymbol(localPart); } qname.localpart = fStringPool.addSymbol(localPart); } else { qname.localpart = qname.rawname; } } // scanQName(char,QName) public int scanName(char fastcheck) throws Exception { int ch = fMostRecentChar; if (ch == -1) { return changeReaders().scanName(fastcheck); } if (!fCalledCharPropInit) { XMLCharacterProperties.initCharFlags(); fCalledCharPropInit = true; } int nameOffset = fCurrentOffset; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_InitialNameCharFlag) == 0) return -1; while (true) { if (++fCurrentOffset >= fEndOffset) { if (oweTrailingSpace) { oweTrailingSpace = false; fMostRecentChar = ' '; } else { fMostRecentChar = -1; } break; } ch = fMostRecentChar = fData.charAt(fCurrentOffset); if (fastcheck == ch) break; if ((XMLCharacterProperties.fgCharFlags[ch] & XMLCharacterProperties.E_NameCharFlag) == 0) break; } int nameIndex = fStringPool.addSymbol(fData.substring(nameOffset, fCurrentOffset)); return nameIndex; } // There are no leading/trailing space checks here because scanContent cannot // be called on a parameter entity reference value. private int recognizeMarkup(int ch) throws Exception { if (ch == -1) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } switch (ch) { case '?': loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_PI; case '!': ch = loadNextChar(); if (ch == -1) { fCurrentOffset -= 2; loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (ch == '-') { ch = loadNextChar(); if (ch == -1) { fCurrentOffset -= 3; loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (ch == '-') { loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_COMMENT; } break; } if (ch == '[') { for (int i = 0; i < 6; i++) { ch = loadNextChar(); if (ch == -1) { fCurrentOffset -= (3 + i); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } if (ch != cdata_string[i]) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } } loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CDSECT; } break; case '/': loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_ETAG; default: return XMLEntityHandler.CONTENT_RESULT_START_OF_ELEMENT; } return XMLEntityHandler.CONTENT_RESULT_MARKUP_NOT_RECOGNIZED; } private int recognizeReference(int ch) throws Exception { if (ch == -1) { return XMLEntityHandler.CONTENT_RESULT_MARKUP_END_OF_INPUT; } // [67] Reference ::= EntityRef | CharRef // [68] EntityRef ::= '&' Name ';' // [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' if (ch == ' loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_START_OF_CHARREF; } else { return XMLEntityHandler.CONTENT_RESULT_START_OF_ENTITYREF; } } public int scanContent(QName element) throws Exception { int ch = fMostRecentChar; if (ch == -1) { return changeReaders().scanContent(element); } int offset = fCurrentOffset; if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiWSCharData[ch]) { case 0: ch = loadNextChar(); break; case 1: ch = loadNextChar(); if (!fInCDSect) { return recognizeMarkup(ch); } break; case 2: ch = loadNextChar(); if (!fInCDSect) { return recognizeReference(ch); } break; case 3: ch = loadNextChar(); if (ch == ']' && fCurrentOffset + 1 < fEndOffset && fData.charAt(fCurrentOffset + 1) == '>') { loadNextChar(); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; } break; case 4: return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; case 5: do { ch = loadNextChar(); if (ch == -1) { callCharDataHandler(offset, fEndOffset, true); return changeReaders().scanContent(element); } } while (ch == 0x20 || ch == 0x0A || ch == 0x0D || ch == 0x09); if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: ch = loadNextChar(); break; case 1: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, true); return recognizeMarkup(ch); } break; case 2: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, true); return recognizeReference(ch); } break; case 3: ch = loadNextChar(); if (ch == ']' && fCurrentOffset + 1 < fEndOffset && fData.charAt(fCurrentOffset + 1) == '>') { callCharDataHandler(offset, fCurrentOffset - 1, true); loadNextChar(); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; } break; case 4: callCharDataHandler(offset, fCurrentOffset, true); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (ch == 0xFFFE || ch == 0xFFFF) { callCharDataHandler(offset, fCurrentOffset, true); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = loadNextChar(); } } } else { if (ch == 0xFFFE || ch == 0xFFFF) { callCharDataHandler(offset, fCurrentOffset, false); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = loadNextChar(); } while (true) { if (ch == -1) { callCharDataHandler(offset, fEndOffset, false); return changeReaders().scanContent(element); } if (ch >= 0x80) break; if (XMLCharacterProperties.fgAsciiCharData[ch] != 0) break; ch = loadNextChar(); } while (true) { // REVISIT - EOF check ? if (ch < 0x80) { switch (XMLCharacterProperties.fgAsciiCharData[ch]) { case 0: ch = loadNextChar(); break; case 1: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, false); return recognizeMarkup(ch); } break; case 2: ch = loadNextChar(); if (!fInCDSect) { callCharDataHandler(offset, fCurrentOffset - 1, false); return recognizeReference(ch); } break; case 3: ch = loadNextChar(); if (ch == ']' && fCurrentOffset + 1 < fEndOffset && fData.charAt(fCurrentOffset + 1) == '>') { callCharDataHandler(offset, fCurrentOffset - 1, false); loadNextChar(); loadNextChar(); return XMLEntityHandler.CONTENT_RESULT_END_OF_CDSECT; } break; case 4: callCharDataHandler(offset, fCurrentOffset, false); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } } else { if (ch == 0xFFFE || ch == 0xFFFF) { callCharDataHandler(offset, fCurrentOffset, false); return XMLEntityHandler.CONTENT_RESULT_INVALID_CHAR; } ch = loadNextChar(); } if (ch == -1) { callCharDataHandler(offset, fCurrentOffset, false); return changeReaders().scanContent(element); } } } private void callCharDataHandler(int offset, int endOffset, boolean isWhitespace) throws Exception { int length = endOffset - offset; if (!fSendCharDataAsCharArray) { int stringIndex = addString(offset, length); if (isWhitespace) fCharDataHandler.processWhitespace(stringIndex); else fCharDataHandler.processCharacters(stringIndex); return; } if (isWhitespace) fCharDataHandler.processWhitespace(fData.toCharArray(), offset, length); else fCharDataHandler.processCharacters(fData.toCharArray(), offset, length); } private static final char[] cdata_string = { 'C','D','A','T','A','[' }; private StringPool fStringPool = null; private String fData = null; private int fEndOffset; private boolean hadTrailingSpace = false; private boolean oweTrailingSpace = false; private int fMostRecentChar; private StringReader fNextFreeReader = null; private static StringReader fgFreeReaders = null; private boolean fCalledCharPropInit = false; }
package org.cocolab.inpro.incremental; import java.util.Collection; import java.util.List; import org.cocolab.inpro.incremental.unit.EditMessage; import org.cocolab.inpro.incremental.unit.IU; import org.cocolab.inpro.incremental.unit.IUList; import org.cocolab.inpro.incremental.util.TedAdapter; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Boolean; import edu.cmu.sphinx.util.props.S4ComponentList; import edu.cmu.sphinx.util.props.S4Integer; import edu.cmu.sphinx.util.props.S4String; /** * Abstract class of an incremental module in InproTk. * Implementing modules should implement leftBufferUpdate() and, * from within this method, use one of the rightBuffer.setBuffer() methods * to set their output after this processing increment. * * @author timo */ public abstract class IUModule extends PushBuffer { @S4ComponentList(type = PushBuffer.class) public final static String PROP_HYP_CHANGE_LISTENERS = "hypChangeListeners"; List<PushBuffer> listeners; @S4Integer(defaultValue = 2000) public final static String PROP_TEDVIEW_LOG_PORT = "tedLogPort"; @S4String(defaultValue = "localhost") public final static String PROP_TEDVIEW_LOG_ADDRESS = "tedLogAddress"; @S4Boolean(defaultValue = true) public final static String PROP_LOG_TO_TEDVIEW = "logToTedView"; private boolean logToTedView; protected TedAdapter tedLogAdapter; /** the right buffer of this module */ protected final RightBuffer rightBuffer = new RightBuffer(); @Override public void newProperties(PropertySheet ps) throws PropertyException { listeners = ps.getComponentList(PROP_HYP_CHANGE_LISTENERS, PushBuffer.class); int tedPort = ps.getInt(PROP_TEDVIEW_LOG_PORT); String tedAddress = ps.getString(PROP_TEDVIEW_LOG_ADDRESS); this.logToTedView = ps.getBoolean(PROP_LOG_TO_TEDVIEW); tedLogAdapter = new TedAdapter(tedAddress, tedPort); } /** * the method that IU modules must implement * @param ius list of IUs that make up the current hypothesis * @param edits a list of edits since the last call */ protected abstract void leftBufferUpdate(Collection<? extends IU> ius, List<? extends EditMessage<? extends IU>> edits); @Override public void hypChange(Collection<? extends IU> ius, List<? extends EditMessage<? extends IU>> edits) { leftBufferUpdate(ius, edits); rightBuffer.notify(listeners); } /* * * utility methods * * */ public long getTime() { return System.currentTimeMillis() - IU.startupTime; } public void logToTedView(String message) { if (this.logToTedView) { String tedTrack = this.getClass().getSimpleName(); StringBuilder sb = new StringBuilder("<event time='"); sb.append(getTime()); sb.append("' originator='"); sb.append(tedTrack); sb.append("'>"); sb.append(message.replace("<", "&lt;").replace(">", "&gt;")); sb.append("</event>"); tedLogAdapter.write(sb.toString()); } } /** * Encapsulates the module's output in two representations. * * Modules should call either of the setBuffer methods in their * implementation of leftBufferUpdate(). * * @author timo */ protected class RightBuffer { /** true if the content has changed since the last call to notify */ boolean hasUpdates = false; IUList<IU> ius = new IUList<IU>(); List<EditMessage<IU>> edits; // just a list of IUs, automatically infers the edits since the last call public void setBuffer(Collection<? extends IU> outputIUs) { IUList<IU> newList = new IUList<IU>(); newList.addAll(outputIUs); edits = ius.diff(newList); ius = newList; hasUpdates = !edits.isEmpty(); } // just a list of edits, automatically updates IUs from last call @SuppressWarnings("unchecked") public void setBuffer(List<? extends EditMessage<? extends IU>> edits) { ius.apply((EditMessage<IU>) edits); hasUpdates = !edits.isEmpty(); } // both ius and edits @SuppressWarnings("unchecked") public void setBuffer(Collection<? extends IU> outputIUs, List<? extends EditMessage<? extends IU>> outputEdits) { ius = new IUList<IU>(); ius.addAll(outputIUs); edits = (List<EditMessage<IU>>) outputEdits; hasUpdates = !edits.isEmpty(); } public void notify(PushBuffer listener) { if (hasUpdates) { listener.hypChange(ius, edits); } } public void notify(List<PushBuffer> listeners) { for (PushBuffer listener : listeners) { notify(listener); } hasUpdates = false; } } }
package org.ensembl.healthcheck; import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.util.LogFormatter; import org.ensembl.healthcheck.util.MyStreamHandler; import org.ensembl.healthcheck.util.Utils; /** * Pull healthcheck results from a database and write to an HTML file. */ public class DatabaseToHTML { private boolean debug = false; private String PROPERTIES_FILE = "database.properties"; private String outputDir = "."; private long sessionID = -1; protected static Logger logger = Logger.getLogger("HealthCheckLogger"); /** * Command-line entry point. * * @param args * Command line args. */ public static void main(String[] args) { new DatabaseToHTML().run(args); } /** * Main run method. * * @param args * Command-line arguments. */ private void run(String[] args) { parseCommandLine(args); setupLogging(); Utils.readPropertiesFileIntoSystem(PROPERTIES_FILE); parseProperties(); Connection con = connectToOutputDatabase(); sessionID = getSessionID(sessionID, con); printOutput(con); } // run private void parseCommandLine(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-h")) { printUsage(); System.exit(0); } else if (args[i].equals("-output")) { i++; outputDir = args[i]; logger.finest("Will write output to " + outputDir); } else if (args[i].equals("-session")) { i++; sessionID = Long.parseLong(args[i]); logger.finest("Will use session ID " + sessionID); } else if (args[i].equals("-debug")) { debug = true; } } } // parseCommandLine private void printUsage() { System.out.println("\nUsage: DatabaseToHTML {options} \n"); System.out.println("Options:"); System.out.println(" -output Specify output directory. Default is current directory."); System.out.println(" -h This message."); System.out.println(" -debug Print debugging info"); System.out.println(); System.out.println("All other configuration information is read from the file database.properties. "); System.out.println("See the comments in that file for information on which options to set."); } private void setupLogging() { // stop parent logger getting the message logger.setUseParentHandlers(false); Handler myHandler = new MyStreamHandler(System.out, new LogFormatter()); logger.addHandler(myHandler); logger.setLevel(Level.WARNING); if (debug) { logger.setLevel(Level.FINEST); } } // setupLogging private void parseProperties() { } private Connection connectToOutputDatabase() { Connection con = DBUtils.openConnection(System.getProperty("output.driver"), System.getProperty("output.databaseURL") + System.getProperty("output.database"), System.getProperty("output.user"), System.getProperty("output.password")); logger.fine("Connecting to " + System.getProperty("output.databaseURL") + System.getProperty("output.database") + " as " + System.getProperty("output.user") + " password " + System.getProperty("output.password")); return con; } /** * Get the most recent session ID from the database, or use the one defined on * the command line. */ private long getSessionID(long s, Connection con) { long sess = -1; String sql = "SELECT MAX(session_id) FROM session"; if (s > 0) { sess = s; } else { try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { sess = rs.getLong(1); logger.finest("Maximum session ID from database: " + sess); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } if (sess == 1) { logger.severe("Can't get session ID from command-line or database."); } return sess; } /** * Print formatted output. */ private void printOutput(Connection con) { try { PrintWriter pwIntro = new PrintWriter(new FileOutputStream(outputDir + File.separator + "healthcheck_summary.html")); printIntroPage(pwIntro, con); // now loop over each species and print the detailed output String sql = "SELECT DISTINCT(species) FROM report WHERE session_id=" + sessionID + " ORDER BY species "; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String species = rs.getString("species"); PrintWriter pw = new PrintWriter(new FileOutputStream(outputDir + File.separator + species + ".html")); printHeader(pw, species, con); printNavigation(pw, species, con); // printExecutiveSummary(pw); printSummaryByDatabase(pw, species, con); printSummaryByTest(pw, species, con); printReportsByDatabase(pw, species, con); printFooter(pw); pw.close(); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } pwIntro.close(); } catch (Exception e) { System.err.println("Error writing output"); e.printStackTrace(); } } private void printIntroPage(PrintWriter pw, Connection con) { // header print(pw, "<html>"); print(pw, "<head>"); print(pw, "<style type='text/css' media='all'>"); print(pw, "@import url(http: print(pw, "@import url(http: print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }"); print(pw, "</style>"); print(pw, "<title>Healthcheck Results</title>"); print(pw, "</head>"); print(pw, "<body>"); print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'>&nbsp;</div>"); print(pw, "<div id='release'>Healthcheck results</div>"); print(pw, "<hr>"); print(pw, ""); print(pw, "<h2>Results by species</h2>"); print(pw, "<ul>"); // now loop over each species String sql = "SELECT DISTINCT(species) FROM report WHERE session_id = " + sessionID + " ORDER BY species"; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String species = rs.getString("species"); print(pw, "<li><p><a href='" + species + ".html'>" + Utils.ucFirst(species) + "</a></p></li>"); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } // footer print(pw, "</ul>"); print(pw, ""); print(pw, "<hr>"); print(pw, ""); print(pw, "<h3>Previous releases</h3>"); print(pw, ""); print(pw, "<ul>"); print(pw, "<li><a href='previous/39/web_healthcheck_summary.html'>39</a> (June 2006)</li>"); print(pw, "<li><a href='previous/38/web_healthcheck_summary.html'>38</a> (April 2006)</li>"); print(pw, "</ul>"); print(pw, "<hr>"); sql = "SELECT start_time, end_time, host, groups, database_regexp FROM session WHERE session_id = " + sessionID; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { print(pw, "<p>Test run was started at " + rs.getString("start_time") + " and finished at " + rs.getString("end_time") + "<br>"); print(pw, "<h4>Configuration used:</h4>"); print(pw, "<pre>"); print(pw, "Tests/groups run: " + rs.getString("groups") + "<br>"); print(pw, "Database host: " + rs.getString("host") + "<br>"); print(pw, "Database names: " + rs.getString("database_regexp") + "<br>"); print(pw, "</pre>"); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } print(pw, "</body>"); print(pw, "</html>"); print(pw, "<hr>"); } private void printHeader(PrintWriter pw, String species, Connection con) { print(pw, "<html>"); print(pw, "<head>"); print(pw, "<style type=\"text/css\" media=\"all\">"); print(pw, "@import url(http: print(pw, "@import url(http: print(pw, "#page ul li { list-style-type:none; list-style-image: none; margin-left: -2em }"); print(pw, "td { font-size: 9pt}"); print(pw, "</style>"); print(pw, "<title>Healthcheck results for " + Utils.ucFirst(species) + "</title>"); print(pw, "</head>"); print(pw, "<body>"); print(pw, "<div id='page'><div id='i1'><div id='i2'><div class='sptop'>&nbsp;</div>"); print(pw, "<div id='release'>Healthcheck results for " + Utils.ucFirst(species) + "</div>"); print(pw, "<hr>"); } private void printFooter(PrintWriter pw) { print(pw, "</div>"); print(pw, "</body>"); print(pw, "</html>"); } private void printNavigation(PrintWriter pw, String species, Connection con) { print(pw, "<div id='related'><div id='related-box'>"); // results by database print(pw, "<h2>Results by database</h2>"); print(pw, "<ul>"); String sql = "SELECT DISTINCT(database_name) FROM report WHERE species='" + species + "' AND session_id=" + sessionID; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String database = rs.getString(1); String link = "<a href=\"#" + database + "\">"; print(pw, "<li>" + link + Utils.truncateDatabaseName(database) + "</a></li>"); } print(pw, "</ul>"); // results by test print(pw, "<h2>Failures by test</h2>"); print(pw, "<ul>"); sql = "SELECT DISTINCT(testcase) FROM report WHERE species='" + species + "' AND result IN ('PROBLEM','WARNING','INFO') AND session_id=" + sessionID; rs = stmt.executeQuery(sql); while (rs.next()) { String test = rs.getString(1); String name = test.substring(test.lastIndexOf('.') + 1); String link = "<a href=\"#" + name + "\">"; print(pw, "<li>" + link + Utils.truncateTestName(name) + "</a></li>"); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } print(pw, "</ul>"); print(pw, "</div></div>"); } private void printSummaryByDatabase(PrintWriter pw, String species, Connection con) { print(pw, "<h2>Summary of results by database</h2>"); print(pw, "<p><table class='ss'>"); print(pw, "<tr><th>Database</th><th>Passed</th><th>Failed</th></tr>"); String sql = "SELECT DISTINCT(database_name) FROM report WHERE species='" + species + "' AND session_id=" + sessionID; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String database = rs.getString(1); String link = "<a href=\"#" + database + "\">"; int[] passesAndFails = countPassesAndFailsDatabase(database, con); String s = (passesAndFails[1] == 0) ? passFont() : failFont(); String[] t = { link + s + database + "</font></a>", passFont() + passesAndFails[0] + "</font>", failFont() + passesAndFails[1] + "</font>" }; printTableLine(pw, t); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } print(pw, "</table></p>"); print(pw, "<hr>"); } private void print(PrintWriter pw, String s) { pw.write(s + "\n"); pw.flush(); } private void printTableLine(PrintWriter pw, String[] s) { pw.write("<tr>"); for (int i = 0; i < s.length; i++) { pw.write("<td>" + s[i] + "</td>"); } pw.write("</tr>\n"); } private String passFont() { return "<font color='green' size=-1>"; } private String failFont() { return "<font color='red' size=-1>"; } private int[] countPassesAndFailsDatabase(String database, Connection con) { int[] result = new int[2]; int total = -1, failed = -1; // get count of total tests run String sql = "SELECT COUNT(DISTINCT(testcase)) FROM report WHERE database_name='" + database + "' AND session_id=" + sessionID; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { total = rs.getInt(1); } sql = "SELECT COUNT(DISTINCT(testcase)) FROM report WHERE database_name='" + database + "' AND result = 'PROBLEM' AND session_id=" + sessionID; rs = stmt.executeQuery(sql); if (rs.next()) { failed = rs.getInt(1); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } result[1] = failed; result[0] = total - failed; return result; } private void printSummaryByTest(PrintWriter pw, String species, Connection con) { print(pw, "<h2>Summary of failures by test</h2>"); print(pw, "<p><table class='ss'>"); print(pw, "<tr><th>Test</th><th>Result</th></tr>"); // group failed tests before passed ones via ORDER BY String sql = "SELECT DISTINCT(testcase), result FROM report WHERE species='" + species + "' AND session_id=" + sessionID + " AND result IN ('PROBLEM','WARNING','INFO') ORDER BY result"; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String testcase = rs.getString(1); String result = rs.getString(2); String link = "<a href=\"#" + testcase + "\">"; String s = (result.equals("CORRECT")) ? passFont() : failFont(); String r = (result.equals("CORRECT")) ? "Passed" : "Failed"; String[] t = { link + s + testcase + "</a></font>", s + r + "</font>" }; printTableLine(pw, t); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } print(pw, "</table></p>"); print(pw, "<hr>"); } private void printReportsByDatabase(PrintWriter pw, String species, Connection con) { print(pw, "<h2>Detailed failure reports by database</h2>"); String sql = "SELECT r.report_id, r.database_name, r.testcase, r.result, r.text, a.person, a.action, a.reason, a.comment FROM report r LEFT JOIN annotation a ON r.report_id=a.report_id WHERE r.species='" + species + "' AND r.session_id=" + sessionID + " AND r.result IN ('PROBLEM','WARNING','INFO') ORDER BY r.database_name, r.testcase"; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); String lastDatabase = ""; String lastTest = ""; while (rs.next()) { String database = rs.getString("database_name"); String testcase = rs.getString("testcase"); String result = rs.getString("result"); String text = rs.getString("text"); String person = stringOrBlank(rs.getString("person")); String action = stringOrBlank(rs.getString("action")); String reason = stringOrBlank(rs.getString("reason")); String comment = stringOrBlank(rs.getString("comment")); if (!database.equals(lastDatabase)) { if (lastDatabase != "") { print(pw, "</table>"); } String link = "<a name=\"" + database + "\">"; print(pw, "<h3 class='boxed'>" + link + database + "</a></h3>"); print(pw, "<table>"); lastDatabase = database; } if (!lastTest.equals("") && !testcase.equals(lastTest)) { print(pw, "<tr><td colspan='7'>&nbsp;</td></tr>"); } lastTest = testcase; String linkTarget = "<a name=\"" + database + ":" + testcase + "\"></a> "; String f1 = getFontForResult(result, action); String f2 = "</font>"; String[] s = {linkTarget, f1 + "<strong>" + testcase + "</strong>" + f2, f1 + text + f2, f1 + person + f2, f1 + action + f2, f1 + reason + f2, f1 + comment + f2}; printTableLine(pw, s); } } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } private String getFontForResult(String result, String action) { String s1 = "<font color='black'>"; if (result.equals("PROBLEM")) { s1 = "<font color='red'>"; } if (result.equals("WARNING")) { s1 = "<font color='black'>"; } if (result.equals("INFO")) { s1 = "<font color='black'>"; } if (result.equals("CORRECT")) { s1 = "<font color='green'>"; } if (result.equals("")) { s1 = "<font color='red'>"; } if (result.equals("PROBLEM")) { s1 = "<font color='red'>"; } // override if there has been an annotation if (action != null) { if(action.equals("ignore") || action.equals("normal")) { s1 = "<font color='grey'>"; } } return s1; } private String stringOrBlank(String s) { return (s != null) ? s : ""; } } // DatabaseToHTML
package net.domesdaybook.reader; import java.io.IOException; import java.io.InputStream; /** * * @author matt */ public class InputStreamReader extends AbstractReader { private final InputStream stream; private long streamPos = 0; private long length = UNKNOWN_LENGTH; public InputStreamReader(final InputStream stream) { this(stream, DEFAULT_WINDOW_SIZE); } public InputStreamReader(final InputStream stream, final WindowCache cache) { this(stream, DEFAULT_WINDOW_SIZE, cache); } public InputStreamReader(final InputStream stream, final int windowSize) { this(stream, windowSize, new WindowAllCache()); } public InputStreamReader(final InputStream stream, final int windowSize, final WindowCache cache) { super(windowSize, cache); this.stream = stream; } @Override public final Window getWindow(final long position) throws IOException, CacheFailureException { final Window window = super.getWindow(position); if (window == null && position < streamPos && position >= 0) { // No window was returned, but the position requested has already // been read. This means the cache algorithm selected to use with // this reader cannot return an earlier position, and being a stream, // we can't rewind to read it again. There is nothing which can be // done at this point other than to throw an exception. // This runtime exception flags a programming error, in selecting an // innapropriate cache algorithm to use for the access needed. // A reader should always be able to return a window for a valid position, // setting aside genuine IO Exceptions. final String message = "Cache failed to provide a window at position: %d when we have already read past this position, currently at: %d"; throw new CacheFailureException(String.format(message, position, streamPos)); } return window; } @Override Window createWindow(final long readPos) throws IOException { Window lastWindow = null; while (readPos > streamPos && length == UNKNOWN_LENGTH) { final byte[] bytes = new byte[windowSize]; final int totalRead = ReadUtils.readBytes(stream, bytes); if (totalRead > 0) { lastWindow = new Window(bytes, streamPos, totalRead); streamPos += totalRead; cache.addWindow(lastWindow); } if (totalRead < windowSize) { // If we read less than the available array: length = streamPos; // then the length is whatever the streampos is now. } } return lastWindow; } @Override public long length() throws IOException { while (length == UNKNOWN_LENGTH) { final byte[] bytes = new byte[windowSize]; final int totalRead = ReadUtils.readBytes(stream, bytes); if (totalRead > 0) { final Window lastWindow = new Window(bytes, streamPos, totalRead); streamPos += totalRead; cache.addWindow(lastWindow); } if (totalRead < windowSize) { // If we read less than the available array: length = streamPos; } } return length; } @Override public void clearCache() { // The cache is the only representation of the stream we can replay, // so we don't clear it, as it's not really a cache anymore. } @Override public void close() { try { stream.close(); } catch (IOException canDoNothing) { } finally { super.close(); } } }
package org.intellij.ibatis; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.facet.FacetManager; import com.intellij.navigation.ChooseByNameContributor; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.NavigationItem; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlTag; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.ElementPresentationManager; import org.intellij.ibatis.facet.IbatisFacet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; /** * Base class for "Go To Symbol" contributors. * * @author Jacky */ abstract class GoToSymbolProvider implements ChooseByNameContributor { protected abstract void getNames(@NotNull Module module, Set<String> result); protected abstract void getItems(@NotNull Module module, String name, List<NavigationItem> result); protected static void addNames(@NotNull final Collection<? extends DomElement> elements, final Set<String> existingNames) { for (DomElement name : elements) { XmlTag tag = name.getXmlTag(); if (tag != null) existingNames.add(tag.getAttributeValue("id")); } } public String[] getNames(final Project project, boolean includeNonProjectItems) { Set<String> result = new HashSet<String>(); Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { if (IbatisFacet.getInstance(module) != null) { getNames(module, result); } } return result.toArray(new String[result.size()]); } public NavigationItem[] getItemsByName(String name, String s1, Project project, boolean includeNonProjectItems) { List<NavigationItem> result = new ArrayList<NavigationItem>(); Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { if (IbatisFacet.getInstance(module) != null) { getItems(module, name, result); } } return result.toArray(new NavigationItem[result.size()]); } @Nullable protected static NavigationItem createNavigationItem(final DomElement domElement) { XmlTag xmlTag = domElement.getXmlTag(); if (xmlTag == null) return null; final String value = xmlTag.getAttributeValue("id"); if (value == null) return null; final Icon icon = ElementPresentationManager.getIcon(domElement); return createNavigationItem(xmlTag.getAttribute("id"), value, icon); } @NotNull protected static NavigationItem createNavigationItem(@NotNull final PsiElement element, @NotNull @NonNls final String text, @Nullable final Icon icon) { return new BaseNavigationItem(element, text, icon); } /** * Wraps one entry to display in "Go To Symbol" dialog. */ protected static class BaseNavigationItem extends ASTWrapperPsiElement { private final PsiElement myPsiElement; private final String myText; private final Icon myIcon; /** * Creates a new display item. * * @param psiElement The PsiElement to navigate to. * @param text Text to show for this element. * @param icon Icon to show for this element. */ protected BaseNavigationItem(@NotNull PsiElement psiElement, @NotNull @NonNls String text, @Nullable Icon icon) { super(psiElement.getNode()); myPsiElement = psiElement; myText = text; myIcon = icon; } public Icon getIcon(int flags) { return myIcon; } public ItemPresentation getPresentation() { return new ItemPresentation() { public String getPresentableText() { return myText; } @Nullable public String getLocationString() { return '(' + myPsiElement.getContainingFile().getName() + ')'; } @Nullable public Icon getIcon(boolean open) { return myIcon; } @Nullable public TextAttributesKey getTextAttributesKey() { return null; } }; } } public boolean isIbatisModule(Module module) { return FacetManager.getInstance(module).getFacetsByType(IbatisFacet.FACET_TYPE_ID).size() > 0; } }
package net.wurstclient.features.mods; import net.minecraft.network.play.client.CPacketPlayer; import net.wurstclient.compatibility.WConnection; import net.wurstclient.compatibility.WMinecraft; import net.wurstclient.events.listeners.UpdateListener; @Mod.Info( description = "While this is active, other people will think you are\n" + "headless. Looks hilarious!", name = "Headless", tags = "head less", help = "Mods/Headless") @Mod.Bypasses(ghostMode = false, latestNCP = false, olderNCP = false) public final class HeadlessMod extends Mod implements UpdateListener { @Override public void onEnable() { wurst.events.add(UpdateListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); } @Override public void onUpdate() { WConnection.sendPacket( new CPacketPlayer.Rotation(WMinecraft.getPlayer().rotationYaw, 180F, WMinecraft.getPlayer().onGround)); } }
package org.jactiveresource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; public class ResourceConnection { private URL site; private String username; private String password; private ClientConnectionManager connectionManager; private DefaultHttpClient httpclient; private static final String CONTENT_TYPE = "Content-type"; // TODO remove trailing slashes public ResourceConnection(URL site) { this.site = site; init(); } public ResourceConnection(String site) throws MalformedURLException { this.site = new URL(site); init(); } public ResourceConnection(URL site, ResourceFormat format) { this.site = site; init(); } public ResourceConnection(String site, ResourceFormat format) throws MalformedURLException { this.site = new URL(site); init(); } /** * * @return the URL object for the site this connection is attached to */ public URL getSite() { return this.site; } /** * @return the username used for authentication */ public String getUsername() { return username; } /** * @param username * the username to use for authentication */ public void setUsername(String username) { this.username = username; } /** * @return the password used for authentication */ public String getPassword() { return password; } /** * @param password * the password to use for authentication */ public void setPassword(String password) { this.password = password; } /** * append url to the site this * {@link ResourceConnection#ResourceConnection(String) ResourceConnection} * was created with, issue a HTTP GET request, and return the body of the * HTTP response * * @param url * the url to retrieve * @return a string containing the body of the response * @throws HttpException * @throws IOException * @throws InterruptedException * @throws URISyntaxException */ public String get(String url) throws HttpException, IOException, InterruptedException, URISyntaxException { HttpClient client = createHttpClient(this.getSite()); HttpGet request = new HttpGet(this.getSite().toString() + url); HttpEntity entity = null; try { HttpResponse response = client.execute(request); checkHttpStatus(response); entity = response.getEntity(); StringBuffer sb = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader( entity.getContent())); int c; while ((c = reader.read()) != -1) sb.append((char) c); return sb.toString(); } finally { // if there is no entity, the connection is already released if (entity != null) entity.consumeContent(); // release connection gracefully } } /** * append url to the site this * {@link ResourceConnection#ResourceConnection(String) ResourceConnection} * was created with, issue a HTTP GET request, and return a buffered input * stream of the body of the HTTP response * * @param url * @return a buffered stream of the response * @throws HttpException * @throws IOException * @throws InterruptedException * @throws URISyntaxException */ public BufferedReader getStream(String url) throws HttpException, IOException, InterruptedException, URISyntaxException { HttpClient client = createHttpClient(this.getSite()); HttpGet request = new HttpGet(this.getSite().toString() + url); HttpEntity entity = null; HttpResponse response = client.execute(request); checkHttpStatus(response); entity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity .getContent())); return reader; } /** * send an http put request to the server. This is a bit unique because * there is no response returned from the server. * * @param url * @param body * @param contentType * @throws URISyntaxException * @throws HttpException * @throws IOException * @throws InterruptedException */ public HttpResponse put(String url, String body, String contentType) throws URISyntaxException, HttpException, IOException, InterruptedException { HttpClient client = createHttpClient(this.getSite()); HttpPut request = new HttpPut(this.getSite().toString() + url); request.setHeader(CONTENT_TYPE, contentType); StringEntity entity = new StringEntity(body); request.setEntity(entity); HttpResponse response = client.execute(request); return response; } /** * send a post request, used to create a new resource * * @param url * @param body * @throws ClientProtocolException * @throws IOException * @throws ClientError * @throws ServerError */ public HttpResponse post(String url, String body, String contentType) throws ClientProtocolException, IOException, ClientError, ServerError { HttpClient client = createHttpClient(this.getSite()); HttpPost request = new HttpPost(this.getSite().toString() + url); request.setHeader(CONTENT_TYPE, contentType); StringEntity entity = new StringEntity(body); request.setEntity(entity); HttpResponse response = client.execute(request); return response; } /** * delete a resource on the server * * @param url * @throws ClientError * @throws ServerError * @throws ClientProtocolException * @throws IOException */ public void delete(String url) throws ClientError, ServerError, ClientProtocolException, IOException { HttpClient client = createHttpClient(this.getSite()); HttpDelete request = new HttpDelete(this.getSite().toString() + url); HttpResponse response = client.execute(request); checkHttpStatus(response); } /** * check the status in the HTTP response and throw an appropriate exception * * @param response * @throws ClientError * @throws ServerError */ public final void checkHttpStatus(HttpResponse response) throws ClientError, ServerError { int status = response.getStatusLine().getStatusCode(); if (status == 400) throw new BadRequest(); else if (status == 401) throw new UnauthorizedAccess(); else if (status == 403) throw new ForbiddenAccess(); else if (status == 404) throw new ResourceNotFound(); else if (status == 405) throw new MethodNotAllowed(); else if (status == 409) throw new ResourceConflict(); else if (status == 422) throw new ResourceInvalid(); else if (status >= 401 && status <= 499) throw new ClientError(); else if (status >= 500 && status <= 599) throw new ServerError(); } /* * create or retrieve a cached HttpClient object */ private HttpClient createHttpClient(URL site) { this.connectionManager = new ThreadSafeClientConnManager( getHttpParams(), supportedSchemes); this.httpclient = new DefaultHttpClient(this.connectionManager, getHttpParams()); // check for authentication credentials String u = null, p = null; if (this.username != null) { // we have explicit username and password u = this.username; p = this.password; } else { // check the URI String userinfo = site.getUserInfo(); if (userinfo != null) { int pos = userinfo.indexOf(":"); if (pos > 0) { u = userinfo.substring(0, pos); p = userinfo.substring(pos + 1); } } } // use the credentials if we have them if (u != null) { this.httpclient.getCredentialsProvider().setCredentials( new AuthScope(site.getHost(), site.getPort()), new UsernamePasswordCredentials(u, p)); } return this.httpclient; } private HttpParams httpParams; public HttpParams getHttpParams() { return httpParams; } public void setHttpParams(HttpParams params) { this.httpParams = params; } /** * The scheme registry. Instantiated in {@link #init setup}. */ private static SchemeRegistry supportedSchemes; /** * initialize http client settings */ private void init() { supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); sf = SSLSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("https", sf, 443)); // set parameters httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); ConnManagerParams.setMaxTotalConnections(httpParams, 400); } public String toString() { return site.toString(); } }
package org.objectweb.asm.util; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.objectweb.asm.Attribute; /** * An abstract visitor. * * @author Eric Bruneton */ public abstract class AbstractVisitor { /** * The names of the Java Virtual Machine opcodes. */ public final static String[] OPCODES; /** * Types for <code>operand</code> parameter of the * {@link org.objectweb.asm.MethodVisitor#visitIntInsn} method when * <code>opcode</code> is <code>NEWARRAY</code>. */ public final static String[] TYPES; static { String s = "NOP,ACONST_NULL,ICONST_M1,ICONST_0,ICONST_1,ICONST_2," + "ICONST_3,ICONST_4,ICONST_5,LCONST_0,LCONST_1,FCONST_0," + "FCONST_1,FCONST_2,DCONST_0,DCONST_1,BIPUSH,SIPUSH,LDC,,," + "ILOAD,LLOAD,FLOAD,DLOAD,ALOAD,,,,,,,,,,,,,,,,,,,,,IALOAD," + "LALOAD,FALOAD,DALOAD,AALOAD,BALOAD,CALOAD,SALOAD,ISTORE," + "LSTORE,FSTORE,DSTORE,ASTORE,,,,,,,,,,,,,,,,,,,,,IASTORE," + "LASTORE,FASTORE,DASTORE,AASTORE,BASTORE,CASTORE,SASTORE,POP," + "POP2,DUP,DUP_X1,DUP_X2,DUP2,DUP2_X1,DUP2_X2,SWAP,IADD,LADD," + "FADD,DADD,ISUB,LSUB,FSUB,DSUB,IMUL,LMUL,FMUL,DMUL,IDIV,LDIV," + "FDIV,DDIV,IREM,LREM,FREM,DREM,INEG,LNEG,FNEG,DNEG,ISHL,LSHL," + "ISHR,LSHR,IUSHR,LUSHR,IAND,LAND,IOR,LOR,IXOR,LXOR,IINC,I2L," + "I2F,I2D,L2I,L2F,L2D,F2I,F2L,F2D,D2I,D2L,D2F,I2B,I2C,I2S,LCMP," + "FCMPL,FCMPG,DCMPL,DCMPG,IFEQ,IFNE,IFLT,IFGE,IFGT,IFLE," + "IF_ICMPEQ,IF_ICMPNE,IF_ICMPLT,IF_ICMPGE,IF_ICMPGT,IF_ICMPLE," + "IF_ACMPEQ,IF_ACMPNE,GOTO,JSR,RET,TABLESWITCH,LOOKUPSWITCH," + "IRETURN,LRETURN,FRETURN,DRETURN,ARETURN,RETURN,GETSTATIC," + "PUTSTATIC,GETFIELD,PUTFIELD,INVOKEVIRTUAL,INVOKESPECIAL," + "INVOKESTATIC,INVOKEINTERFACE,,NEW,NEWARRAY,ANEWARRAY," + "ARRAYLENGTH,ATHROW,CHECKCAST,INSTANCEOF,MONITORENTER," + "MONITOREXIT,,MULTIANEWARRAY,IFNULL,IFNONNULL,"; OPCODES = new String[200]; int i = 0; int j = 0; int l; while ((l = s.indexOf(',', j)) > 0) { OPCODES[i++] = j + 1 == l ? null : s.substring(j, l); j = l + 1; } s = "T_BOOLEAN,T_CHAR,T_FLOAT,T_DOUBLE,T_BYTE,T_SHORT,T_INT,T_LONG,"; TYPES = new String[12]; j = 0; i = 4; while ((l = s.indexOf(',', j)) > 0) { TYPES[i++] = s.substring(j, l); j = l + 1; } } /** * The text to be printed. Since the code of methods is not necessarily * visited in sequential order, one method after the other, but can be * interlaced (some instructions from method one, then some instructions * from method two, then some instructions from method one again...), it is * not possible to print the visited instructions directly to a sequential * stream. A class is therefore printed in a two steps process: a string * tree is constructed during the visit, and printed to a sequential stream * at the end of the visit. This string tree is stored in this field, as a * string list that can contain other string lists, which can themselves * contain other string lists, and so on. */ public final List text; /** * A buffer that can be used to create strings. */ protected final StringBuffer buf; /** * Constructs a new {@link AbstractVisitor}. */ protected AbstractVisitor() { this.text = new ArrayList(); this.buf = new StringBuffer(); } /** * Returns the text constructed by this visitor. * * @return the text constructed by this visitor. */ public List getText() { return text; } /** * Prints the text constructed by this visitor. * * @param pw the print writer to be used. */ public void print(final PrintWriter pw) { printList(pw, text); } /** * Appends a quoted string to a given buffer. * * @param buf the buffer where the string must be added. * @param s the string to be added. */ public static void appendString(final StringBuffer buf, final String s) { buf.append("\""); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == '\n') { buf.append("\\n"); } else if (c == '\r') { buf.append("\\r"); } else if (c == '\\') { buf.append("\\\\"); } else if (c == '"') { buf.append("\\\""); } else if (c < 0x20 || c > 0x7f) { buf.append("\\u"); if (c < 0x10) { buf.append("000"); } else if (c < 0x100) { buf.append("00"); } else if (c < 0x1000) { buf.append("0"); } buf.append(Integer.toString(c, 16)); } else { buf.append(c); } } buf.append("\""); } /** * Prints the given string tree. * * @param pw the writer to be used to print the tree. * @param l a string tree, i.e., a string list that can contain other string * lists, and so on recursively. */ void printList(final PrintWriter pw, final List l) { for (int i = 0; i < l.size(); ++i) { Object o = l.get(i); if (o instanceof List) { printList(pw, (List) o); } else { pw.print(o.toString()); } } } /** * Returns the default {@link ASMifiable} prototypes. * * @return the default {@link ASMifiable} prototypes. */ public static Attribute[] getDefaultAttributes() { return new Attribute[0]; } }
package odontosoft.controller; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import java.sql.Connection; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TextField; import odontosoft.model.dao.UsuarioDAO; import odontosoft.model.database.ConexaoBanco; import odontosoft.model.domain.Usuario; /** * FXML Controller class * * @author eduardo */ public class TelaLoginController implements Initializable { @FXML TextField txtFieldNomeUsuario,txtFieldSenha; @FXML Button btnEntrar; ConexaoBanco conexao = new ConexaoBanco(); Connection connect = conexao.getConexao(); /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { } @FXML public void clickBtnEntrar(){ String idInformado = txtFieldNomeUsuario.getText(); String senhaInformada = txtFieldSenha.getText(); Usuario user = new UsuarioDAO(connect).buscaPorId(idInformado); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Conexão"); if(senhaInformada.equals(user.getSenha())){ alert.setContentText("Conexão realizada com sucesso!"); alert.showAndWait(); }else{ alert.setContentText("Usuario ou senha incorreto(s)!"); alert.showAndWait(); } } }
package com.eolwral.osmonitor.ui; import java.text.Collator; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Debug.MemoryInfo; import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment; import android.support.v4.util.SimpleArrayMap; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.MenuItemCompat.OnActionExpandListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewStub; import android.view.WindowManager.LayoutParams; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.PopupWindow.OnDismissListener; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; import android.widget.Toast; import com.eolwral.osmonitor.OSMonitorService; import com.eolwral.osmonitor.R; import com.eolwral.osmonitor.core.OsInfo.osInfo; import com.eolwral.osmonitor.core.ProcessInfo.processInfo; import com.eolwral.osmonitor.ipc.IpcMessage.ipcAction; import com.eolwral.osmonitor.ipc.IpcMessage.ipcData; import com.eolwral.osmonitor.ipc.IpcMessage.ipcMessage; import com.eolwral.osmonitor.ipc.IpcService; import com.eolwral.osmonitor.ipc.IpcService.ipcClientListener; import com.eolwral.osmonitor.preference.Preference; import com.eolwral.osmonitor.settings.Settings; import com.eolwral.osmonitor.util.CommonUtil; import com.eolwral.osmonitor.util.ProcessUtil; public class ProcessFragment extends ListFragment implements ipcClientListener { // ipc client private IpcService ipcService = IpcService.getInstance(); private boolean ipcStop = false; // screen private TextView processCount = null; private TextView cpuUsage = null; private TextView memoryTotal = null; private TextView memoryFree = null; // data private ProcessUtil infoHelper = null; private ArrayList<processInfo> data = new ArrayList<processInfo>(); private osInfo info = null; private Settings settings = null; // status private static int itemColor[] = null; private static int oddItem = 0; private static int evenItem = 1; private static int selectedItem = 2; private final SimpleArrayMap<String, Boolean> expandStatus = new SimpleArrayMap<String, Boolean>(); private final SimpleArrayMap<String, Integer> selectedStatus = new SimpleArrayMap<String, Integer>(); // tablet private boolean tabletLayout = false; private int selectedPID = -1; private int selectedPrority = 0; private String selectedProcess = ""; private ViewHolder selectedHolder = null; // preference private enum SortType { SortbyUsage, SortbyMemory, SortbyPid, SortbyName, SortbyCPUTime } private SortType sortSetting = SortType.SortbyUsage; // kill private enum KillMode { None, Select } private KillMode killSetting = KillMode.None; ImageButton killButton = null; // stop or start private boolean stopUpdate = false; private ImageButton stopButton = null; private PopupWindow sortMenu = null; private boolean openSortMenu = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // prepare draw color itemColor = new int[3]; itemColor[oddItem] = getResources().getColor(R.color.dkgrey_osmonitor); itemColor[evenItem] = getResources().getColor(R.color.black_osmonitor); itemColor[selectedItem] = getResources().getColor(R.color.selected_osmonitor); settings = Settings.getInstance(getActivity().getApplicationContext()); infoHelper = ProcessUtil.getInstance(getActivity().getApplicationContext(), true); setListAdapter(new ProcessListAdapter(getActivity().getApplicationContext())); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.ui_process_fragment, container, false); // detect layout if ( v.findViewById(R.id.ui_process_tablet_layout) != null) { tabletLayout = true; prepareSelectedHolder(v); } else { tabletLayout = false; resetSelectedHolder(); } // enable fragment option menu setHasOptionsMenu(true); // get UI item processCount = ((TextView) v.findViewById(R.id.id_process_count)); cpuUsage = ((TextView) v.findViewById(R.id.id_process_cpuusage)); memoryTotal = ((TextView) v.findViewById(R.id.id_process_memorytotal)); memoryFree = ((TextView) v.findViewById(R.id.id_process_memoryfree)); // detect last sort mode if(settings.getSortType().equals("Usage")) { sortSetting = SortType.SortbyUsage; } else if(settings.getSortType().equals("Pid")) { sortSetting = SortType.SortbyPid; } else if(settings.getSortType().equals("Memory")) { sortSetting = SortType.SortbyMemory; } else if(settings.getSortType().equals("Name")) { sortSetting = SortType.SortbyName; } else if(settings.getSortType().equals("CPUTime")) { sortSetting = SortType.SortbyCPUTime; } return v; } private void prepareSelectedHolder(View v) { selectedHolder = new ViewHolder(); selectedHolder.detailIcon = ((ImageView) v.findViewById(R.id.id_process_detail_image)); selectedHolder.detailTitle = ((TextView) v.findViewById(R.id.id_process_detail_title)); selectedHolder.detailName = ((TextView) v.findViewById(R.id.id_process_detail_name)); selectedHolder.detailStatus = ((TextView) v.findViewById(R.id.id_process_detail_status)); selectedHolder.detailStime = ((TextView) v.findViewById(R.id.id_process_detail_stime)); selectedHolder.detailUtime = ((TextView) v.findViewById(R.id.id_process_detail_utime)); selectedHolder.detailCPUtime = ((TextView) v.findViewById(R.id.id_process_detail_cputime)); selectedHolder.detailMemory = ((TextView) v.findViewById(R.id.id_process_detail_memory)); selectedHolder.detailPPID = ((TextView) v.findViewById(R.id.id_process_detail_ppid)); selectedHolder.detailUser = ((TextView) v.findViewById(R.id.id_process_detail_user)); selectedHolder.detailStarttime = ((TextView) v.findViewById(R.id.id_process_detail_starttime)); selectedHolder.detailThread = ((TextView) v.findViewById(R.id.id_process_detail_thread)); selectedHolder.detailNice = ((TextView) v.findViewById(R.id.id_process_detail_nice)); String[] menuText = getResources().getStringArray(R.array.ui_process_menu_item); Button buttonAction = (Button) v.findViewById(R.id.id_process_button_kill); buttonAction.setText(menuText[0]); buttonAction.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (selectedPID != -1 && !selectedProcess.isEmpty()) killProcess(selectedPID, selectedProcess); } }); buttonAction = (Button) v.findViewById(R.id.id_process_button_switch); buttonAction.setText(menuText[1]); buttonAction.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (selectedPID != -1 && !selectedProcess.isEmpty()) switchToProcess(selectedPID, selectedProcess); } }); buttonAction = (Button) v.findViewById(R.id.id_process_button_watchlog); buttonAction.setText(menuText[2]); buttonAction.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (selectedPID != -1 && !selectedProcess.isEmpty()) watchLog(selectedPID, selectedProcess); } }); buttonAction = (Button) v.findViewById(R.id.id_process_button_setprority); buttonAction.setText(menuText[3]); buttonAction.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (selectedPID != -1 && !selectedProcess.isEmpty()) setPrority(selectedPID, selectedProcess, selectedPrority); } }); } private void resetSelectedHolder() { selectedHolder = null; } @Override public void onCreateOptionsMenu (Menu menu, MenuInflater inflater){ inflater.inflate(R.menu.ui_process_menu, menu); MenuItem toolsMenu = menu.findItem(R.id.ui_menu_tools); MenuItemCompat.setOnActionExpandListener(toolsMenu, new ToolActionExpandListener()); View toolsView = MenuItemCompat.getActionView(toolsMenu); ImageButton sortButton = (ImageButton) toolsView.findViewById(R.id.id_action_sort); sortButton.setOnClickListener( new SortMenuClickListener()); killButton = (ImageButton) toolsView.findViewById(R.id.id_action_kill); killButton.setOnClickListener( new KillButtonClickListener()); killSetting = KillMode.None; // refresh button stopButton = (ImageButton) toolsView.findViewById(R.id.id_action_stop); if(stopUpdate) stopButton.setImageResource(R.drawable.ic_action_start); else stopButton.setImageResource(R.drawable.ic_action_stop); stopButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { stopUpdate = !stopUpdate; if(stopUpdate) stopButton.setImageResource(R.drawable.ic_action_start); else stopButton.setImageResource(R.drawable.ic_action_stop); } }); return; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.ui_menu_help: onHelpClick(); break; case R.id.ui_menu_setting: onSettingClick(); break; case R.id.ui_menu_exit: onExitClick(); break; } return super.onOptionsItemSelected(item); } private void onExitClick() { getActivity().stopService(new Intent(getActivity(), OSMonitorService.class)); android.os.Process.killProcess(android.os.Process.myPid()); return ; } private void onSettingClick() { Intent settings = new Intent(getActivity(), Preference.class); settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(settings); return; } private void onHelpClick() { ShowHelp(); return; } private class ToolActionExpandListener implements OnActionExpandListener { @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { killSetting = KillMode.None; selectedStatus.clear(); ((ProcessListAdapter) getListAdapter()).refresh(); return true; } } private class KillButtonClickListener implements OnClickListener { @Override public void onClick(View v) { // enter select mode if (killSetting == KillMode.None) { killSetting = KillMode.Select; killButton.setImageResource(R.drawable.ic_action_kill_done); return; } // leave select mode killButton.setImageResource(R.drawable.ic_action_kill); killSetting = KillMode.None; // selected items is empty if(selectedStatus.size() == 0) return; // show message String rawFormat = getResources().getString(R.string.ui_text_kill); String strFormat = String.format(rawFormat, selectedStatus.size()); Toast.makeText(getActivity().getApplicationContext(), strFormat, Toast.LENGTH_SHORT).show(); // kill all selected items for(int i = 0; i < selectedStatus.size(); i++) killProcess(selectedStatus.valueAt(i), selectedStatus.keyAt(i)); // clean up selected items selectedStatus.clear(); } } private class SortMenuClickListener implements OnClickListener { @Override public void onClick(View v) { openSortMenu = !openSortMenu; if (!openSortMenu) { sortMenu.dismiss(); return; } if (null == sortMenu) { View layout = LayoutInflater.from(getActivity()) .inflate(R.layout.ui_process_menu_sort, null); sortMenu = new PopupWindow(layout); sortMenu.setBackgroundDrawable(new BitmapDrawable()); sortMenu.setFocusable(true); sortMenu.setWidth(LayoutParams.WRAP_CONTENT); sortMenu.setHeight(LayoutParams.WRAP_CONTENT); sortMenu.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { openSortMenu = false; } }); } RadioGroup sortGroup = (RadioGroup) sortMenu.getContentView() .findViewById(R.id.id_process_sort_group); switch (sortSetting) { case SortbyUsage: sortGroup.check(R.id.id_process_sort_usage); break; case SortbyMemory: sortGroup.check(R.id.id_process_sort_memory); break; case SortbyPid: sortGroup.check(R.id.id_process_sort_pid); break; case SortbyName: sortGroup.check(R.id.id_process_sort_name); break; case SortbyCPUTime: sortGroup.check(R.id.id_process_sort_cputime); break; } sortGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.id_process_sort_usage: sortSetting = SortType.SortbyUsage; settings.setSortType("Usage"); break; case R.id.id_process_sort_memory: sortSetting = SortType.SortbyMemory; settings.setSortType("Memory"); break; case R.id.id_process_sort_pid: sortSetting = SortType.SortbyPid; settings.setSortType("Pid"); break; case R.id.id_process_sort_name: sortSetting = SortType.SortbyName; settings.setSortType("Name"); break; case R.id.id_process_sort_cputime: sortSetting = SortType.SortbyCPUTime; settings.setSortType("CPUTime"); break; } // force update after setting has been changed if(stopUpdate == true) stopButton.performClick(); sortMenu.dismiss(); } }); sortMenu.showAsDropDown(v); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); // clear up selected item if(this.isVisible()) { if (!isVisibleToUser) { selectedStatus.clear(); ((ProcessListAdapter) getListAdapter()).refresh(); } } ipcService.removeRequest(this); ipcStop = !isVisibleToUser; if(isVisibleToUser == true) { ipcAction newCommand[] = { ipcAction.OS, ipcAction.PROCESS }; ipcService.addRequest(newCommand, 0, this); } } private void killProcess(int pid, String process) { CommonUtil.killProcess(pid, getActivity()); ((ActivityManager) getActivity(). getSystemService(Context.ACTIVITY_SERVICE)).restartPackage(process); } private void watchLog(int pid, String process) { // pass information ProcessLogViewFragment newLog = new ProcessLogViewFragment(); Bundle args = new Bundle(); args.putInt(ProcessLogViewFragment.TARGETPID, pid); args.putString(ProcessLogViewFragment.TARGETNAME, infoHelper.getPackageName(process)); newLog.setArguments(args); // replace current fragment final FragmentManager fragmanger = getActivity().getSupportFragmentManager(); newLog.show(fragmanger, "logview"); } private void switchToProcess(int pid, String process) { PackageManager QueryPackage = getActivity().getPackageManager(); Intent mainIntent = new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> appList = QueryPackage.queryIntentActivities(mainIntent, 0); String className = null; for(int index = 0; index < appList.size(); index++) if(appList.get(index).activityInfo.applicationInfo.packageName.equals(process)) className = appList.get(index).activityInfo.name; if(className != null) { Intent switchIntent = new Intent(); switchIntent.setAction(Intent.ACTION_MAIN); switchIntent.addCategory(Intent.CATEGORY_LAUNCHER); switchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); switchIntent.setComponent(new ComponentName(process, className)); startActivity(switchIntent); getActivity().finish(); } } private void setPrority(int pid, String process, int prority) { // pass information ProcessProrityFragment newPrority = new ProcessProrityFragment(); Bundle args = new Bundle(); args.putInt(ProcessProrityFragment.TARGETPID, pid); args.putString(ProcessProrityFragment.TARGETNAME, infoHelper.getPackageName(process)); args.putInt(ProcessProrityFragment.DEFAULTPRORITY, prority); newPrority.setArguments(args); // replace current fragment final FragmentManager fragmanger = getActivity().getSupportFragmentManager(); newPrority.show(fragmanger, "prority"); } @Override public void onRecvData(ipcMessage result) { // check if(ipcStop == true) return; // stop update if (stopUpdate == true || result == null) { ipcAction newCommand[] = { ipcAction.OS, ipcAction.PROCESS }; ipcService.addRequest(newCommand, settings.getInterval(), this); return; } // clean up while (!data.isEmpty()) data.remove(0); data.clear(); // convert data // TODO: reuse old objects for (int index = 0; index < result.getDataCount(); index++) { try { ipcData rawData = result.getData(index); // process osInfo if (rawData.getAction() == ipcAction.OS) { info = osInfo.parseFrom(rawData.getPayload(0)); continue; } // skip others if (rawData.getAction() != ipcAction.PROCESS) continue; // summary all system processes processInfo.Builder syspsInfo = processInfo.newBuilder(); // fixed value syspsInfo.setPid(0); syspsInfo.setUid(0); syspsInfo.setPpid(0); syspsInfo.setName("System"); syspsInfo.setOwner("root"); syspsInfo.setPriorityLevel(0); syspsInfo.setStatus(processInfo.processStatus.Running); // summary value syspsInfo.setCpuUsage(0); syspsInfo.setRss(0); syspsInfo.setVsz(0); syspsInfo.setStartTime(0); syspsInfo.setThreadCount(0); syspsInfo.setUsedSystemTime(0); syspsInfo.setUsedUserTime(0); syspsInfo.setCpuTime(0); // process processInfo for (int count = 0; count < rawData.getPayloadCount(); count++) { processInfo psInfo = processInfo.parseFrom(rawData.getPayload(count)); boolean doMerge = false; if( psInfo.getUid() == 0 || psInfo.getName().contains("/system/") || psInfo.getName().contains("/sbin/") ) doMerge = true; if(psInfo.getName().toLowerCase(Locale.getDefault()).contains("osmcore")) doMerge = false; if(settings.isUseExpertMode()) doMerge = false; // Don't merge data if(doMerge == false) { data.add(psInfo); continue; } // Merge process information into a process syspsInfo.setCpuUsage(syspsInfo.getCpuUsage()+psInfo.getCpuUsage()); syspsInfo.setRss(syspsInfo.getRss()+psInfo.getRss()); syspsInfo.setVsz(syspsInfo.getVsz()+psInfo.getVsz()); syspsInfo.setThreadCount(syspsInfo.getThreadCount()+psInfo.getThreadCount()); syspsInfo.setUsedSystemTime(syspsInfo.getUsedSystemTime()+psInfo.getUsedSystemTime()); syspsInfo.setUsedUserTime(syspsInfo.getUsedUserTime()+psInfo.getUsedUserTime()); syspsInfo.setCpuTime(syspsInfo.getCpuTime()+psInfo.getCpuTime()); if(syspsInfo.getStartTime() < psInfo.getStartTime() || syspsInfo.getStartTime() == 0) syspsInfo.setStartTime(psInfo.getStartTime()); } if(!settings.isUseExpertMode()) data.add(syspsInfo.build()); } catch (Exception e) { e.printStackTrace(); } } // calculate CPU Usage float totalCPUUsage = 0; for (int index = 0; index < data.size(); index++) totalCPUUsage += data.get(index).getCpuUsage(); // sort data switch(sortSetting) { case SortbyUsage: Collections.sort(data, new SortbyUsage()); break; case SortbyMemory: Collections.sort(data, new SortbyMemory()); break; case SortbyPid: Collections.sort(data, new SortbyPid()); break; case SortbyName: Collections.sort(data, new SortbyName()); break; case SortbyCPUTime: Collections.sort(data, new SortbyCPUTime()); break; } processCount.setText(""+data.size()); cpuUsage.setText(CommonUtil.convertToUsage(totalCPUUsage) + "%"); if (info != null) { memoryTotal.setText(CommonUtil.convertToSize(info.getTotalMemory(), true)); memoryFree.setText(CommonUtil.convertToSize(info.getFreeMemory()+ info.getBufferedMemory()+ info.getCachedMemory(), true)); } getActivity().runOnUiThread( new Runnable() { public void run() { ((ProcessListAdapter) getListAdapter()).refresh(); } }); // send command again ipcAction newCommand[] = { ipcAction.OS, ipcAction.PROCESS }; ipcService.addRequest(newCommand, settings.getInterval(), this); } /** * Comparator class for sort by usage */ private class SortbyUsage implements Comparator<processInfo> { @Override public int compare(processInfo lhs, processInfo rhs) { if (lhs.getCpuUsage() > rhs.getCpuUsage()) return -1; else if (lhs.getCpuUsage() < rhs.getCpuUsage()) return 1; return 0; } } /** * Comparator class for sort by memory */ private class SortbyMemory implements Comparator<processInfo> { @Override public int compare(processInfo lhs, processInfo rhs) { if (lhs.getRss() > rhs.getRss()) return -1; else if (lhs.getRss() < rhs.getRss()) return 1; return 0; } } /** * Comparator class for sort by Pid */ private class SortbyPid implements Comparator<processInfo> { @Override public int compare(processInfo lhs, processInfo rhs) { if (lhs.getPid() > rhs.getPid()) return -1; else if (lhs.getPid() < rhs.getPid()) return 1; return 0; } } /** * Comparator class for sort by Name */ private class SortbyName implements Comparator<processInfo> { @Override public int compare(processInfo lhs, processInfo rhs) { Collator collator = Collator.getInstance(); String lhsName = infoHelper.getPackageName(lhs.getName()); if (lhsName == null) lhsName = lhs.getName(); String rhsName = infoHelper.getPackageName(rhs.getName()); if (rhsName == null) rhsName = rhs.getName(); if (collator.compare(lhsName, rhsName) == -1) return -1; else if (collator.compare(lhsName, rhsName) == 1) return 1; return 0; } } /** * Comparator class for sort by CPU time */ private class SortbyCPUTime implements Comparator<processInfo> { @Override public int compare(processInfo lhs, processInfo rhs) { if (lhs.getCpuTime() > rhs.getCpuTime()) return -1; else if (lhs.getCpuTime() < rhs.getCpuTime()) return 1; return 0; } } /** * implement viewholder class for process list */ private class ViewHolder { // main information TextView pid; ImageView icon; TextView name; TextView cpuUsage; // color int bkcolor; // phone layout detail information LinearLayout detail; // tablet layout detail information TextView detailTitle; ImageView detailIcon; // common detail information TextView detailName; TextView detailStatus; TextView detailStime; TextView detailUtime; TextView detailCPUtime; TextView detailMemory; TextView detailPPID; TextView detailUser; TextView detailStarttime; TextView detailThread; TextView detailNice; } private void setItemStatus(View v, boolean status) { // change expand status if (status) { ViewHolder holder = (ViewHolder) v.getTag(); if (holder.detail == null) { // loading view ViewStub stub = (ViewStub) v.findViewById(R.id.id_process_detail_viewstub); stub.inflate(); // prepare detail information holder.detail = (LinearLayout) v.findViewById(R.id.id_process_detail_stub); holder.detailName = ((TextView) v.findViewById(R.id.id_process_detail_name)); holder.detailStatus = ((TextView) v.findViewById(R.id.id_process_detail_status)); holder.detailStime = ((TextView) v.findViewById(R.id.id_process_detail_stime)); holder.detailUtime = ((TextView) v.findViewById(R.id.id_process_detail_utime)); holder.detailCPUtime = ((TextView) v.findViewById(R.id.id_process_detail_cputime)); holder.detailMemory = ((TextView) v.findViewById(R.id.id_process_detail_memory)); holder.detailPPID = ((TextView) v.findViewById(R.id.id_process_detail_ppid)); holder.detailUser = ((TextView) v.findViewById(R.id.id_process_detail_user)); holder.detailStarttime = ((TextView) v.findViewById(R.id.id_process_detail_starttime)); holder.detailThread = ((TextView) v.findViewById(R.id.id_process_detail_thread)); holder.detailNice = ((TextView) v.findViewById(R.id.id_process_detail_nice)); } else holder.detail.setVisibility(View.VISIBLE); } else { ViewHolder holder = (ViewHolder) v.getTag(); if (holder.detail != null) holder.detail.setVisibility(View.GONE); } } private static void setSelectStatus(View v, int position, boolean status) { if (status) v.setBackgroundColor(itemColor[selectedItem]); else if (position % 2 == 0) v.setBackgroundColor(itemColor[oddItem]); else v.setBackgroundColor(itemColor[evenItem]); } private class ProcessListAdapter extends BaseAdapter { private LayoutInflater itemInflater = null; private ViewHolder holder = null; public ProcessListAdapter(Context mContext) { itemInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View sv = null; // get data processInfo item = data.get(position); // check cached status if (!infoHelper.checkPackageInformation(item.getName())) { if(item.getName().toLowerCase(Locale.getDefault()).contains("osmcore")) infoHelper.doCacheInfo(android.os.Process.myUid(), item.getOwner(), item.getName()); else infoHelper.doCacheInfo(item.getUid(), item.getOwner(), item.getName()); } // prepare view if (convertView == null) { sv = (View) itemInflater.inflate(R.layout.ui_process_item, parent, false); holder = new ViewHolder(); holder.pid = ((TextView) sv.findViewById(R.id.id_process_pid)); holder.name = ((TextView) sv.findViewById(R.id.id_process_name)); holder.cpuUsage = ((TextView) sv.findViewById(R.id.id_process_value)); holder.icon = ((ImageView) sv.findViewById(R.id.id_process_icon)); sv.setTag(holder); } else { sv = (View) convertView; holder = (ViewHolder) sv.getTag(); } sv.setOnClickListener(new ProcessClickListener(position)); sv.setOnLongClickListener(new ProcessLongClickListener(position)); // check expand status if (!tabletLayout) { if (expandStatus.containsKey(data.get(position).getName()) == true) setItemStatus(sv, true); else setItemStatus(sv, false); } // draw current color for each item if (selectedStatus.containsKey(data.get(position).getName()) == true) holder.bkcolor = itemColor[selectedItem]; else if (position % 2 == 0) holder.bkcolor = itemColor[oddItem]; else holder.bkcolor = itemColor[evenItem]; sv.setBackgroundColor(holder.bkcolor); // offer better indicator for interactive sv.setOnTouchListener(new OnTouchListener () { @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: v.setBackgroundColor(getResources().getColor(R.color.selected_osmonitor)); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: ViewHolder holder = (ViewHolder) v.getTag(); v.setBackgroundColor(holder.bkcolor); break; } return false; } }); // prepare main information holder.pid.setText(String.format("%5d", item.getPid())); holder.name.setText(infoHelper.getPackageName(item.getName())); holder.icon.setImageDrawable(infoHelper.getPackageIcon(item.getName())); if(sortSetting == SortType.SortbyMemory) holder.cpuUsage.setText(CommonUtil.convertToSize((item.getRss()*1024), true)); else if(sortSetting == SortType.SortbyCPUTime) holder.cpuUsage.setText(String.format("%02d:%02d", item.getCpuTime()/60, item.getCpuTime() % 60)); else holder.cpuUsage.setText(CommonUtil.convertToUsage(item.getCpuUsage())); // prepare detail information if (holder.detail != null) showProcessDetail(holder, item); return sv; } private void refreshTabletPanel() { if (selectedPID == -1) return; // find target Item processInfo targetItem = null; for (int i = 0; i < data.size(); i++) { if (data.get(i).getPid() != selectedPID) continue; targetItem = data.get(i); break; } // show if (targetItem != null && selectedHolder != null) { selectedProcess = targetItem.getName(); selectedPrority = targetItem.getPriorityLevel(); showProcessDetail(selectedHolder, targetItem ); } } private void showProcessDetail( ViewHolder holder, processInfo item) { if (holder.detailTitle != null) holder.detailTitle.setText(infoHelper.getPackageName(item.getName())); if (holder.detailIcon != null) holder.detailIcon.setImageDrawable(infoHelper.getPackageIcon(item.getName())); holder.detailName.setText(item.getName()); holder.detailStime.setText(String.format("%,d", item.getUsedSystemTime())); holder.detailUtime.setText(String.format("%,d", item.getUsedUserTime())); holder.detailCPUtime.setText(String.format("%02d:%02d", item.getCpuTime()/60, item.getCpuTime() % 60)); holder.detailThread.setText(String.format("%d", item.getThreadCount())); holder.detailNice.setText(String.format("%d", item.getPriorityLevel())); // get memory information MemoryInfo memInfo = infoHelper.getMemoryInfo(item.getPid()); String memoryData = CommonUtil.convertToSize((item.getRss()*1024), true)+" / "+ CommonUtil.convertToSize(memInfo.getTotalPss()*1024, true)+" / " + CommonUtil.convertToSize(memInfo.getTotalPrivateDirty()*1024, true) ; holder.detailMemory.setText(memoryData); holder.detailPPID.setText(""+item.getPpid()); // convert time format final Calendar calendar = Calendar.getInstance(); final DateFormat convertTool = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.getDefault()); calendar.setTimeInMillis(item.getStartTime()*1000); holder.detailStarttime.setText(convertTool.format(calendar.getTime())); holder.detailUser.setText(item.getOwner()); // convert status switch(item.getStatus().getNumber()) { case processInfo.processStatus.Unknown_VALUE: holder.detailStatus.setText(R.string.ui_process_status_unknown); break; case processInfo.processStatus.Running_VALUE: holder.detailStatus.setText(R.string.ui_process_status_running); break; case processInfo.processStatus.Sleep_VALUE: holder.detailStatus.setText(R.string.ui_process_status_sleep); break; case processInfo.processStatus.Stopped_VALUE: holder.detailStatus.setText(R.string.ui_process_status_stop); break; case processInfo.processStatus.Page_VALUE: case processInfo.processStatus.Disk_VALUE: holder.detailStatus.setText(R.string.ui_process_status_waitio); break; case processInfo.processStatus.Zombie_VALUE: holder.detailStatus.setText(R.string.ui_process_status_zombie); break; } } public void refresh() { this.notifyDataSetChanged(); if (tabletLayout == true) refreshTabletPanel(); } private class ProcessLongClickListener implements OnLongClickListener { private int position; public ProcessLongClickListener(int position) { this.position = position; } @Override public boolean onLongClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(infoHelper.getPackageName(data.get(position).getName())) .setItems(R.array.ui_process_menu_item, new ProcessItemMenu(position)); builder.create().show(); return false; } } private class ProcessItemMenu implements DialogInterface.OnClickListener { private String process; private int pid; private int prority; public ProcessItemMenu(int position) { this.process = data.get(position).getName(); this.pid = data.get(position).getPid(); this.prority = data.get(position).getPriorityLevel(); } public void onClick(DialogInterface dialog, int which) { switch(which) { case 0: killProcess(pid, process); break; case 1: switchToProcess(pid, process); break; case 2: watchLog(pid, process); break; case 3: setPrority(pid, process, prority); break; } } } private class ProcessClickListener implements OnClickListener { private int position; public ProcessClickListener(int position) { this.position = position; } public void onClick(View v) { // enter kill mode if( killSetting == KillMode.Select) { this.ToogleSelected(v); return; } // phone if(!tabletLayout) { this.ToogleExpand(v); return; } // tablet ViewHolder holder = (ViewHolder) v.getTag(); if (holder != null) selectedPID = Integer.parseInt(holder.pid.getText().toString().trim()); // refresh refreshTabletPanel(); return; } private void ToogleSelected(View v) { // change expand status if (selectedStatus.containsKey(data.get(position).getName()) == false) { selectedStatus.put(data.get(position).getName(), data.get(position).getPid()); setSelectStatus(v, position, true); } else { selectedStatus.remove(data.get(position).getName()); setSelectStatus(v, position, false); } } private void ToogleExpand(View v) { // data must ready to read if (position > data.size()) return; // change expand status if (expandStatus.containsKey(data.get(position).getName()) == false) { expandStatus.put(data.get(position).getName(), Boolean.TRUE); setItemStatus(v, true); // force redraw single row ListView list = getListView(); list.getAdapter().getView(position, v, list); } else { expandStatus.remove(data.get(position).getName()); setItemStatus(v, false); } } } } @SuppressLint("SetJavaScriptEnabled") void ShowHelp() { CommonUtil.showHelp(getActivity(), "file:///android_asset/help/help-process.html"); } }
package org.biojava.bio.seq; import java.util.Iterator; import org.biojava.bio.BioError; import org.biojava.bio.BioException; import org.biojava.utils.AbstractChangeable; import org.biojava.utils.ChangeVetoException; /** * An abstract implementation of FeatureHolder. * * This provides the filter method, but who wants to code that more than * once? It also has support for the ChangeEvents. * * @author Matthew Pocock * @author Thomas Down */ public abstract class AbstractFeatureHolder extends AbstractChangeable implements FeatureHolder { public FeatureHolder filter(FeatureFilter filter) { boolean recurse = !FilterUtils.areProperSubset(filter, FeatureFilter.top_level); return filter(filter, recurse); } public FeatureHolder filter(FeatureFilter ff, boolean recurse) { SimpleFeatureHolder res = new SimpleFeatureHolder(); for(Iterator f = features(); f.hasNext();) { Feature feat = (Feature) f.next(); if(ff.accept(feat)) { try { res.addFeature(feat); } catch (ChangeVetoException cve) { throw new BioError( "Assertion failed: Couldn't add a feature to my new FeatureHolder" ); } } if(recurse) { FeatureHolder r = feat.filter(ff, recurse); for(Iterator rf = r.features(); rf.hasNext();) { try { res.addFeature((Feature) rf.next()); } catch (ChangeVetoException cve) { throw new BioError( "Assertion failure: Should be able to manipulate this FeatureHolder", cve ); } } } } return res; } public Feature createFeature(Feature.Template temp) throws BioException, ChangeVetoException { throw new ChangeVetoException( "This FeatureHolder does not support creation of new Features." ); } public void removeFeature(Feature f) throws ChangeVetoException, BioException { throw new ChangeVetoException( "This FeatureHolder does not support removal of Features." ); } }
package org.biojava.bio.seq.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.LinkedHashMap; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.biojava.bio.BioException; import org.biojava.bio.seq.DNATools; import org.biojava.bio.seq.ProteinTools; import org.biojava.bio.symbol.Alignment; import org.biojava.bio.symbol.FiniteAlphabet; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.bio.symbol.SimpleAlignment; import org.biojava.bio.symbol.SimpleSymbolList; import org.biojava.bio.symbol.Symbol; import org.biojava.bio.symbol.SymbolList; /** * @author raemig * @author Thomas Down * @author Keith James * @author Nimesh Singh * @author Mark Schreiber * @author Matthew Pocock * @author Bradford Powell */ public class MSFAlignmentFormat implements AlignmentFormat { private static final boolean DEBUGPRINT = false; private static final int DNA = 1; private static final int PROTEIN = 2; public MSFAlignmentFormat () { } /** * used to quick test the code * @param args */ public static void main (String[] args) { String filename; if (args.length < 1) { filename = "SimpleMSF.msf"; //change to your favorite } else { filename = args[0]; } try { BufferedReader reader = new BufferedReader(new FileReader(filename)); MSFAlignmentFormat MSFAlignmentFormat1 = new MSFAlignmentFormat(); MSFAlignmentFormat1.read(reader); } catch (Exception E) {} } /** * Reads an MSF Alignment File * @param reader The file reader * @return Alignment A SimpleAlignment consisting of the sequences in the file. */ public Alignment read (BufferedReader reader) { Vector sequenceNames = new Vector(); String sequenceName = null; StringBuffer sequenceData[] = null; int startOfData = 0; //the start of the sequence data in the line int currSeqCount = 0; //which sequence data you are currently trying to get try { Pattern mtc = Pattern.compile("Name:\\s+(.*?)\\s+(oo|Len:)"); Pattern removewhitespace = Pattern.compile("\\s"); // REMatch rem = null; String line = reader.readLine(); //parse past header while (line.indexOf("Name:") == -1) { line = reader.readLine(); } //read each name (between Name: and Len: while ((line.indexOf("//") == -1) && ((line.trim()).length() != 0)) { Matcher matcher = mtc.matcher(line); if (!matcher.find()) { break; } //end of sequence names //sequenceName = line.substring(rem.getSubStartIndex(1), // rem.getSubEndIndex(1)); if ((line.trim()).length() == 0) { break; } sequenceName = matcher.group(1).trim(); sequenceNames.add(sequenceName); line = reader.readLine(); } sequenceData = new StringBuffer[sequenceNames.size()]; for (int it = 0; it < sequenceNames.size(); it++) { sequenceData[it] = new StringBuffer(); } //until you get a line that matches the first sequence while (line.indexOf((String)sequenceNames.get(0)) == -1) { line = reader.readLine(); } //now you on the first line of the sequence data while (line != null) { for (currSeqCount = 0; currSeqCount < sequenceNames.size(); currSeqCount++) {//you could also check for order of names if (line.indexOf((String)sequenceNames.get(currSeqCount)) == -1) { break; } //error startOfData = line.indexOf((String)sequenceNames.get(currSeqCount)) + ((String)sequenceNames.get(currSeqCount)).length(); line = (line.substring(startOfData)); line = removewhitespace.matcher(line).replaceAll(""); sequenceData[currSeqCount].append(line); //make into string buffer line = reader.readLine(); if ((currSeqCount < sequenceNames.size() - 1) && (line.trim().length() == 0)) { break; } //could be an error } //until you get a line that matches the first sequence while ((line != null) && (line.indexOf((String)sequenceNames.get(0)) == -1)) // || ( (line.trim()) .length()>0 ) ) { line = reader.readLine(); } } //print them out for testing if (DEBUGPRINT) { for (currSeqCount = 0; currSeqCount < sequenceNames.size(); currSeqCount++) { System.out.println((String)sequenceNames.get(currSeqCount) + ":" + sequenceData[currSeqCount]); } } //check DNA, RNA or Prot StringBuffer testString = new StringBuffer(); int agct = 0; for (currSeqCount = 0; currSeqCount < sequenceNames.size(); currSeqCount++) { testString.append(sequenceData[currSeqCount]); } String testStringUpper=testString.toString().toUpperCase(); //now parse through them and create gapped symbol lists LinkedHashMap sequenceDataMap = new LinkedHashMap(); Symbol sym = null; FiniteAlphabet alph = null; for (int i = 0; i < testStringUpper.length(); i++) { char c=testStringUpper.charAt(i); if (c == 'F' || c == 'L' || c == 'I' || c == 'P' || c == 'Q' || c == 'E') { alph = ProteinTools.getTAlphabet(); break; } } if (alph == null) { alph = DNATools.getDNA(); } SymbolTokenization parse = alph.getTokenization("token"); for (currSeqCount = 0; currSeqCount < sequenceNames.size(); currSeqCount++) { String sd = sequenceData[currSeqCount].toString(); //change stop codons to specified symbols sd = sd.replace('~', '-'); //sometimes this is a term signal not a gap sd = sd.replace('.', '-'); //sometimes this is a term signal not a gap sequenceDataMap.put((String)sequenceNames.get(currSeqCount), new SimpleSymbolList(parse, sd)); } SimpleAlignment sa=new SimpleAlignment(sequenceDataMap); return (sa); } catch (Exception e) { e.printStackTrace(); System.err.println("MSFFormatReader " + e.getMessage()); // throw (e); } return (null); } //end read it //This is where I am writing an alignment writer public void write(OutputStream os, Alignment align, int fileType) throws BioException, IllegalSymbolException { PrintStream out = new PrintStream(os); Object labels[] = align.getLabels().toArray(); int numSeqs = labels.length; Iterator seqIts[] = new Iterator[numSeqs]; int maxLabelLength = 0; for (int i = 0; i < numSeqs; i++) { seqIts[i] = align.symbolListForLabel(labels[i]).iterator(); if (((String) labels[i]).length() > maxLabelLength) { maxLabelLength = ((String) labels[i]).length(); } } String nl = System.getProperty("line.separator"); SymbolTokenization toke = null; //really should determine the filetype based on one of the seqeunces alphabet if (align.symbolListForLabel(labels[0]).getAlphabet()==DNATools.getDNA()) { fileType = DNA; } else if (align.symbolListForLabel(labels[0]).getAlphabet()==ProteinTools.getAlphabet() ||align.symbolListForLabel(labels[0]).getAlphabet()==ProteinTools.getTAlphabet() ) { fileType = PROTEIN; } if (fileType == DNA) { out.print("PileUp"+nl); out.print(nl); out.print(" MSF: " + align.length() + " Type: "); out.print("N"); out.print(" Check: "+0+" .."+nl); toke = DNATools.getDNA().getTokenization("token"); } else if (fileType == PROTEIN) { out.print("PileUp"+nl); out.print(nl); out.print(" MSF: " + align.length() + " Type: "); out.print("P"); out.print(" Check: "+0+" .."+nl); toke = ProteinTools.getTAlphabet().getTokenization("token"); } else { System.out.println("MSFAlignment.write -- File type not recognized."); return; } out.print(nl); for (int i = 0; i < numSeqs; i++) { out.print(" Name: " + labels[i]); for (int j = 0; j < (maxLabelLength - ((String) labels[i]).length()); j++) {//padding out.print(" "); } out.print(" Len: " + align.length() +" Check: "+0+" Weight: "+0+nl); //this really should be seq length? } out.println(nl+"//"+nl+nl); //now should print the numbering line while (seqIts[0].hasNext()) { for (int i = 0; i < numSeqs; i++) { while (((String) labels[i]).length() < maxLabelLength + 1) { labels[i] = " " + labels[i]; } out.print(labels[i] + " "); theLabel: for (int j = 0; j < 5; j++) { out.print(" "); for (int k = 0; k < 10; k++) { if (seqIts[i].hasNext()) { out.print(toke.tokenizeSymbol((Symbol) seqIts[i].next())); } else { break theLabel; } } } out.print(nl); } out.print(nl); } } //end write public void writeDna(OutputStream os, Alignment align) throws BioException, IllegalSymbolException { write(os, align, DNA); } public void writeProtein(OutputStream os, Alignment align) throws BioException, IllegalSymbolException { write(os, align, PROTEIN); } } //end class
package org.biojava.bio.symbol; import org.biojava.utils.*; import org.biojava.bio.*; /** * A no-frills implementation of AtomicSymbol. * * @author Matthew Pocock */ public class SimpleAtomicSymbol implements AtomicSymbol { private final char token; private final String name; private final Annotation annotation; private final SingletonAlphabet alphabet; protected ChangeSupport changeSupport = null; protected Annotatable.AnnotationForwarder annotationForwarder = null; public SimpleAtomicSymbol(char token, String name, Annotation annotation) { if(annotation == null) { throw new IllegalArgumentException("Can't use null Annotation"); } this.token = token; this.name = name; this.annotation = new SimpleAnnotation(annotation); this.alphabet = new SingletonAlphabet(this); } public char getToken() { return token; } public String getName() { return name; } public Annotation getAnnotation() { return annotation; } public Alphabet getMatches() { return alphabet; } protected void generateChangeSupport(ChangeType changeType) { if(changeSupport == null) { changeSupport = new ChangeSupport(); } if( ((changeType == null) || (changeType == Annotation.PROPERTY)) && (annotationForwarder == null) ) { annotationForwarder = new Annotatable.AnnotationForwarder(this, changeSupport); annotation.addChangeListener(annotationForwarder, Annotation.PROPERTY); } } public void addChangeListener(ChangeListener cl) { generateChangeSupport(null); synchronized(changeSupport) { changeSupport.addChangeListener(cl); } } public void addChangeListener(ChangeListener cl, ChangeType ct) { generateChangeSupport(ct); synchronized(changeSupport) { changeSupport.addChangeListener(cl, ct); } } public void removeChangeListener(ChangeListener cl) { if(changeSupport != null) { synchronized(changeSupport) { changeSupport.removeChangeListener(cl); } } } public void removeChangeListener(ChangeListener cl, ChangeType ct) { if(changeSupport != null) { synchronized(changeSupport) { changeSupport.removeChangeListener(cl, ct); } } } }
package org.concord.sensor.serial; public class SerialException extends Exception { /** * This is reimplemented here instead of using the cause * support in Exception because waba doesn't have that cause * support. */ Throwable cause; int error; public SerialException(String message){ super(message); } public SerialException(String message, int error){ super(message); this.error = error; } public SerialException(String message, Throwable cause){ super(message); this.cause = cause; } public int getPortError(){ return error; } }
package org.jitsi.impl.neomedia; import java.io.*; import java.lang.reflect.*; import java.util.*; import javax.media.*; import javax.media.format.*; import javax.media.protocol.*; import javax.media.rtp.*; import javax.media.rtp.event.*; import javax.media.rtp.rtcp.*; import org.jitsi.impl.neomedia.protocol.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.*; import com.sun.media.rtp.*; /** * Implements <tt>RTPTranslator</tt> which represents an RTP translator which * forwards RTP and RTCP traffic between multiple <tt>MediaStream</tt>s. * * @author Lyubomir Marinov */ public class RTPTranslatorImpl implements ReceiveStreamListener, RTPTranslator { /** * The <tt>Logger</tt> used by the <tt>RTPTranslatorImpl</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(RTPTranslatorImpl.class); /** * The indicator which determines whether the method * {@link #createFakeSendStreamIfNecessary()} is to be executed by * <tt>RTPTranslatorImpl</tt>. */ private static final boolean CREATE_FAKE_SEND_STREAM_IF_NECESSARY = false; /** * An array with <tt>long</tt> element type and no elements explicitly * defined to reduce unnecessary allocations. */ private static final long[] EMPTY_LONG_ARRAY = new long[0]; /** * The <tt>RTPConnector</tt> which is used by {@link #manager} and which * delegates to the <tt>RTPConnector</tt>s of the <tt>StreamRTPManager</tt>s * attached to this instance. */ private RTPConnectorImpl connector; private SendStream fakeSendStream; /** * The <tt>RTPManager</tt> which implements the actual RTP management of * this instance. */ private final RTPManager manager = RTPManager.newInstance(); private final List<SendStreamDesc> sendStreams = new LinkedList<SendStreamDesc>(); /** * The list of <tt>StreamRTPManager</tt>s i.e. <tt>MediaStream</tt>s which * this instance forwards RTP and RTCP traffic between. */ private final List<StreamRTPManagerDesc> streamRTPManagers = new ArrayList<StreamRTPManagerDesc>(); /** * Initializes a new <tt>RTPTranslatorImpl</tt> instance. */ public RTPTranslatorImpl() { manager.addReceiveStreamListener(this); } public synchronized void addFormat( StreamRTPManager streamRTPManager, Format format, int payloadType) { manager.addFormat(format, payloadType); getStreamRTPManagerDesc(streamRTPManager, true) .addFormat(format, payloadType); } public synchronized void addReceiveStreamListener( StreamRTPManager streamRTPManager, ReceiveStreamListener listener) { getStreamRTPManagerDesc(streamRTPManager, true) .addReceiveStreamListener(listener); } public void addRemoteListener( StreamRTPManager streamRTPManager, RemoteListener listener) { manager.addRemoteListener(listener); } public void addSendStreamListener( StreamRTPManager streamRTPManager, SendStreamListener listener) { // TODO Auto-generated method stub } public void addSessionListener( StreamRTPManager streamRTPManager, SessionListener listener) { // TODO Auto-generated method stub } /** * Closes {@link #fakeSendStream} if it exists and is considered no longer * necessary; otherwise, does nothing. */ private synchronized void closeFakeSendStreamIfNotNecessary() { /* * If a SendStream has been created in response to a request from the * clients of this RTPTranslator implementation, the newly-created * SendStream in question will disperse the received RTP and RTCP from * remote peers so fakeSendStream will be obsolete. */ try { if ((!sendStreams.isEmpty() || (streamRTPManagers.size() < 2)) && (fakeSendStream != null)) { try { fakeSendStream.close(); } catch (NullPointerException npe) { /* * Refer to MediaStreamImpl#stopSendStreams( * Iterable<SendStream>, boolean) for an explanation about * the swallowing of the exception. */ logger.error("Failed to close fake send stream", npe); } finally { fakeSendStream = null; } } } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; else if (logger.isDebugEnabled()) { logger.debug( "Failed to close the fake SendStream of this" + " RTPTranslator.", t); } } } private synchronized void closeSendStream(SendStreamDesc sendStreamDesc) { if (sendStreams.contains(sendStreamDesc) && (sendStreamDesc.getSendStreamCount() < 1)) { SendStream sendStream = sendStreamDesc.sendStream; try { sendStream.close(); } catch (NullPointerException npe) { /* * Refer to MediaStreamImpl#stopSendStreams( * Iterable<SendStream>, boolean) for an explanation about the * swallowing of the exception. */ logger.error("Failed to close send stream", npe); } sendStreams.remove(sendStreamDesc); } } /** * Creates {@link #fakeSendStream} if it does not exist yet and is * considered necessary; otherwise, does nothing. */ private synchronized void createFakeSendStreamIfNecessary() { /* * If no SendStream has been created in response to a request from the * clients of this RTPTranslator implementation, it will need * fakeSendStream in order to be able to disperse the received RTP and * RTCP from remote peers. Additionally, the fakeSendStream is not * necessary in the case of a single client of this RTPTranslator * because there is no other remote peer to disperse the received RTP * and RTCP to. */ if ((fakeSendStream == null) && sendStreams.isEmpty() && (streamRTPManagers.size() > 1)) { Format supportedFormat = null; for (StreamRTPManagerDesc s : streamRTPManagers) { Format[] formats = s.getFormats(); if ((formats != null) && (formats.length > 0)) { for (Format f : formats) { if (f != null) { supportedFormat = f; break; } } if (supportedFormat != null) break; } } if (supportedFormat != null) { try { fakeSendStream = manager.createSendStream( new FakePushBufferDataSource(supportedFormat), 0); } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; else { logger.error( "Failed to create a fake SendStream to ensure" + " that this RTPTranslator is able to" + " disperse RTP and RTCP received from" + " remote peers even when the local peer" + " is not generating media to be" + " transmitted.", t); } } } } } public synchronized SendStream createSendStream( StreamRTPManager streamRTPManager, DataSource dataSource, int streamIndex) throws IOException, UnsupportedFormatException { SendStreamDesc sendStreamDesc = null; for (SendStreamDesc s : sendStreams) if ((s.dataSource == dataSource) && (s.streamIndex == streamIndex)) { sendStreamDesc = s; break; } if (sendStreamDesc == null) { SendStream sendStream = manager.createSendStream(dataSource, streamIndex); if (sendStream != null) { sendStreamDesc = new SendStreamDesc(dataSource, streamIndex, sendStream); sendStreams.add(sendStreamDesc); closeFakeSendStreamIfNotNecessary(); } } return (sendStreamDesc == null) ? null : sendStreamDesc.getSendStream(streamRTPManager, true); } /** * Releases the resources allocated by this instance in the course of its * execution and prepares it to be garbage collected. */ public synchronized void dispose() { manager.removeReceiveStreamListener(this); try { manager.dispose(); } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; else { /* * RTPManager.dispose() often throws at least a * NullPointerException in relation to some RTP BYE. */ logger.error("Failed to dispose of RTPManager", t); } } } public synchronized void dispose(StreamRTPManager streamRTPManager) { Iterator<StreamRTPManagerDesc> streamRTPManagerIter = streamRTPManagers.iterator(); while (streamRTPManagerIter.hasNext()) { StreamRTPManagerDesc streamRTPManagerDesc = streamRTPManagerIter.next(); if (streamRTPManagerDesc.streamRTPManager == streamRTPManager) { RTPConnectorDesc connectorDesc = streamRTPManagerDesc.connectorDesc; if (connectorDesc != null) { if (this.connector != null) this.connector.removeConnector(connectorDesc); connectorDesc.connector.close(); streamRTPManagerDesc.connectorDesc = null; } streamRTPManagerIter.remove(); closeFakeSendStreamIfNotNecessary(); break; } } } private synchronized StreamRTPManagerDesc findStreamRTPManagerDescByReceiveSSRC( long receiveSSRC, StreamRTPManagerDesc exclusion) { for (int i = 0, count = streamRTPManagers.size(); i < count; i++) { StreamRTPManagerDesc s = streamRTPManagers.get(i); if ((s != exclusion) && s.containsReceiveSSRC(receiveSSRC)) return s; } return null; } public Object getControl( StreamRTPManager streamRTPManager, String controlType) { return manager.getControl(controlType); } public GlobalReceptionStats getGlobalReceptionStats( StreamRTPManager streamRTPManager) { return manager.getGlobalReceptionStats(); } public GlobalTransmissionStats getGlobalTransmissionStats( StreamRTPManager streamRTPManager) { return manager.getGlobalTransmissionStats(); } public long getLocalSSRC(StreamRTPManager streamRTPManager) { return ((RTPSessionMgr) manager).getLocalSSRC(); } public synchronized Vector<ReceiveStream> getReceiveStreams( StreamRTPManager streamRTPManager) { StreamRTPManagerDesc streamRTPManagerDesc = getStreamRTPManagerDesc(streamRTPManager, false); Vector<ReceiveStream> receiveStreams = null; if (streamRTPManagerDesc != null) { Vector<?> managerReceiveStreams = manager.getReceiveStreams(); if (managerReceiveStreams != null) { receiveStreams = new Vector<ReceiveStream>(managerReceiveStreams.size()); for (Object s : managerReceiveStreams) { ReceiveStream receiveStream = (ReceiveStream) s; if (streamRTPManagerDesc.containsReceiveSSRC( receiveStream.getSSRC())) receiveStreams.add(receiveStream); } } } return receiveStreams; } public synchronized Vector<SendStream> getSendStreams( StreamRTPManager streamRTPManager) { Vector<?> managerSendStreams = manager.getSendStreams(); Vector<SendStream> sendStreams = null; if (managerSendStreams != null) { sendStreams = new Vector<SendStream>(managerSendStreams.size()); for (SendStreamDesc sendStreamDesc : this.sendStreams) if (managerSendStreams.contains(sendStreamDesc.sendStream)) { SendStream sendStream = sendStreamDesc.getSendStream(streamRTPManager, false); if (sendStream != null) sendStreams.add(sendStream); } } return sendStreams; } private synchronized StreamRTPManagerDesc getStreamRTPManagerDesc( StreamRTPManager streamRTPManager, boolean create) { for (StreamRTPManagerDesc s : streamRTPManagers) if (s.streamRTPManager == streamRTPManager) return s; StreamRTPManagerDesc s; if (create) { s = new StreamRTPManagerDesc(streamRTPManager); streamRTPManagers.add(s); } else s = null; return s; } public synchronized void initialize( StreamRTPManager streamRTPManager, RTPConnector connector) { if (this.connector == null) { this.connector = new RTPConnectorImpl(); manager.initialize(this.connector); } StreamRTPManagerDesc streamRTPManagerDesc = getStreamRTPManagerDesc(streamRTPManager, true); RTPConnectorDesc connectorDesc = streamRTPManagerDesc.connectorDesc; if ((connectorDesc == null) || (connectorDesc.connector != connector)) { if (connectorDesc != null) this.connector.removeConnector(connectorDesc); streamRTPManagerDesc.connectorDesc = connectorDesc = (connector == null) ? null : new RTPConnectorDesc(streamRTPManagerDesc, connector); if (connectorDesc != null) this.connector.addConnector(connectorDesc); } } /** * Logs information about an RTCP packet using {@link #logger} for debugging * purposes. * * @param obj the object which is the source of the log request * @param methodName the name of the method on <tt>obj</tt> which is the * source of the log request * @param buffer the <tt>byte</tt>s which (possibly) represent an RTCP * packet to be logged for debugging purposes * @param offset the position within <tt>buffer</tt> at which the valid data * begins * @param length the number of bytes in <tt>buffer</tt> which constitute the * valid data */ private static void logRTCP( Object obj, String methodName, byte[] buffer, int offset, int length) { /* * Do the bytes in the specified buffer resemble (a header of) an RTCP * packet? */ if (length > 8) { byte b0 = buffer[offset]; int v = (b0 & 0xc0) >>> 6; if (v == 2) { byte b1 = buffer[offset + 1]; int pt = b1 & 0xff; if (pt == 203 /* BYE */) { int sc = b0 & 0x1f; long ssrc = (sc > 0) ? readInt(buffer, offset + 4) : -1; logger.trace( obj.getClass().getName() + '.' + methodName + ": RTCP BYE v=" + v + "; pt=" + pt + "; ssrc=" + ssrc + ';'); } } } } /** * Notifies this instance that an RTP or RTCP packet has been received from * a peer represented by a specific <tt>PushSourceStreamDesc</tt>. * * @param streamDesc a <tt>PushSourceStreamDesc</tt> which identifies the * peer from which an RTP or RTCP packet has been received * @param buffer the buffer which contains the bytes of the received RTP or * RTCP packet * @param offset the zero-based index in <tt>buffer</tt> at which the bytes * of the received RTP or RTCP packet begin * @param length the number of bytes in <tt>buffer</tt> beginning at * <tt>offset</tt> which are allowed to be accessed * @param read the number of bytes in <tt>buffer</tt> beginning at * <tt>offset</tt> which represent the received RTP or RTCP packet * @return the number of bytes in <tt>buffer</tt> beginning at * <tt>offset</tt> which represent the received RTP or RTCP packet * @throws IOException if an I/O error occurs while the method processes the * specified RTP or RTCP packet */ private int read( PushSourceStreamDesc streamDesc, byte[] buffer, int offset, int length, int read) throws IOException { boolean data = streamDesc.data; StreamRTPManagerDesc streamRTPManagerDesc = streamDesc.connectorDesc.streamRTPManagerDesc; Format format = null; if (data) { /* * Do the bytes in the specified buffer resemble (a header of) an * RTP packet? */ if ((length >= 12) && ( ((buffer[offset] & 0xc0) >>> 6) == 2)) { long ssrc = readInt(buffer, offset + 8); if (!streamRTPManagerDesc.containsReceiveSSRC(ssrc)) { if (findStreamRTPManagerDescByReceiveSSRC( ssrc, streamRTPManagerDesc) == null) streamRTPManagerDesc.addReceiveSSRC(ssrc); else return 0; } int pt = buffer[offset + 1] & 0x7f; format = streamRTPManagerDesc.getFormat(pt); } } else if (logger.isTraceEnabled()) logRTCP(this, "read", buffer, offset, read); /* * TODO A deadlock between PushSourceStreamImpl.removeStreams and * createFakeSendStreamIfNecessary has been reported. Since the latter * method is disabled at the time of this writing, do not even try to * execute it and thus avoid the deadlock in question. */ if (CREATE_FAKE_SEND_STREAM_IF_NECESSARY) createFakeSendStreamIfNecessary(); OutputDataStreamImpl outputStream = data ? connector.getDataOutputStream() : connector.getControlOutputStream(); if (outputStream != null) { outputStream.write( buffer, offset, read, format, streamRTPManagerDesc); } return read; } /** * Reads an <tt>int</tt> from a specific <tt>byte</tt> buffer starting at a * specific <tt>offset</tt>. The implementation is the same as * {@link DataInputStream#readInt()}. * * @param buffer the <tt>byte</tt> buffer to read an <tt>int</tt> from * @param offset the zero-based offset in <tt>buffer</tt> to start reading * an <tt>int</tt> from * @return an <tt>int</tt> read from the specified <tt>buffer</tt> starting * at the specified <tt>offset</tt> */ public static int readInt(byte[] buffer, int offset) { return ((buffer[offset++] & 0xff) << 24) | ((buffer[offset++] & 0xff) << 16) | ((buffer[offset++] & 0xff) << 8) | (buffer[offset] & 0xff); } public synchronized void removeReceiveStreamListener( StreamRTPManager streamRTPManager, ReceiveStreamListener listener) { StreamRTPManagerDesc streamRTPManagerDesc = getStreamRTPManagerDesc(streamRTPManager, false); if (streamRTPManagerDesc != null) streamRTPManagerDesc.removeReceiveStreamListener(listener); } public void removeRemoteListener( StreamRTPManager streamRTPManager, RemoteListener listener) { manager.removeRemoteListener(listener); } public void removeSendStreamListener( StreamRTPManager streamRTPManager, SendStreamListener listener) { // TODO Auto-generated method stub } public void removeSessionListener( StreamRTPManager streamRTPManager, SessionListener listener) { // TODO Auto-generated method stub } /** * Notifies this <tt>ReceiveStreamListener</tt> about a specific event * related to a <tt>ReceiveStream</tt>. * * @param event a <tt>ReceiveStreamEvent</tt> which contains the specifics * of the event this <tt>ReceiveStreamListener</tt> is being notified about * @see ReceiveStreamListener#update(ReceiveStreamEvent) */ public void update(ReceiveStreamEvent event) { /* * Because NullPointerException was seen during testing, be thorough * with the null checks. */ if (event != null) { ReceiveStream receiveStream = event.getReceiveStream(); if (receiveStream != null) { StreamRTPManagerDesc streamRTPManagerDesc = findStreamRTPManagerDescByReceiveSSRC( receiveStream.getSSRC(), null); if (streamRTPManagerDesc != null) for (ReceiveStreamListener listener : streamRTPManagerDesc.getReceiveStreamListeners()) listener.update(event); } } } private static class OutputDataStreamDesc { public RTPConnectorDesc connectorDesc; public OutputDataStream stream; public OutputDataStreamDesc( RTPConnectorDesc connectorDesc, OutputDataStream stream) { this.connectorDesc = connectorDesc; this.stream = stream; } } private static class OutputDataStreamImpl implements OutputDataStream, Runnable { private static final int WRITE_QUEUE_CAPACITY = RTPConnectorOutputStream .MAX_PACKETS_PER_MILLIS_POLICY_PACKET_QUEUE_CAPACITY; private boolean closed; private final boolean data; private final List<OutputDataStreamDesc> streams = new ArrayList<OutputDataStreamDesc>(); private final RTPTranslatorBuffer[] writeQueue = new RTPTranslatorBuffer[WRITE_QUEUE_CAPACITY]; private int writeQueueHead; private int writeQueueLength; private Thread writeThread; public OutputDataStreamImpl(boolean data) { this.data = data; } public synchronized void addStream( RTPConnectorDesc connectorDesc, OutputDataStream stream) { for (OutputDataStreamDesc streamDesc : streams) if ((streamDesc.connectorDesc == connectorDesc) && (streamDesc.stream == stream)) return; streams.add(new OutputDataStreamDesc(connectorDesc, stream)); } public synchronized void close() { closed = true; writeThread = null; notify(); } private synchronized void createWriteThread() { writeThread = new Thread(this, getClass().getName()); writeThread.setDaemon(true); writeThread.start(); } private synchronized int doWrite( byte[] buffer, int offset, int length, Format format, StreamRTPManagerDesc exclusion) { int write = 0; for (int streamIndex = 0, streamCount = streams.size(); streamIndex < streamCount; streamIndex++) { OutputDataStreamDesc streamDesc = streams.get(streamIndex); StreamRTPManagerDesc streamRTPManagerDesc = streamDesc.connectorDesc.streamRTPManagerDesc; if (streamRTPManagerDesc != exclusion) { if (data) { if ((format != null) && (length > 0)) { Integer payloadType = streamRTPManagerDesc.getPayloadType(format); if ((payloadType == null) && (exclusion != null)) payloadType = exclusion.getPayloadType(format); if (payloadType != null) { int payloadTypeByteIndex = offset + 1; buffer[payloadTypeByteIndex] = (byte) ((buffer[payloadTypeByteIndex] & 0x80) | (payloadType & 0x7f)); } } } else if (logger.isTraceEnabled()) { logRTCP( this, "doWrite", buffer, offset, length); } int streamWrite = streamDesc.stream.write(buffer, offset, length); if (write < streamWrite) write = streamWrite; } } return write; } public synchronized void removeStreams(RTPConnectorDesc connectorDesc) { Iterator<OutputDataStreamDesc> streamIter = streams.iterator(); while (streamIter.hasNext()) { OutputDataStreamDesc streamDesc = streamIter.next(); if (streamDesc.connectorDesc == connectorDesc) streamIter.remove(); } } public void run() { try { while (true) { int writeIndex; byte[] buffer; StreamRTPManagerDesc exclusion; Format format; int length; synchronized (this) { if (closed || !Thread.currentThread().equals(writeThread)) break; if (writeQueueLength < 1) { boolean interrupted = false; try { wait(); } catch (InterruptedException ie) { interrupted = true; } if (interrupted) Thread.currentThread().interrupt(); continue; } writeIndex = writeQueueHead; RTPTranslatorBuffer write = writeQueue[writeIndex]; buffer = write.data; write.data = null; exclusion = write.exclusion; write.exclusion = null; format = write.format; write.format = null; length = write.length; write.length = 0; writeQueueHead++; if (writeQueueHead >= writeQueue.length) writeQueueHead = 0; writeQueueLength } try { doWrite(buffer, 0, length, format, exclusion); } finally { synchronized (this) { RTPTranslatorBuffer write = writeQueue[writeIndex]; if ((write != null) && (write.data == null)) write.data = buffer; } } } } catch (Throwable t) { logger.error("Failed to translate RTP packet", t); if (t instanceof ThreadDeath) throw (ThreadDeath) t; } finally { synchronized (this) { if (Thread.currentThread().equals(writeThread)) writeThread = null; if (!closed && (writeThread == null) && (writeQueueLength > 0)) createWriteThread(); } } } public int write(byte[] buffer, int offset, int length) { return doWrite(buffer, offset, length, null, null); } public synchronized void write( byte[] buffer, int offset, int length, Format format, StreamRTPManagerDesc exclusion) { if (closed) return; int writeIndex; if (writeQueueLength < writeQueue.length) { writeIndex = (writeQueueHead + writeQueueLength) % writeQueue.length; } else { writeIndex = writeQueueHead; writeQueueHead++; if (writeQueueHead >= writeQueue.length) writeQueueHead = 0; writeQueueLength logger.warn("Will not translate RTP packet."); } RTPTranslatorBuffer write = writeQueue[writeIndex]; if (write == null) writeQueue[writeIndex] = write = new RTPTranslatorBuffer(); byte[] data = write.data; if ((data == null) || (data.length < length)) write.data = data = new byte[length]; System.arraycopy(buffer, offset, data, 0, length); write.exclusion = exclusion; write.format = format; write.length = length; writeQueueLength++; if (writeThread == null) createWriteThread(); else notify(); } } private static class PushSourceStreamDesc { public final RTPConnectorDesc connectorDesc; public final boolean data; public final PushSourceStream stream; public PushSourceStreamDesc( RTPConnectorDesc connectorDesc, PushSourceStream stream, boolean data) { this.connectorDesc = connectorDesc; this.stream = stream; this.data = data; } } private class PushSourceStreamImpl implements PushSourceStream, SourceTransferHandler { private final boolean data; private final List<PushSourceStreamDesc> streams = new LinkedList<PushSourceStreamDesc>(); private PushSourceStreamDesc streamToReadFrom; private SourceTransferHandler transferHandler; public PushSourceStreamImpl(boolean data) { this.data = data; } public synchronized void addStream( RTPConnectorDesc connectorDesc, PushSourceStream stream) { for (PushSourceStreamDesc streamDesc : streams) if ((streamDesc.connectorDesc == connectorDesc) && (streamDesc.stream == stream)) return; streams.add( new PushSourceStreamDesc(connectorDesc, stream, this.data)); stream.setTransferHandler(this); } public void close() { // TODO Auto-generated method stub } public boolean endOfStream() { // TODO Auto-generated method stub return false; } public ContentDescriptor getContentDescriptor() { // TODO Auto-generated method stub return null; } public long getContentLength() { return LENGTH_UNKNOWN; } public Object getControl(String controlType) { // TODO Auto-generated method stub return null; } public Object[] getControls() { // TODO Auto-generated method stub return null; } public synchronized int getMinimumTransferSize() { int minimumTransferSize = 0; for (PushSourceStreamDesc streamDesc : streams) { int streamMinimumTransferSize = streamDesc.stream.getMinimumTransferSize(); if (minimumTransferSize < streamMinimumTransferSize) minimumTransferSize = streamMinimumTransferSize; } return minimumTransferSize; } public int read(byte[] buffer, int offset, int length) throws IOException { PushSourceStreamDesc streamDesc; int read; synchronized (this) { streamDesc = streamToReadFrom; read = (streamDesc == null) ? 0 : streamDesc.stream.read(buffer, offset, length); } if (read > 0) { read = RTPTranslatorImpl.this.read( streamDesc, buffer, offset, length, read); } return read; } public synchronized void removeStreams(RTPConnectorDesc connectorDesc) { Iterator<PushSourceStreamDesc> streamIter = streams.iterator(); while (streamIter.hasNext()) { PushSourceStreamDesc streamDesc = streamIter.next(); if (streamDesc.connectorDesc == connectorDesc) { streamDesc.stream.setTransferHandler(null); streamIter.remove(); if (streamToReadFrom == streamDesc) streamToReadFrom = null; } } } public synchronized void setTransferHandler( SourceTransferHandler transferHandler) { if (this.transferHandler != transferHandler) { this.transferHandler = transferHandler; for (PushSourceStreamDesc streamDesc : streams) streamDesc.stream.setTransferHandler(this); } } public synchronized void transferData(PushSourceStream stream) { SourceTransferHandler transferHandler = null; for (PushSourceStreamDesc streamDesc : streams) if (streamDesc.stream == stream) { streamToReadFrom = streamDesc; transferHandler = this.transferHandler; break; } if (transferHandler != null) transferHandler.transferData(this); } } private static class RTPConnectorDesc { public final RTPConnector connector; public final StreamRTPManagerDesc streamRTPManagerDesc; public RTPConnectorDesc( StreamRTPManagerDesc streamRTPManagerDesc, RTPConnector connector) { this.streamRTPManagerDesc = streamRTPManagerDesc; this.connector = connector; } } /** * Implements the <tt>RTPConnector</tt> with which this instance initializes * its <tt>RTPManager</tt>. It delegates to the <tt>RTPConnector</tt> of the * various <tt>StreamRTPManager</tt>s. */ private class RTPConnectorImpl implements RTPConnector { /** * The <tt>RTPConnector</tt>s this instance delegates to. */ private final List<RTPConnectorDesc> connectors = new LinkedList<RTPConnectorDesc>(); private PushSourceStreamImpl controlInputStream; private OutputDataStreamImpl controlOutputStream; private PushSourceStreamImpl dataInputStream; private OutputDataStreamImpl dataOutputStream; public synchronized void addConnector(RTPConnectorDesc connector) { if (!connectors.contains(connector)) { connectors.add(connector); if (this.controlInputStream != null) { PushSourceStream controlInputStream = null; try { controlInputStream = connector.connector.getControlInputStream(); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } if (controlInputStream != null) { this.controlInputStream.addStream( connector, controlInputStream); } } if (this.controlOutputStream != null) { OutputDataStream controlOutputStream = null; try { controlOutputStream = connector.connector.getControlOutputStream(); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } if (controlOutputStream != null) { this.controlOutputStream.addStream( connector, controlOutputStream); } } if (this.dataInputStream != null) { PushSourceStream dataInputStream = null; try { dataInputStream = connector.connector.getDataInputStream(); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } if (dataInputStream != null) { this.dataInputStream.addStream( connector, dataInputStream); } } if (this.dataOutputStream != null) { OutputDataStream dataOutputStream = null; try { dataOutputStream = connector.connector.getDataOutputStream(); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } if (dataOutputStream != null) { this.dataOutputStream.addStream( connector, dataOutputStream); } } } } public synchronized void close() { if (controlInputStream != null) { controlInputStream.close(); controlInputStream = null; } if (controlOutputStream != null) { controlOutputStream.close(); controlOutputStream = null; } if (dataInputStream != null) { dataInputStream.close(); dataInputStream = null; } if (dataOutputStream != null) { dataOutputStream.close(); dataOutputStream = null; } for (RTPConnectorDesc connectorDesc : connectors) connectorDesc.connector.close(); } public synchronized PushSourceStream getControlInputStream() throws IOException { if (this.controlInputStream == null) { this.controlInputStream = new PushSourceStreamImpl(false); for (RTPConnectorDesc connectorDesc : connectors) { PushSourceStream controlInputStream = connectorDesc.connector.getControlInputStream(); if (controlInputStream != null) { this.controlInputStream.addStream( connectorDesc, controlInputStream); } } } return this.controlInputStream; } public synchronized OutputDataStreamImpl getControlOutputStream() throws IOException { if (this.controlOutputStream == null) { this.controlOutputStream = new OutputDataStreamImpl(false); for (RTPConnectorDesc connectorDesc : connectors) { OutputDataStream controlOutputStream = connectorDesc.connector.getControlOutputStream(); if (controlOutputStream != null) { this.controlOutputStream.addStream( connectorDesc, controlOutputStream); } } } return this.controlOutputStream; } public synchronized PushSourceStream getDataInputStream() throws IOException { if (this.dataInputStream == null) { this.dataInputStream = new PushSourceStreamImpl(true); for (RTPConnectorDesc connectorDesc : connectors) { PushSourceStream dataInputStream = connectorDesc.connector.getDataInputStream(); if (dataInputStream != null) { this.dataInputStream.addStream( connectorDesc, dataInputStream); } } } return this.dataInputStream; } public synchronized OutputDataStreamImpl getDataOutputStream() throws IOException { if (this.dataOutputStream == null) { this.dataOutputStream = new OutputDataStreamImpl(true); for (RTPConnectorDesc connectorDesc : connectors) { OutputDataStream dataOutputStream = connectorDesc.connector.getDataOutputStream(); if (dataOutputStream != null) { this.dataOutputStream.addStream( connectorDesc, dataOutputStream); } } } return this.dataOutputStream; } public int getReceiveBufferSize() { return -1; } public double getRTCPBandwidthFraction() { return -1; } public double getRTCPSenderBandwidthFraction() { return -1; } public int getSendBufferSize() { return -1; } public synchronized void removeConnector(RTPConnectorDesc connector) { if (connectors.contains(connector)) { if (controlInputStream != null) controlInputStream.removeStreams(connector); if (controlOutputStream != null) controlOutputStream.removeStreams(connector); if (dataInputStream != null) dataInputStream.removeStreams(connector); if (dataOutputStream != null) dataOutputStream.removeStreams(connector); connectors.remove(connector); } } public void setReceiveBufferSize(int receiveBufferSize) throws IOException { // TODO Auto-generated method stub } public void setSendBufferSize(int sendBufferSize) throws IOException { // TODO Auto-generated method stub } } private static class RTPTranslatorBuffer { public byte[] data; public StreamRTPManagerDesc exclusion; public Format format; public int length; } private class SendStreamDesc { /** * The <tt>DataSource</tt> from which {@link #sendStream} has been * created. */ public final DataSource dataSource; /** * The <tt>SendStream</tt> created from the stream of * {@link #dataSource} at index {@link #streamIndex}. */ public final SendStream sendStream; /** * The list of <tt>StreamRTPManager</tt>-specific views to * {@link #sendStream}. */ private final List<SendStreamImpl> sendStreams = new LinkedList<SendStreamImpl>(); /** * The number of <tt>StreamRTPManager</tt>s which have started their * views of {@link #sendStream}. */ private int started; /** * The index of the stream of {@link #dataSource} from which * {@link #sendStream} has been created. */ public final int streamIndex; public SendStreamDesc( DataSource dataSource, int streamIndex, SendStream sendStream) { this.dataSource = dataSource; this.sendStream = sendStream; this.streamIndex = streamIndex; } void close(SendStreamImpl sendStream) { boolean close = false; synchronized (this) { if (sendStreams.contains(sendStream)) { sendStreams.remove(sendStream); close = sendStreams.isEmpty(); } } if (close) RTPTranslatorImpl.this.closeSendStream(this); } public synchronized SendStreamImpl getSendStream( StreamRTPManager streamRTPManager, boolean create) { for (SendStreamImpl sendStream : sendStreams) if (sendStream.streamRTPManager == streamRTPManager) return sendStream; if (create) { SendStreamImpl sendStream = new SendStreamImpl(streamRTPManager, this); sendStreams.add(sendStream); return sendStream; } else return null; } public synchronized int getSendStreamCount() { return sendStreams.size(); } synchronized void start(SendStreamImpl sendStream) throws IOException { if (sendStreams.contains(sendStream)) { if (started < 1) { this.sendStream.start(); started = 1; } else started++; } } synchronized void stop(SendStreamImpl sendStream) throws IOException { if (sendStreams.contains(sendStream)) { if (started == 1) { this.sendStream.stop(); started = 0; } else if (started > 1) started } } } private static class SendStreamImpl implements SendStream { private boolean closed; public final SendStreamDesc sendStreamDesc; private boolean started; public final StreamRTPManager streamRTPManager; public SendStreamImpl( StreamRTPManager streamRTPManager, SendStreamDesc sendStreamDesc) { this.sendStreamDesc = sendStreamDesc; this.streamRTPManager = streamRTPManager; } public void close() { if (!closed) { try { if (started) stop(); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } finally { sendStreamDesc.close(this); closed = true; } } } public DataSource getDataSource() { return sendStreamDesc.sendStream.getDataSource(); } public Participant getParticipant() { return sendStreamDesc.sendStream.getParticipant(); } public SenderReport getSenderReport() { return sendStreamDesc.sendStream.getSenderReport(); } public TransmissionStats getSourceTransmissionStats() { return sendStreamDesc.sendStream.getSourceTransmissionStats(); } public long getSSRC() { return sendStreamDesc.sendStream.getSSRC(); } public int setBitRate(int bitRate) { // TODO Auto-generated method stub return 0; } public void setSourceDescription(SourceDescription[] sourceDescription) { // TODO Auto-generated method stub } public void start() throws IOException { if (closed) { throw new IOException( "Cannot start SendStream" + " after it has been closed."); } if (!started) { sendStreamDesc.start(this); started = true; } } public void stop() throws IOException { if (!closed && started) { sendStreamDesc.stop(this); started = false; } } } private static class StreamRTPManagerDesc { public RTPConnectorDesc connectorDesc; private final Map<Integer, Format> formats = new HashMap<Integer, Format>(); private long[] receiveSSRCs = EMPTY_LONG_ARRAY; private final List<ReceiveStreamListener> receiveStreamListeners = new LinkedList<ReceiveStreamListener>(); public final StreamRTPManager streamRTPManager; public StreamRTPManagerDesc(StreamRTPManager streamRTPManager) { this.streamRTPManager = streamRTPManager; } public void addFormat(Format format, int payloadType) { synchronized (formats) { formats.put(payloadType, format); } } public synchronized void addReceiveSSRC(long receiveSSRC) { if (!containsReceiveSSRC(receiveSSRC)) { int receiveSSRCCount = receiveSSRCs.length; long[] newReceiveSSRCs = new long[receiveSSRCCount + 1]; System.arraycopy( receiveSSRCs, 0, newReceiveSSRCs, 0, receiveSSRCCount); newReceiveSSRCs[receiveSSRCCount] = receiveSSRC; receiveSSRCs = newReceiveSSRCs; } } public void addReceiveStreamListener(ReceiveStreamListener listener) { synchronized (receiveStreamListeners) { if (!receiveStreamListeners.contains(listener)) receiveStreamListeners.add(listener); } } public Format getFormat(int payloadType) { synchronized (formats) { return formats.get(payloadType); } } public Format[] getFormats() { synchronized (this.formats) { Collection<Format> formats = this.formats.values(); return formats.toArray(new Format[formats.size()]); } } public Integer getPayloadType(Format format) { synchronized (formats) { for (Map.Entry<Integer, Format> entry : formats.entrySet()) { Format entryFormat = entry.getValue(); if (entryFormat.matches(format) || format.matches(entryFormat)) return entry.getKey(); } } return null; } public ReceiveStreamListener[] getReceiveStreamListeners() { synchronized (receiveStreamListeners) { return receiveStreamListeners.toArray( new ReceiveStreamListener[ receiveStreamListeners.size()]); } } public synchronized boolean containsReceiveSSRC(long receiveSSRC) { for (int i = 0; i < receiveSSRCs.length; i++) if (receiveSSRCs[i] == receiveSSRC) return true; return false; } public void removeReceiveStreamListener(ReceiveStreamListener listener) { synchronized (receiveStreamListeners) { receiveStreamListeners.remove(listener); } } } }
package org.myrobotlab.service; import java.io.IOException; import java.text.ParseException; import java.util.Date; import java.util.Enumeration; import java.util.Properties; import java.util.UUID; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Folder; import javax.mail.Header; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.event.MessageCountEvent; import javax.mail.event.MessageCountListener; import javax.mail.internet.InternetAddress; import javax.mail.internet.MailDateFormat; import javax.mail.internet.MimeMultipart; import org.myrobotlab.document.Document; import org.myrobotlab.document.connector.AbstractConnector; import org.myrobotlab.document.transformer.ConnectorConfig; import org.myrobotlab.framework.ServiceType; import com.sun.mail.imap.IMAPFolder; /** * * ImapEmailConnector - This connector can crawl the folders on an IMAP email * server. you can provide the user/pass/email server hostname. It publishes * documents that represents the emails messages that were crawled. * */ public class ImapEmailConnector extends AbstractConnector { private static final long serialVersionUID = 1L; private static final String MESSAGE_ID_HEADER = "message_id"; private String emailServer; private String username; private String password; private String folderName = "INBOX"; private transient String docIdPrefix = "email_"; private transient Store store; public ImapEmailConnector(String name) { super(name); } @Override public void setConfig(ConnectorConfig config) { // TODO Auto-generated method stub log.info("Set Config not yet implemented"); } public void startCrawling() { log.info("Sarting IMAP Email connector."); // connect to the email store Store store = connect(); if (store == null) { log.warn("Email Store was null. Check credentials and server name"); return; } else { log.info("connected to store"); } // Get INBOX folder typically. Folder folder = null; try { folder = store.getFolder(getFolderName()); folder = openFolder(folder); } catch (MessagingException e) { log.warn("Folder {} not found.", folder); e.printStackTrace(); return; } int count = 0; try { count = processFolder(folder); Folder[] folders = folder.list(); // process all sub folders. // TODO: check the recursion here and do it properly. for (Folder f : folders) { f = openFolder(f); count = count + processFolder(f); } } catch (MessagingException e) { log.warn("Message Exception processing subfolders : {}", e.getLocalizedMessage()); e.printStackTrace(); } disconnect(); log.info("Fetched " + count + " messages"); } public void startListeningForEmail() throws MessagingException { // TODO: Implement me and have a publishEmail method. Store store = connect(); IMAPFolder inbox = (IMAPFolder) store.getFolder("inbox"); inbox.open(Folder.READ_ONLY); inbox.addMessageCountListener(new MessageCountListener() { @Override public void messagesRemoved(MessageCountEvent event) { } @Override public void messagesAdded(MessageCountEvent event) { Message[] messages = event.getMessages(); for (Message message : messages) { try { // System.out.println("Mail Subject:- " + message.getSubject()); invoke("publishEmail", message); } catch (MessagingException e) { e.printStackTrace(); } } } }); // a thread to keep our inbox idle open i guess? a a heartbeat perhaps? new Thread(new Runnable() { private static final long KEEP_ALIVE_FREQ = 10000; @Override public void run() { while (!Thread.interrupted()) { try { inbox.idle(); Thread.sleep(KEEP_ALIVE_FREQ); } catch (InterruptedException e) { } catch (MessagingException e) { } } } }).start(); } public Message publishEmail(Message m) { return m; } private Folder openFolder(Folder folder) { try { // Read only! lets not accidentally blow away someones email. folder.open(Folder.READ_ONLY); } catch (MessagingException e) { log.info("Message Exception {}", e.getLocalizedMessage()); e.printStackTrace(); return null; } return folder; } private int processFolder(Folder folder) { log.info("Processing folder {}", folder.getName()); int numDocs = 0; try { numDocs = folder.getMessageCount(); log.info("Folder has {} docs.", numDocs); } catch (MessagingException e) { log.warn("Messaging Exception {}", e.getLocalizedMessage()); e.printStackTrace(); // TODO: bomb out here? return 0; } try { for (Message m : folder.getMessages()) { try { Document doc = processMessage(m); doc.setField("folder", folder.getName()); feed(doc); numDocs++; } catch (MessagingException | IOException e) { log.warn("process message failed. continuing to next message. {} ", e.getLocalizedMessage()); e.printStackTrace(); continue; } } } catch (MessagingException e) { // TODO Auto-generated catch block log.info("Messaging Exception getMessages {}", e.getLocalizedMessage()); e.printStackTrace(); return 0; } return numDocs; }; private Document processMessage(Message m) throws MessagingException, IOException { // create a unique(ish) doc id until we discover the true message id. String docId = docIdPrefix + UUID.randomUUID().toString(); Document doc = new Document(docId); Enumeration<Header> headers = m.getAllHeaders(); // walk every header and copy them to fields... String messageId = null; while (headers.hasMoreElements()) { Header header = headers.nextElement(); String fieldName = cleanFieldName(header.getName()); if (fieldName.equals(MESSAGE_ID_HEADER)) { // if we get a message id. use it. messageId = header.getValue(); docId = docIdPrefix + messageId; doc.setId(docId); } doc.addToField(fieldName, header.getValue()); } // TODO: grab the body of the email // TODO: grab the attachments. // specific stuff we really care about.. // We want to map all the From / To / CC / BCCs // the "from" field should be handled in the "addHeadersToItem" method. // Specially handle the TO field as this is multivalued. // not sure which other fields we care about this for. // TODO: this might be much faster to call this directly.. just need to // pass it // the header that we already copied to the to / bcc /cc fields of the // mime message. // InternetAddress.parseHeader(toHeader, this.strict) // Address[] recipients = m.getAllRecipients(); // TODO: i don't like calling toString here. if (doc.hasField("to")) { // if the to field was found, we are going to override it here. Address[] recipients = InternetAddress.parse(doc.getField("to").toString()); if (recipients != null) { doc.removeField("to"); for (Address a : recipients) { doc.addToField("to", a.toString()); } } else { // this shouldn't happen, right? doc.setField("to", "unknown"); } } else { // this shouldn't happen? doc.setField("to", "unknown"); } // TODO: what to use with the sent date? // Date d = m.getSentDate(); Date sentdate = null; // TODO: make it so we don't call tostring here. // TODO: array out of bounds checking... if (!doc.hasField("date")) { sentdate = m.getSentDate(); doc.setField("sent_date", sentdate); } else { MailDateFormat mailDateFormat = new MailDateFormat(); try { // parse the string version of the field and make it a proper // java date object sentdate = mailDateFormat.parse(doc.getField("date").get(0).toString()); doc.setField("sent_date", sentdate); } catch (ParseException e) { log.warn("Date Parse Exception {}", e.getLocalizedMessage()); e.printStackTrace(); } } Date receivedDate = m.getReceivedDate(); if (receivedDate != null) { doc.setField("received_date", receivedDate); } Address[] replyTo = m.getReplyTo(); if (replyTo != null) { for (Address replyAddr : replyTo) { doc.addToField("reply_to", replyAddr.toString()); } } String subject = m.getSubject(); if (subject != null) { doc.setField("subject", subject); } else { log.debug("No subject"); } // the body of the email here Object content = m.getContent(); if (content instanceof String) { // This is already a string! ok... doc.addToField("text", (String) (content)); } else if (content instanceof MimeMultipart) { // multi-part mime docs are a pain. we'll just accumulate the // text from each part. int numParts = ((MimeMultipart) content).getCount(); // Walk all parts of the mime message. for (int i = 0; i < numParts; i++) { BodyPart bp = ((MimeMultipart) content).getBodyPart(i); // add the various metadata fields to the document for this body // part. try { parseBodyPart(bp, doc); } catch (Exception e) { log.warn("Exception in parse body part for message {}", e.getLocalizedMessage()); e.printStackTrace(); continue; } } } else { log.info("Unknown Type of content returned : " + content.getClass()); doc.addToField("text", content.toString()); } doc.setField("size", m.getSize()); return doc; } public void parseBodyPart(Part p, Document doc) throws Exception { // switch on ismimetype for processing. (avoid fetching if we don't need // attachments can be large. if (p.isMimeType("text/plain")) { String body = (String) p.getContent(); doc.addToField("text", body); return; } else if (p.isMimeType("multipart/alternative")) { MimeMultipart mmp = (MimeMultipart) p.getContent(); for (int i = 0; i < mmp.getCount(); i++) { // TODO: check this recursion! nested body parts! parseBodyPart(mmp.getBodyPart(i), doc); } return; } else if (p.isMimeType("text/html")) { String body = (String) p.getContent(); // TODO: have the pipeline parse the html doc.addToField("html", body); return; } else if (p.isMimeType("application/ics")) { log.info("Skipping Calender entry: not supported yet."); Object icsEntry = p.getContent(); // TODO: add this to the doc doc.addToField("ics", icsEntry.toString()); return; } else { log.info("Unhandled Content Type {}", p.getContentType()); return; } } private String cleanFieldName(String name) { // TODO : centralize this as a util or something. (maybe move it to the // pipeline) String clean = name.trim().toLowerCase().replaceAll(" ", "_"); return clean; } @Override public void stopCrawling() { // TODO Auto-generated method stub // TODO: this isn't implemented yet.. I'd like to move this sort of // stuff to the base class. } public void disconnect() { try { store.close(); } catch (MessagingException e) { log.warn("error closing store ... " + e.getMessage()); e.printStackTrace(); } } public Store connect() { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = null; try { store = session.getStore("imaps"); } catch (NoSuchProviderException e) { log.warn("No IMAPS support. {}", e.getLocalizedMessage()); e.printStackTrace(); } try { store.connect(getEmailServer(), getUsername(), getPassword()); } catch (MessagingException e) { // TODO Auto-generated catch block log.warn(e.getMessage()); e.printStackTrace(); return null; } return store; } public String getEmailServer() { return emailServer; } public void setEmailServer(String emailServer) { this.emailServer = emailServer; } 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; } public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public String getDocIdPrefix() { return docIdPrefix; } public void setDocIdPrefix(String docIdPrefix) { this.docIdPrefix = docIdPrefix; } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(ImapEmailConnector.class.getCanonicalName()); meta.addDescription("This connector will connect to an IMAP based email server and crawl the emails"); meta.addCategory("data", "ingest"); meta.addDependency("com.sun.mail", "1.4.5"); return meta; } public static void main(String[] args) throws Exception { ImapEmailConnector connector = (ImapEmailConnector) Runtime.start("email", "ImapEmailConnector"); connector.setEmailServer("imap.gmail.com"); connector.setUsername("XX"); connector.setPassword("YY"); connector.setBatchSize(1); //Solr solr = (Solr) Runtime.start("solr", "Solr"); // for example... //solr.setSolrUrl(solrUrl); //connector.addDocumentListener(solr); //connector.startCrawling(); connector.startListeningForEmail(); } }
package org.ohmage.request.image; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.cache.UserBin; import org.ohmage.exception.ServiceException; import org.ohmage.exception.ValidationException; import org.ohmage.request.InputKeys; import org.ohmage.request.UserRequest; import org.ohmage.service.ImageServices; import org.ohmage.service.UserImageServices; import org.ohmage.service.UserServices; import org.ohmage.util.CookieUtils; import org.ohmage.validator.ImageValidators; import org.ohmage.validator.ImageValidators.ImageSize; /** * <p>Returns an image based on the given ID. The requester must be requesting * an image they created, a shared image in a campaign in which they are an * author, or a shared image in a shared campaign in which they are an analyst. * </p> * <table border="1"> * <tr> * <td>Parameter Name</td> * <td>Description</td> * <td>Required</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#CLIENT}</td> * <td>A string describing the client that is making this request.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#IMAGE_ID}</td> * <td>The image's unique identifier.</td> * <td>true</td> * </tr> * <tr> * <td>{@value org.ohmage.request.InputKeys#IMAGE_SIZE}</td> * <td>If omitted, the originally uploaded image will be returned. If * given, it will alter the image in some way based on the value given. * It must be one of * {@link org.ohmage.validator.ImageValidators.ImageSize}.</td> * <td>false</td> * </tr> * </table> * * @author John Jenkins */ public class ImageReadRequest extends UserRequest { private static final Logger LOGGER = Logger.getLogger(ImageReadRequest.class); private static final int CHUNK_SIZE = 4096; private static final long MILLIS_IN_A_SECOND = 1000; private final UUID imageId; private final ImageSize size; private InputStream imageStream; private long imageSize; /** * Creates a new image read request. * * @param httpRequest The HttpServletRequest with all of the parameters to * build this request. */ public ImageReadRequest(HttpServletRequest httpRequest) { super(httpRequest, TokenLocation.EITHER, false); LOGGER.info("Creating an image read request."); UUID tImageId = null; ImageSize tSize = null; if(! isFailed()) { try { tImageId = ImageValidators.validateId(httpRequest.getParameter(InputKeys.IMAGE_ID)); if(tImageId == null) { setFailed(ErrorCode.IMAGE_INVALID_ID, "The image ID is missing: " + InputKeys.IMAGE_ID); throw new ValidationException("The image ID is missing: " + InputKeys.IMAGE_ID); } else if(httpRequest.getParameterValues(InputKeys.IMAGE_ID).length > 1) { setFailed(ErrorCode.IMAGE_INVALID_ID, "Multiple owner values were given: " + InputKeys.IMAGE_ID); throw new ValidationException("Multiple owner values were given: " + InputKeys.IMAGE_ID); } tSize = ImageValidators.validateImageSize(httpRequest.getParameter(InputKeys.IMAGE_SIZE)); if((tSize != null) && (httpRequest.getParameterValues(InputKeys.IMAGE_SIZE).length > 1)) { setFailed(ErrorCode.IMAGE_INVALID_SIZE, "Multiple image sizes were given: " + InputKeys.IMAGE_SIZE); throw new ValidationException("Multiple image sizes were given: " + InputKeys.IMAGE_SIZE); } } catch(ValidationException e) { e.failRequest(this); LOGGER.info(e.toString()); } } imageId = tImageId; size = tSize; imageStream = null; } /** * Services the request. */ @Override public void service() { LOGGER.info("Servicing image read request."); if(! authenticate(AllowNewAccount.NEW_ACCOUNT_DISALLOWED)) { return; } try { LOGGER.info("Verifying that the image exists."); ImageServices.instance().verifyImageExistance(imageId, true); try { LOGGER.info("Checking if the user is an admin."); UserServices.instance().verifyUserIsAdmin(getUser().getUsername()); } catch(ServiceException e) { LOGGER.info("Verifying that the user can read the image."); UserImageServices.instance().verifyUserCanReadImage(getUser().getUsername(), imageId); } LOGGER.info("Retrieving the image."); imageStream = ImageServices.instance().getImage(imageId, size); try { LOGGER.info("Retrieving the image's size."); URL imageUrl = ImageServices.instance().getImageUrl(imageId); if(ImageSize.SMALL.equals(size)) { try { imageUrl = new URL(imageUrl.toString() + "-s"); } catch (MalformedURLException e) { throw new ServiceException( "The image's URL is corrupt."); } } imageSize =(new File(imageUrl.toURI())).length(); } catch(URISyntaxException e) { throw new ServiceException(e); } } catch(ServiceException e) { e.failRequest(this); e.logException(LOGGER); } } /** * Responds to the request with an image if it was successful or JSON if it * was not. */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Writing image read response."); // Creates the writer that will write the response, success or fail. OutputStream os; try { os = httpResponse.getOutputStream(); } catch(IOException e) { LOGGER.error("Unable to create writer object. Aborting.", e); return; } // Sets the HTTP headers to disable caching expireResponse(httpResponse); // If the request hasn't failed, attempt to write the file to the // output stream. if(! isFailed()) { try { // Set the type as a JPEG. // FIXME: This isn't necessarily the case. We might want to do // some sort of image inspection to figure out what this should httpResponse.setContentType("image/png"); httpResponse.setHeader("Content-Disposition", "filename=image"); httpResponse.setHeader("Content-Length", String.valueOf(imageSize)); // If available, set the token. if(getUser() != null) { final String token = getUser().getToken(); if(token != null) { CookieUtils.setCookieValue( httpResponse, InputKeys.AUTH_TOKEN, token, (int) (UserBin.getTokenRemainingLifetimeInMillis(token) / MILLIS_IN_A_SECOND)); } } // Set the output stream to the response. DataOutputStream dos = new DataOutputStream(os); // Read the file in chunks and write it to the output stream. byte[] bytes = new byte[CHUNK_SIZE]; int currRead; while((currRead = imageStream.read(bytes)) != -1) { dos.write(bytes, 0, currRead); } // Close the image's InputStream. imageStream.close(); // Flush and close the data output stream to which we were // writing. dos.flush(); dos.close(); // Flush and close the output stream that was used to generate // the data output stream. os.flush(); os.close(); } // If the error occurred while reading from the input stream or // writing to the output stream, abort the whole operation and // return an error. catch(IOException e) { LOGGER.error("The contents of the file could not be read or written to the response.", e); setFailed(); } } // If the request ever failed, write an error message. // FIXME: This should probably check if it's a GET and send a 404. if(isFailed()) { httpResponse.setContentType("text/html"); Writer writer = new BufferedWriter(new OutputStreamWriter(os)); // Write the error response. try { writer.write(getFailureMessage()); } catch(IOException e) { LOGGER.error("Unable to write failed response message. Aborting.", e); } // Flush it and close. try { writer.flush(); writer.close(); } catch(IOException e) { LOGGER.warn("Unable to flush or close the writer.", e); } } } }
package org.opencms.main; import org.opencms.util.CmsStringUtil; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.net.URLConnection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; /** * Handles the requests for static resources located in the classpath.<p> */ public class CmsStaticResourceHandler implements I_CmsRequestHandler { /** The handler name. */ public static final String HANDLER_NAME = "Static"; /** The static resource prefix '/handleStatic'. */ public static final String STATIC_RESOURCE_PREFIX = OpenCmsServlet.HANDLE_PATH + HANDLER_NAME; /** The default output buffer size. */ private static final int DEFAULT_BUFFER_SIZE = 32 * 1024; /** Default cache lifetime in seconds. */ private static final int DEFAULT_CACHE_TIME = 3600; /** The handler names. */ private static final String[] HANDLER_NAMES = new String[] {HANDLER_NAME}; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsStaticResourceHandler.class); /** The regular expression to remove the static resource path prefix. */ private static String m_removePrefixRegex; /** The regular expression to identify static resource paths. */ private static String m_staticResourceRegex; /** The opencms path prefix for static resources. */ private static final String OPENCMS_PATH_PREFIX = "OPENCMS/"; /** * Returns the context for static resources served from the class path, e.g. "/opencms/handleStatic/v5976v".<p> * * @param opencmsContext the OpenCms context * @param opencmsVersion the OpenCms version * * @return the static resource context */ public static String getStaticResourceContext(String opencmsContext, String opencmsVersion) { return opencmsContext + STATIC_RESOURCE_PREFIX + "/v" + opencmsVersion.hashCode() + "v"; } /** * Returns the URL to a static resource.<p> * * @param resourcePath the static resource path * * @return the resource URL */ public static URL getStaticResourceURL(String resourcePath) { URL resourceURL = null; if (isStaticResourceUri(resourcePath)) { String path = removeStaticResourcePrefix(resourcePath); path = CmsStringUtil.joinPaths(OPENCMS_PATH_PREFIX, path); resourceURL = OpenCms.getSystemInfo().getClass().getClassLoader().getResource(path); } return resourceURL; } /** * Returns if the given URI points to a static resource.<p> * * @param path the path to test * * @return <code>true</code> in case the given URI points to a static resource */ public static boolean isStaticResourceUri(String path) { return (path != null) && path.matches(getStaticResourceRegex()); } /** * Returns if the given URI points to a static resource.<p> * * @param uri the URI to test * * @return <code>true</code> in case the given URI points to a static resource */ public static boolean isStaticResourceUri(URI uri) { return (uri != null) && isStaticResourceUri(uri.getPath()); } /** * Removes the static resource path prefix.<p> * * @param path the path * * @return the modified path */ public static String removeStaticResourcePrefix(String path) { return path.replaceFirst(getRemovePrefixRegex(), ""); } /** * Returns the regular expression to remove the static resource path prefix.<p> * * @return the regular expression to remove the static resource path prefix */ private static String getRemovePrefixRegex() { if (m_removePrefixRegex == null) { m_removePrefixRegex = "^(" + OpenCms.getSystemInfo().getOpenCmsContext() + ")?" + STATIC_RESOURCE_PREFIX + "(/v-?\\d+v/)?"; } return m_removePrefixRegex; } /** * Returns the regular expression to identify static resource paths.<p> * * @return the regular expression to identify static resource paths */ private static String getStaticResourceRegex() { if (m_staticResourceRegex == null) { m_staticResourceRegex = getRemovePrefixRegex() + ".*"; } return m_staticResourceRegex; } /** * @see org.opencms.main.I_CmsRequestHandler#getHandlerNames() */ public String[] getHandlerNames() { return HANDLER_NAMES; } /** * @see org.opencms.main.I_CmsRequestHandler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String) */ public void handle(HttpServletRequest request, HttpServletResponse response, String name) throws IOException { String path = OpenCmsCore.getInstance().getPathInfo(request); URL resourceURL = getStaticResourceURL(path); if (resourceURL != null) { setResponseHeaders(request, response, path, resourceURL); writeStaticResourceResponse(request, response, resourceURL); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } /** * Returns whether this servlet should attempt to serve a precompressed * version of the given static resource. If this method returns true, the * suffix {@code .gz} is appended to the URL and the corresponding resource * is served if it exists. It is assumed that the compression method used is * gzip. If this method returns false or a compressed version is not found, * the original URL is used.<p> * * The base implementation of this method returns true if and only if the * request indicates that the client accepts gzip compressed responses and * the filename extension of the requested resource is .js, .css, or .html.<p> * * @param request the request for the resource * @param url the URL of the requested resource * * @return true if the servlet should attempt to serve a precompressed version of the resource, false otherwise */ protected boolean allowServePrecompressedResource(HttpServletRequest request, String url) { String accept = request.getHeader("Accept-Encoding"); return (accept != null) && accept.contains("gzip") && (url.endsWith(".js") || url.endsWith(".css") || url.endsWith(".html")); } /** * Calculates the cache lifetime for the given filename in seconds. By * default filenames containing ".nocache." return 0, filenames containing * ".cache." return one year, all other return the value defined in the * web.xml using resourceCacheTime (defaults to 1 hour).<p> * * @param filename the file name * * @return cache lifetime for the given filename in seconds */ protected int getCacheTime(String filename) { if (filename.contains(".nocache.")) { return 0; } if (filename.contains(".cache.")) { return 60 * 60 * 24 * 365; } /* * For all other files, the browser is allowed to cache for 1 hour * without checking if the file has changed. This forces browsers to * fetch a new version when the Vaadin version is updated. This will * cause more requests to the servlet than without this but for high * volume sites the static files should never be served through the * servlet. */ return DEFAULT_CACHE_TIME; } /** * Sets the response headers.<p> * * @param request the request * @param response the response * @param filename the file name * @param resourceURL the resource URL */ protected void setResponseHeaders( HttpServletRequest request, HttpServletResponse response, String filename, URL resourceURL) { String cacheControl = "public, max-age=0, must-revalidate"; int resourceCacheTime = getCacheTime(filename); if (resourceCacheTime > 0) { cacheControl = "max-age=" + String.valueOf(resourceCacheTime); } response.setHeader("Cache-Control", cacheControl); response.setDateHeader("Expires", System.currentTimeMillis() + (resourceCacheTime * 1000)); // Find the modification timestamp long lastModifiedTime = 0; URLConnection connection = null; try { connection = resourceURL.openConnection(); lastModifiedTime = connection.getLastModified(); // Remove milliseconds to avoid comparison problems (milliseconds // are not returned by the browser in the "If-Modified-Since" // header). lastModifiedTime = lastModifiedTime - (lastModifiedTime % 1000); response.setDateHeader("Last-Modified", lastModifiedTime); if (browserHasNewestVersion(request, lastModifiedTime)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } catch (Exception e) { // Failed to find out last modified timestamp. Continue without it. LOG.debug("Failed to find out last modified timestamp. Continuing without it.", e); } finally { try { if (connection != null) { // Explicitly close the input stream to prevent it // from remaining hanging InputStream is = connection.getInputStream(); if (is != null) { is.close(); } } } catch (Exception e) { LOG.info("Error closing URLConnection input stream", e); } } // Set type mime type if we can determine it based on the filename String mimetype = OpenCms.getResourceManager().getMimeType(filename, "UTF-8"); if (mimetype != null) { response.setContentType(mimetype); } } /** * Writes the contents of the given resourceUrl in the response. Can be * overridden to add/modify response headers and similar.<p> * * @param request the request for the resource * @param response the response * @param resourceUrl the url to send * * @throws IOException in case writing the response fails */ protected void writeStaticResourceResponse( HttpServletRequest request, HttpServletResponse response, URL resourceUrl) throws IOException { URLConnection connection = null; InputStream is = null; String urlStr = resourceUrl.toExternalForm(); try { if (allowServePrecompressedResource(request, urlStr)) { // try to serve a precompressed version if available try { connection = new URL(urlStr + ".gz").openConnection(); is = connection.getInputStream(); // set gzip headers response.setHeader("Content-Encoding", "gzip"); } catch (Exception e) { LOG.debug("Unexpected exception looking for gzipped version of resource " + urlStr, e); } } if (is == null) { // precompressed resource not available, get non compressed connection = resourceUrl.openConnection(); try { is = connection.getInputStream(); } catch (FileNotFoundException e) { LOG.debug(e.getMessage(), e); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } try { @SuppressWarnings("null") int length = connection.getContentLength(); if (length >= 0) { response.setContentLength(length); } } catch (Throwable e) { LOG.debug(e.getMessage(), e); // This can be ignored, content length header is not required. // Need to close the input stream because of // prevent it from hanging, but that is done below. } streamContent(response, is); } finally { if (is != null) { is.close(); } } } /** * Checks if the browser has an up to date cached version of requested * resource. Currently the check is performed using the "If-Modified-Since" * header. Could be expanded if needed.<p> * * @param request the HttpServletRequest from the browser * @param resourceLastModifiedTimestamp the timestamp when the resource was last modified. 0 if the last modification time is unknown * * @return true if the If-Modified-Since header tells the cached version in the browser is up to date, false otherwise */ private boolean browserHasNewestVersion(HttpServletRequest request, long resourceLastModifiedTimestamp) { if (resourceLastModifiedTimestamp < 1) { // We do not know when it was modified so the browser cannot have an // up-to-date version return false; } /* * The browser can request the resource conditionally using an * If-Modified-Since header. Check this against the last modification * time. */ try { // If-Modified-Since represents the timestamp of the version cached // in the browser long headerIfModifiedSince = request.getDateHeader("If-Modified-Since"); if (headerIfModifiedSince >= resourceLastModifiedTimestamp) { // Browser has this an up-to-date version of the resource return true; } } catch (Exception e) { // Failed to parse header. Fail silently - the browser does not have // an up-to-date version in its cache. } return false; } /** * Streams the input stream to the response.<p> * * @param response the response * @param is the input stream * * @throws IOException in case writing to the response fails */ private void streamContent(HttpServletResponse response, InputStream is) throws IOException { OutputStream os = response.getOutputStream(); try { byte buffer[] = new byte[DEFAULT_BUFFER_SIZE]; int bytes; while ((bytes = is.read(buffer)) >= 0) { os.write(buffer, 0, bytes); } } finally { os.close(); } } }
package org.xdi.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @see org.apache.commons.lang.StringUtils */ public final class StringHelper { private static final Pattern MULTI_SPACE_PATTERN = Pattern.compile("\\s+"); private static final Pattern QUOTE_PATTERN = Pattern.compile("\\\""); private static final String charset = "!0123456789abcdefghijklmnopqrstuvwxyz"; private static Random rand; private StringHelper() { } public static String getRandomString(int length) { if (rand == null) { rand = new Random(System.currentTimeMillis()); } StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int pos = rand.nextInt(charset.length()); sb.append(charset.charAt(pos)); } return sb.toString(); } public static String[] add(String[] x, String sep, String[] y) { String[] result = new String[x.length]; for (int i = 0; i < x.length; i++) { result[i] = x[i] + sep + y[i]; } return result; } public static String repeat(String string, int times) { StringBuffer buf = new StringBuffer(string.length() * times); for (int i = 0; i < times; i++) buf.append(string); return buf.toString(); } public static String repeat(char character, int times) { char[] buffer = new char[times]; Arrays.fill(buffer, character); return new String(buffer); } public static String[] split(String str, String delim) { return split(str, delim, true, false); } public static String[] split(String str, String delim, boolean trim, boolean include) { StringTokenizer tokens = new StringTokenizer(str, delim, include); String[] result = new String[tokens.countTokens()]; int i = 0; while (tokens.hasMoreTokens()) { String token = tokens.nextToken(); if (trim) { token = token.trim(); } result[i++] = token; } return result; } public static String unqualify(String qualifiedName) { int loc = qualifiedName.lastIndexOf("."); return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1); } public static String qualifier(String qualifiedName) { int loc = qualifiedName.lastIndexOf("."); return (loc < 0) ? "" : qualifiedName.substring(0, loc); } public static String suffix(String name, String suffix) { return (suffix == null) ? name : name + suffix; } public static boolean booleanValue(String tfString) { String trimmed = tfString.trim().toLowerCase(); return trimmed.equals("true") || trimmed.equals("t"); } public static String toString(Object[] array) { int len = array.length; if (len == 0) return ""; StringBuffer buf = new StringBuffer(len * 12); for (int i = 0; i < len - 1; i++) { buf.append(array[i]).append(", "); } return buf.append(array[len - 1]).toString(); } public static boolean isNotEmpty(String str) { return !StringHelper.isEmpty(str); } public static boolean isEmpty(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i)) == false) { return false; } } return true; } public static String truncate(String string, int length) { if (string.length() <= length) { return string; } else { return string.substring(0, length); } } public static String toUpperCase(String str) { return str == null ? null : str.toUpperCase(); } public static String toLowerCase(String str) { return str == null ? null : str.toLowerCase(); } public static String moveAndToBeginning(String filter) { if (filter.trim().length() > 0) { filter += " and "; if (filter.startsWith(" and ")) filter = filter.substring(4); } return filter; } public static String removePunctuation(String punctuatedString) { return punctuatedString == null ? null : punctuatedString.replaceAll("[\\.@!,:/]", ""); } public static String formatZeroLeadingLong(long n, int digits) { /* * we create a format : %% : % the first % is to escape the second % 0 : * 0 zero character %d : how many '0' we want (specified by digits) d : * d the number to format */ String format = String.format("%%0%dd", digits); return String.format(format, n); } public static boolean compare(String str1, String str2) { if (str1 == null) { if (str2 != null) { return false; } } else { return str1.equals(str2); } return true; } public static boolean equalsIgnoreCase(String str1, String str2) { if (str1 == null) { if (str2 != null) { return false; } } else if (!str1.equalsIgnoreCase(str2)) { return false; } return true; } public static boolean equals(String str1, String str2) { if (str1 == null) { if (str2 != null) { return false; } } else if (!str1.equals(str2)) { return false; } return true; } public static String encodeString(String str) { if ((str == null) || (str.length() == 0)) { return str; } try { return (new URI(null, str, null)).toString(); } catch (URISyntaxException ex) { return null; } } public static String getEmtpyStringIfNull(String str) { return (str == null) ? "" : str; } public static String getNullIfEmtpyString(String str) { return (str == null) || (str.trim().length() == 0) ? null : str; } public static String getValueFromDelimitedString(String delimitedString, int attrIndex) { if (isEmpty(delimitedString)) { return ""; } String[] parts = delimitedString.split("\\|"); if (attrIndex < parts.length) { String[] paramPararts = parts[attrIndex].split("\\:"); if (paramPararts.length == 2) { return paramPararts[1].trim(); } } return ""; } public static Map<String, String> getValueMapForDelimitedString(String delimitedString) { Map<String, String> result = new HashMap<String, String>(); if (isEmpty(delimitedString)) { return result; } String[] parts = delimitedString.split("\\|"); for (String part : parts) { String[] paramPararts = part.split("\\:"); if (paramPararts.length == 2) { result.put(paramPararts[0].trim().toLowerCase(), paramPararts[1].trim()); } } return result; } public static String[] getValuesFromColonDelimitedString(String delimitedString) { if (isEmpty(delimitedString)) { return new String[0]; } String[] result = delimitedString.split("\\:"); for (int i = 0; i < result.length; i++) { if (StringHelper.isNotEmpty(result[i])) { result[i] = result[i].trim(); } } return result; } public static String buildDelimitedString(String[] attributes, String... values) { if ((attributes == null) || (values == null) || (attributes.length != values.length)) { return null; } StringBuilder result = new StringBuilder(); for (int i = 0; i < attributes.length; i++) { String value = getEmtpyStringIfNull(values[i]); result.append(attributes[i]).append(": ").append(value); if (i < attributes.length - 1) { if (value.length() > 0) { result.append(" "); } result.append("| "); } } return result.toString(); } public static String buildColonDelimitedString(String... values) { return buildDelimitedString(" : ", values); } public static String buildDelimitedString(String delimiter, String... values) { if (values == null) { return null; } StringBuilder result = new StringBuilder(); for (int i = 0; i < values.length; i++) { result.append(getEmtpyStringIfNull(values[i])); if (i < values.length - 1) { result.append(delimiter); } } return result.toString(); } public static float toFloat(String string) { if (isEmpty(string)) { return 0.0f; } try { return Float.parseFloat(string); } catch (NumberFormatException ex) { return 0.0f; } } public static int toInteger(String string) { if (isEmpty(string)) { return 0; } try { return Integer.parseInt(string); } catch (NumberFormatException ex) { return 0; } } public static int toInteger(String string, int defaultValue) { if (isEmpty(string)) { return defaultValue; } try { return Integer.parseInt(string); } catch (NumberFormatException ex) { return defaultValue; } } public static Integer toInteger(String string, Integer defaultValue) { if (isEmpty(string)) { return defaultValue; } try { return Integer.parseInt(string); } catch (NumberFormatException ex) { return defaultValue; } } public static int toInt(String string, int defaultValue) { if (isEmpty(string)) { return defaultValue; } try { return Integer.parseInt(string); } catch (NumberFormatException ex) { return defaultValue; } } public static boolean toBoolean(Boolean value, boolean defaultValue) { return value != null ? value : defaultValue; } public static boolean toBoolean(String string, boolean defaultValue) { if (isEmpty(string)) { return defaultValue; } try { return Boolean.parseBoolean(string); } catch (NumberFormatException ex) { return defaultValue; } } public static String getFirstPositiveNumber(String string) { if (isEmpty(string)) { return ""; } String[] numbers = string.split("([^\\d]+)"); if (numbers.length > 0) { return numbers[0]; } return ""; } public static String removeMultipleSpaces(String string) { if (isEmpty(string)) { return string; } Matcher matcher = MULTI_SPACE_PATTERN.matcher(string); if (matcher.find()) { return matcher.replaceAll(" "); } return string; } // Deprecated. Use IOUtils.toString(input) @Deprecated public static String convertStreamToString(InputStream is) throws IOException { /* * To convert the InputStream to String we use the Reader.read(char[] * buffer) method. We iterate until the Reader return -1 which means * there's no more data to read. We use the StringWriter class to * produce the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } } public static String replaceLast(String string, String toReplace, String replacement) { int pos = string.lastIndexOf(toReplace); if (pos > -1) { return string.substring(0, pos) + replacement + string.substring(pos + toReplace.length(), string.length()); } else { return string; } } public static String doubleQuotes(String string) { if (isEmpty(string)) { return string; } Matcher matcher = QUOTE_PATTERN.matcher(string); if (matcher.find()) { return matcher.replaceAll("\"\""); } return string; } public static String addQuote(String string) { if (isEmpty(string)) { return ""; } return "\"" + string + "\""; } public static boolean isEmptyString(Object string) { return !(string instanceof String) || isEmpty((String) string); } public static boolean isNotEmptyString(Object string) { return !(string instanceof String) || isNotEmpty((String) string); } public static String toString(Object object) { return (object == null) ? null : object.toString(); } public static String qualify(String prefix, String name) { if (name == null || prefix == null) { throw new NullPointerException(); } return new StringBuffer(prefix.length() + name.length() + 1).append(prefix).append('.').append(name).toString(); } public static String trimAll(String string) { if (isEmpty(string)) { return string; } return string.trim(); } }
package requester_responder.responder; import java.util.Random; import jade.core.behaviours.OneShotBehaviour; import jade.lang.acl.ACLMessage; public class Decision extends OneShotBehaviour { private final Random randomizer = new Random(); @Override public void action() { ActivityResponder parent = (ActivityResponder) getParent(); ACLMessage request = (ACLMessage) getDataStore().get(parent.REQUEST_KEY); int decision = randomizer.nextInt(100); ACLMessage response = request.createReply(); if (decision > 50) { response.setPerformative(ACLMessage.AGREE); response.setContent("now"); } else { response.setPerformative(ACLMessage.REFUSE); response.setContent("busy doing another job"); } getDataStore().put(parent.RESPONSE_KEY, response); } private static final long serialVersionUID = 8554746504981566315L; }
package Subsystem.Swerve; import MathObject.O_Vector; import MathObject.O_Point; import Robot.OI; import Robot.RobotMap; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * @author 1218 */ public class SS_Swerve extends Subsystem { O_SwerveModule[] modules = new O_SwerveModule[4]; public SS_Swerve() { modules[0] = new O_SwerveModule(new O_Point(1,1), RobotMap.SM0_CIM, RobotMap.SM0_CIMile, RobotMap.SM0_banebot, RobotMap.SM0_EncoderA, RobotMap.SM0_EncoderB, RobotMap.SM0_Zero, -145, false); modules[1] = new O_SwerveModule(new O_Point(-1,1), RobotMap.SM1_CIM, RobotMap.SM1_CIMile, RobotMap.SM1_banebot, RobotMap.SM1_EncoderA, RobotMap.SM1_EncoderB, RobotMap.SM1_Zero, 0, false); modules[2] = new O_SwerveModule(new O_Point(-1,-1), RobotMap.SM2_CIM, RobotMap.SM2_CIMile, RobotMap.SM2_banebot, RobotMap.SM2_EncoderA, RobotMap.SM2_EncoderB, RobotMap.SM2_Zero, -10, true); modules[3] = new O_SwerveModule(new O_Point(1,-1), RobotMap.SM3_CIM, RobotMap.SM3_CIMile, RobotMap.SM3_banebot, RobotMap.SM3_EncoderA, RobotMap.SM3_EncoderB, RobotMap.SM3_Zero, 100, true); System.out.println("Swerve Modules Initialized"); } public void initDefaultCommand() { setDefaultCommand(new C_Swerve()); } public void swerve(O_Vector translationVector, O_Point center, double turnSpeed) { double maxWheelMagnitude = 0; for(int k = 0; k<4; k++) { O_Vector steeringVector = new O_Vector(center, modules[k].location); //initilizes as a radial vector from turning center to wheel steeringVector.rotate90(); //steering vector now faces in direction for rotation steeringVector.setMagnitude(turnSpeed); modules[k].wheelVector = translationVector.add(steeringVector); //sum is required wheel vector //check if this wheel has the highest magnitude if(modules[k].wheelVector.getMagnitude() > maxWheelMagnitude) { maxWheelMagnitude = modules[k].wheelVector.getMagnitude(); } // modules[k].isZeroing = OI.Button_A.get(); //the isZeroing vairable should only be assigned to when its is pressed //iszeroing is automatically set to false by zeroing code when done zeroing //this stops zeroing whenever button is pressed if (OI.Button_A.get()) { modules[k].isZeroing = true; } } //scale vectors so no wheel has to drive over 100% if(maxWheelMagnitude > 1.0) { //otherwise Garentess tha there will be a wheel at 100% power - not good when stopped double scaleFactor = 1.0 / maxWheelMagnitude; for(int k = 0; k<4; k++) { modules[k].wheelVector.setMagnitude(scaleFactor * modules[k].wheelVector.getMagnitude()); } } for(int k = 0; k<4; k++) { modules[k].update(); } } //convenience method public void swerve(int heading, double power, O_Point center, double turnSpeed) { O_Vector translationVector = new O_Vector(); translationVector = translationVector.polarVector(heading, power); swerve(translationVector, center, turnSpeed); } /** * Publishes all Swerve System Values to the dashboard. */ public void syncDashboard() { SmartDashboard.putNumber("Wheel1Angle", modules[0].wheelVector.getAngle()); SmartDashboard.putNumber("Wheel2Angle", modules[1].wheelVector.getAngle()); SmartDashboard.putNumber("Wheel3Angle", modules[2].wheelVector.getAngle()); SmartDashboard.putNumber("Wheel4Angle", modules[3].wheelVector.getAngle()); SmartDashboard.putNumber("WheelAngle", modules[3].turnEncoder.encoder.getRaw()); SmartDashboard.putNumber("PIDTarget", modules[3].turn.getSetpoint()); SmartDashboard.putNumber("Power" + modules[3].turnMotor.getChannel(), modules[3].wheelVector.getMagnitude()); System.out.println("Zero Speed: " + modules[3].zeroSpeedOutput); System.out.println("Error: " + ( modules[3].desiredZeroSpeed - modules[3].turnEncoder.encoder.getRate()) * (modules[3].turnEncoder.encoder.getDirection() ? 1.0 : -1.0)); System.out.println("photogate: " + modules[1].turnEncoder.zeroSensor.get()); } }
package mitzi; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import static mitzi.MateScores.*; import mitzi.UCIReporter.InfoType; public class MitziBrain implements IBrain { private IBoard board; private Variation principal_variation; private long eval_counter; private IBoardAnalyzer board_analyzer = new BasicBoardAnalyzer(); @Override public void set(IBoard board) { this.board = board; this.eval_counter = 0; this.principal_variation = null; } /** * Sends updates about evaluation status to UCI GUI. * */ class UCIUpdater extends TimerTask { private long old_mtime; private long old_eval_counter; @Override public void run() { long mtime = System.currentTimeMillis(); long eval_span = eval_counter - old_eval_counter; if (old_mtime != 0) { long time_span = mtime - old_mtime; UCIReporter.sendInfoNum(InfoType.NPS, eval_span * 1000 / time_span); } old_mtime = mtime; old_eval_counter += eval_span; } } private Variation evalBoard(IBoard board, int total_depth, int depth, int alpha, int beta, Variation old_tree) { // whose move is it? Side side = board.getActiveColor(); int side_sign = Side.getSideSign(side); // generate moves Set<IMove> moves = board.getPossibleMoves(); // check for mate and stalemate (the side should alternate) if (moves.isEmpty()) { Variation base_variation; if (board.isCheckPosition()) { base_variation = new Variation(null, NEG_INF * side_sign, Side.getOppositeSide(side)); } else { base_variation = new Variation(null, 0, Side.getOppositeSide(side)); } eval_counter++; return base_variation; } // base case (the side should alternate) if (depth == 0) { AnalysisResult result = board_analyzer.eval0(board); Variation base_variation = new Variation(null, result.getScore(), Side.getOppositeSide(side)); eval_counter++; return base_variation; } int best_value = NEG_INF; // this starts always at negative! // Sort the moves: BasicMoveComparator move_comparator = new BasicMoveComparator(board); ArrayList<IMove> ordered_moves; ArrayList<Variation> ordered_variations = null; if (old_tree == null || old_tree.getSubVariations().isEmpty()) { // no previous computation given, use basic heuristic ordered_moves = new ArrayList<IMove>(moves); Collections.sort(ordered_moves, Collections.reverseOrder(move_comparator)); } else { // use old Variation tree for ordering Set<Variation> children = old_tree.getSubVariations(); ordered_variations = new ArrayList<Variation>(children); if (side == Side.BLACK) Collections.sort(ordered_variations); else Collections .sort(ordered_variations, Collections.reverseOrder()); ordered_moves = new ArrayList<IMove>(); for (Variation var : ordered_variations) { ordered_moves.add(var.getMove()); } // add remaining moves in basic heuristic order ArrayList<IMove> remaining_moves = new ArrayList<IMove>(); for (IMove move : moves) { if (!ordered_moves.contains(move)) remaining_moves.add(move); } Collections.sort(remaining_moves, Collections.reverseOrder(move_comparator)); ordered_moves.addAll(remaining_moves); } // create new parent Variation Variation parent = new Variation(null, NEG_INF, Side.getOppositeSide(side)); int i = 0; // alpha beta search for (IMove move : ordered_moves) { if (depth == total_depth && total_depth >= 6) { // output currently searched move to UCI UCIReporter.sendInfoCurrMove(move, i + 1); } Variation variation; if (ordered_variations != null && i < ordered_variations.size()) { variation = evalBoard(board.doMove(move), total_depth, depth - 1, -beta, -alpha, ordered_variations.get(i)); } else { variation = evalBoard(board.doMove(move), total_depth, depth - 1, -beta, -alpha); } int negaval = variation.getValue() * side_sign; // better variation found if (negaval >= best_value) { boolean truly_better = negaval > best_value; best_value = negaval; // update variation tree parent.update(null, variation.getValue()); // update the missing move for the child variation.update(move, variation.getValue()); parent.addSubVariation(variation); // output to UCI if (depth == total_depth && truly_better) { principal_variation = parent.getPrincipalVariation(); UCIReporter.sendInfoPV(principal_variation, total_depth, variation.getValue(), board.getActiveColor()); } } // alpha beta cutoff alpha = Math.max(alpha, negaval); if (alpha >= beta) break; i++; // keep ordered_moves and ordered_variations in sync } return parent; } private Variation evalBoard(IBoard board, int total_depth, int depth, int alpha, int beta) { return evalBoard(board, total_depth, depth, alpha, beta, null); } @Override public IMove search(int movetime, int maxMoveTime, int searchDepth, boolean infinite, Set<IMove> searchMoves) { // first of all, ignoring the timings and restriction to certain // moves... Timer timer = new Timer(); timer.scheduleAtFixedRate(new UCIUpdater(), 1000, 5000); // iterative deepening Variation var_tree = null; // TODO: use previous searches as starting // point Variation var_tree_temp; // Parameters for aspiration windows int alpha = NEG_INF; // initial value int beta = POS_INF; // initial value int asp_window = 200; // often 50 or 25 is used int factor = 3; // factor for increasing if out of bounds for (int current_depth = 1; current_depth < searchDepth; current_depth++) { this.principal_variation = null; var_tree_temp = evalBoard(board, current_depth, current_depth, alpha, beta, var_tree); // mate found if (principal_variation != null && principal_variation.getValue() == POS_INF && board.getActiveColor() == Side.WHITE || principal_variation.getValue() == NEG_INF && board.getActiveColor() == Side.BLACK) { timer.cancel(); return principal_variation.getMove(); } // If Value is out of bounds, redo search with larger bounds, but // with the same variation tree if (var_tree_temp.getValue() <= alpha) { alpha -= factor * asp_window; current_depth continue; } else if (var_tree_temp.getValue() >= beta) { beta += factor * asp_window; current_depth continue; } alpha = var_tree_temp.getValue() - asp_window; beta = var_tree_temp.getValue() + asp_window; var_tree = var_tree_temp; } // repeat until a value inside the alpha-beta bound is found. while (true) { this.principal_variation = null; var_tree_temp = evalBoard(board, searchDepth, searchDepth, alpha, beta, var_tree); if (var_tree_temp.getValue() <= alpha) { alpha -= factor * asp_window; } else if (var_tree_temp.getValue() >= beta) { beta += factor * asp_window; } else { var_tree = var_tree_temp; break; } } timer.cancel(); if (principal_variation != null) { return principal_variation.getMove(); } else { // mitzi cannot avoid mate :( return var_tree.getBestMove(); } } @Override public IMove stop() { // TODO Auto-generated method stub return null; } }
package com.example.acedeno.customcamera; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.apache.cordova.PluginResult; import org.apache.cordova.CordovaInterface; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import android.app.Activity; import android.util.Log; import android.content.Context; import java.util.ArrayList; public class CustomCameraPlugin extends CordovaPlugin{ private static final String CAMERA = "customCamera"; private static final int GET_PICTURES_REQUEST = 1; private CallbackContext callback; public CustomCameraPlugin() {} public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if(action.equals(CAMERA)){ this.callback = callbackContext; class Snapshot implements Runnable { private CallbackContext callback; private CustomCameraPlugin self; Snapshot(CallbackContext callbackContext, CustomCameraPlugin self){ this.callback = callbackContext; this.self = self; } public void run(){ Intent intent = new Intent(self.cordova.getActivity(), CustomCameraActivity.class); //intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); if(this.self.cordova != null) this.self.cordova.startActivityForResult((CordovaPlugin)this.self, intent, GET_PICTURES_REQUEST); } } this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this)); return true; } return false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); Log.i("XXX", "Pasa por activityResult"); Log.i("XXX", "resultok: " + cordova.getActivity().RESULT_OK); Log.i("XXX", "resultCode" + resultCode); if (requestCode == GET_PICTURES_REQUEST && callback != null) { if (resultCode == cordova.getActivity().RESULT_OK) { Log.i("XXX", "Responde OK"); Bundle extras = intent.getExtras(); String result = extras.getString("result"); Log.i("XXX", "Responde success"); callback.success(result); } else { Log.i("XXX", "Responde failure"); PluginResult r = new PluginResult(PluginResult.Status.OK); r.setKeepCallback(true); callback.sendPluginResult(r); } } //resultCode = Activity.RESULT_OK; } }
package com.example.acedeno.customcamera; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.apache.cordova.PluginResult; import org.apache.cordova.CordovaInterface; import android.content.Intent; import android.os.Bundle; import android.os.Build; import android.widget.Toast; import android.app.Activity; import android.util.Log; import android.content.Context; import java.io.FileNotFoundException; import com.itextpdf.text.DocumentException; import java.util.ArrayList; public class CustomCameraPlugin extends CordovaPlugin{ private static final String CAMERA = "customCamera"; private static final String IMAGES = "images"; private static final int GET_PICTURES_REQUEST = 1; private CallbackContext callback; private boolean running = false; private ArrayList<String> pagepath; public CustomCameraPlugin() {} public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if(action.equals(CAMERA)){ this.callback = callbackContext; class Snapshot implements Runnable { private CallbackContext callback; private CustomCameraPlugin self; Snapshot(CallbackContext callbackContext, CustomCameraPlugin self){ this.callback = callbackContext; this.self = self; } public void run(){ Intent intent = new Intent(self.cordova.getActivity(), CustomCameraActivity.class); if(this.self.cordova != null){ this.self.cordova.startActivityForResult((CordovaPlugin)this.self, intent, GET_PICTURES_REQUEST); } } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this)); }else{ if(!this.running){ this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this)); this.running = true; } } return true; } else if(action.equals(IMAGES)){ Log.i("XXX", "Pasa por imágenes"); try { //JSONObject json = new JSONObject(args.getString(0)); JSONArray json = args.getJSONArray(0); for(int i=0;i<json.length(); i++){ String data = json.getString(i); Log.i("data: ",data); } }catch(Exception e){ Log.i("XXX", "Error"); e.printStackTrace(); } //Log.i("XXX", "data: " + js); PluginResult r = new PluginResult(PluginResult.Status.OK); r.setKeepCallback(true); callbackContext.sendPluginResult(r); /*if (jsArr != null){ for(int i = 0; i < jsArr.length(); i ++){ this.pagepath.add(jsArr.getString(i)); } try{ ImagesManager im = new ImagesManager(this.pagepath); String pdfPath = im.createPdf(); Log.i("XXX", pdfPath); PluginResult r = new PluginResult(PluginResult.Status.OK, pdfPath); r.setKeepCallback(true); callbackContext.sendPluginResult(r); } catch (FileNotFoundException e) { Log.i("XXX", "FileNotFound"); e.printStackTrace(); } catch (DocumentException e) { Log.i("XXX", "DocumentException"); e.printStackTrace(); } catch(Exception e){ Log.i("XXX", "Exception"); e.printStackTrace(); } }*/ return true; } return false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == GET_PICTURES_REQUEST && callback != null) { this.running = false; if (resultCode == cordova.getActivity().RESULT_OK) { Bundle extras = intent.getExtras(); String result = extras.getString("result"); callback.success(result); } else { PluginResult r = new PluginResult(PluginResult.Status.OK); r.setKeepCallback(true); callback.sendPluginResult(r); } } } }
package simcity.TRestaurant; import agent.Role; import simcity.TRestaurant.gui.TWaiterGui; import simcity.gui.SimCityGui; import simcity.gui.trace.AlertLog; import simcity.gui.trace.AlertTag; import simcity.interfaces.TCustomer; import simcity.interfaces.TWaiter; import simcity.PersonAgent; import java.util.*; import java.util.concurrent.Semaphore; /** * Restaurant Waiter Agent */ public class TWaiterSharedDataRole extends TWaiterRole implements TWaiter{ public List<customers> myCustomers = new ArrayList<customers>(); enum CustomerState {waiting, seated, ordering, askingForOrder, waitingForOrder, orderPlaced, orderDone, Eating, wantsCheck, needsCheck, Paying, gaveCheck, Leaving}; private String name; private Semaphore atTable = new Semaphore(0,true); private Semaphore withCustomer = new Semaphore(-1, true); private Semaphore atCook = new Semaphore(0, true); private THostRole host; private TCookRole cook; private TCashierRole cashier; public boolean onBreak = false; public boolean askingForBreak = false; boolean goHome = false; Timer timer = new Timer(); private Menu menu = new Menu(); SimCityGui gui; boolean arrived; public TWaiterGui waiterGui = null; public TWaiterSharedDataRole(SimCityGui gui) { super(gui); this.gui = gui; this.name = name; } public String getMaitreDName() { return name; } public String getName() { return name; } // Messages public void msgSeatAtTable(TCustomer cust, int t) { customers c = new customers(); c.setCustomer(cust); c.setTable(t); myCustomers.add(c); stateChanged(); } public void msgReadyToOrder(TCustomer cust) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != cust && index < myCustomers.size()) { index++; } myCustomers.get(index).state = CustomerState.ordering; } stateChanged(); } public void msgHeresMyChoice(TCustomer cust, String order) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != cust && index < myCustomers.size()) { index++; } setOrder(myCustomers.get(index).c, order); myCustomers.get(index).state = CustomerState.waitingForOrder; } stateChanged(); } public void msgOutOfFood(int t) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).table != t && index < myCustomers.size()) { index++; } myCustomers.get(index).state = CustomerState.ordering; } stateChanged(); } public void msgOrderIsReady(int t) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).table != t) { index++; } myCustomers.get(index).state = CustomerState.orderDone; } stateChanged(); } public void msgReadyForCheck(TCustomer cust) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != cust) { index++; } myCustomers.get(index).state = CustomerState.wantsCheck; } stateChanged(); } public void msgHereIsCheck(TCustomer cust, double c) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != cust) { index++; } AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Recieved check from cashier"); Do("Received check from cashier"); myCustomers.get(index).check = c; myCustomers.get(index).state = CustomerState.Paying; } stateChanged(); } public void msgLeavingTable(TCustomer cust) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != cust) { index++; } myCustomers.get(index).state = CustomerState.Leaving; } stateChanged(); } public void msgNoBreak() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "No break for me."); Do("No break for me."); askingForBreak = false; stateChanged(); } public void msgOnBreak() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "I can have a break! :)"); Do("I can have a break! :)"); onBreak = true; stateChanged(); } public void msgAtTable() {//from animation //print("msgAtTable() called"); atTable.release();// = true; stateChanged(); } public void msgWithCustomer() { withCustomer.release(); stateChanged(); } public void msgAtKitchen() { atCook.release(); stateChanged(); } public void msgAskForBreak () { askingForBreak = true; stateChanged(); } public void msgGoHome(double moneys) { myPerson.money += moneys; goHome = true; stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ public boolean pickAndExecuteAnAction() { if(arrived) { tellHost(); return true; } if (askingForBreak == true) { askingForBreak = false; AskForBreak(); return true; } try { if (!myCustomers.isEmpty()) { for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.Paying) { print("Giving customer his check"); giveCheck(myCustomers.get(index).c, myCustomers.get(index).table, myCustomers.get(index).check); myCustomers.get(index).state = CustomerState.gaveCheck; return true; } } for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.Leaving) { callHost(myCustomers.get(index).c); return true; } } for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.ordering) { myCustomers.get(index).state = CustomerState.askingForOrder; print("Going to take customer's order"); try { goToTable(myCustomers.get(index).c, myCustomers.get(index).table); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } } for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.wantsCheck) { print("Calling cashier for check"); callCashier(myCustomers.get(index).c); myCustomers.get(index).state = CustomerState.needsCheck; return true; } } for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.waitingForOrder) { print("Calling cook to give order"); callCook(myCustomers.get(index)); myCustomers.get(index).state = CustomerState.orderPlaced; return true; } } for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.orderDone) { //goToCook(); giveOrder(myCustomers.get(index).c, myCustomers.get(index).table); myCustomers.get(index).state = CustomerState.Eating; return true; } } for (int index = 0; index < myCustomers.size(); index++) { if (myCustomers.get(index).state == CustomerState.waiting) { /** waiterGui.getCustomer(); try { withCustomer.acquire(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } */ seatCustomer(myCustomers.get(index)); return true; } } } } catch (ConcurrentModificationException e) { e.printStackTrace(); } if(goHome) { goHome(); return true; } if (onBreak == true && myCustomers.isEmpty()) { onBreak = false; takeBreak(); return true; } return false; } // Actions private void tellHost() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Telling manager I can work"); Do("Telling manager I can work"); arrived = false; host.msgIAmHere(this, "Waiter"); if (waiterGui == null) { TWaiterGui w = new TWaiterGui(this); gui.myPanels.get("Restaurant 6").panel.addGui(w); waiterGui = w; } } private void goHome() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Going home"); Do("Going home"); isActive = false; goHome = false; } private void seatCustomer(customers customer) { //DoGetCustomer(); menu.setMenu(); customer.c.msgSitAtTable(customer.table, menu.foodChoices); customer.state = CustomerState.seated; customer.c.setWaiter(this); //DoSeatCustomer(customer.c, customer.table); try { atTable.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //waiterGui.DoLeaveCustomer(); } private void goToTable (TCustomer c, int table) throws InterruptedException { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Going to table"); Do("Going to table " + table + " to take order"); //DoGoToTable(table); //atTable.acquire(); c.msgWhatWouldYouLike(); //waiterGui.DoLeaveCustomer(); } private void setOrder(TCustomer c, String o) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != c) { index ++; } myCustomers.get(index).choice = o; } myCustomers.get(index).state = CustomerState.waitingForOrder; AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Received customer's orders"); Do("Received customer's orders"); } private void callCook(customers c) { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "in callCook"); Do("in callCook"); /** goToCook(); try { atCook.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ cook.msgHereIsAnOrder(c.table, c.choice, this); //waiterGui.DoLeaveCustomer(); } private void giveOrder(TCustomer c, int t) { //goToCook(); try { atCook.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } /** DoGoToTable(t); try { atTable.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Giving customer their order"); Do("Giving customer their order."); c.msgHeresYourOrder(); //waiterGui.DoLeaveCustomer(); } private void callCashier(TCustomer c) { int index = 0; while (myCustomers.get(index).c != c) { index ++; } cashier.msgComputeBill(this, myCustomers.get(index).c, myCustomers.get(index).choice); } private void giveCheck(TCustomer c, int tab, double check) { //DoGoToTable(tab); try { atTable.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Gave check to customer"); Do("Gave check to customer"); c.msgHereIsYourCheck(check); //waiterGui.DoLeaveCustomer(); } private void callHost(TCustomer c) { int index = 0; synchronized (myCustomers) { while (myCustomers.get(index).c != c) { index ++; } myCustomers.remove(index); } host.msgCustomerLeft(c); } private void AskForBreak() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Asking host for a break"); Do("Asking host for a break"); host.msgBreakPlease(this); } private void takeBreak() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Taking my break"); Do("Taking my break"); //waiterGui.DoGoOnBreak(); //waiterGui.setBreak(); timer.schedule(new TimerTask() { public void run() { DoneWithBreak(); } }, 10000); } public void DoneWithBreak() { AlertLog.getInstance().logInfo(AlertTag.TRestaurant, "TWaiterSharedDataRole", "Done with my break"); Do("Done with my break"); //waiterGui.DoLeaveCustomer(); //waiterGui.offBreak(); host.msgOffBreak(this); } // The animation DoXYZ() routines /** private void DoGetCustomer() { waiterGui.getCustomer(); } private void DoSeatCustomer(TCustomer c, int tab) { print("Seating " + c + " at table " + tab); waiterGui.DoBringToTable(tab); } private void DoGoToTable (int tab) { waiterGui.DoBringToTable(tab); } private void goToCook () { waiterGui.DoGoToCook(); } */ //utilities public void setGui(TWaiterGui gui) { waiterGui = gui; } public void setHomePosition (int l) { //waiterGui.setHome(l); } public TWaiterGui getGui() { return waiterGui; } public void setHost(THostRole h) { host = h; } public void setCook(TCookRole c) { cook = c; } public void setCashier (TCashierRole c) { cashier = c; } class customers { TCustomer c; int table; String choice; Double check; CustomerState state; public void setCustomer(TCustomer cust) { c = cust; state = CustomerState.waiting; } public void setTable (int t) { table = t; } TCustomer getC(){ return c; } } public class Menu { //public String[] foodChoices = {"Steak", "Chicken", "Salad", "Pizza"}; public List<String> foodChoices = new ArrayList<String>(); public void setMenu () { foodChoices.add("Steak"); foodChoices.add("Salad"); foodChoices.add("Chicken"); foodChoices.add("Pizza"); } public void removeItem(String item) { int i = 0; while (foodChoices.get(i) != item) { i++; } foodChoices.remove(i); } public void addItem(String item) { foodChoices.add(item); } } }
package com.amihaiemil.camel; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; /** * Unit tests for {@link Scalar}. * @author Mihai Andronache (amihaiemil@gmail.com) * @version $Id$ * @since 1.0.0 * */ public final class ScalarTest { /** * Scalar can return its own value. */ @Test public void returnsValue() { final String val = "test scalar value"; final Scalar<String> scl = new Scalar<String>( Arrays.asList(Mockito.mock(AbstractNode.class)), val ); MatcherAssert.assertThat( scl.value(), Matchers.equalTo(val) ); } /** * A Scalar shouldn't have any child nodes. */ @Test public void hasNoChildren() { final String val = "test scalar value"; final Scalar<String> scl = new Scalar<String>( Arrays.asList(Mockito.mock(AbstractNode.class)), val ); MatcherAssert.assertThat( scl.children(), Matchers.emptyIterable() ); } /** * Scalar throws ISE if no parents are specified. */ @Test (expected = IllegalStateException.class) public void orphanForbidden() { new Scalar<String>( new ArrayList<AbstractNode>(), "orphan" ); } /** * Make sure that equals and hash code are reflexive * and symmetric. */ @Test public void equalsAndHashCode() { final String val = "test scalar value"; final Scalar<String> firstScalar = new Scalar<String>( Arrays.asList(Mockito.mock(AbstractNode.class)), val ); final Scalar<String> secondScalar = new Scalar<String>( Arrays.asList(Mockito.mock(AbstractNode.class)), val ); MatcherAssert.assertThat(firstScalar, Matchers.equalTo(secondScalar)); MatcherAssert.assertThat(secondScalar, Matchers.equalTo(firstScalar)); MatcherAssert.assertThat(firstScalar, Matchers.equalTo(firstScalar)); MatcherAssert.assertThat(firstScalar, Matchers.equalTo(null)); MatcherAssert.assertThat(firstScalar.getClass() != secondScalar.getClass(), is(false)); MatcherAssert.assertThat( firstScalar.hashCode() == secondScalar.hashCode(), is(true) ); } }
package de.bwaldvogel; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import java.net.InetSocketAddress; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.HeapChannelBufferFactory; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoClient; import com.mongodb.MongoException; import de.bwaldvogel.mongo.backend.MongoServerBackend; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; import de.bwaldvogel.mongo.wire.MongoDatabaseHandler; import de.bwaldvogel.mongo.wire.MongoWireEncoder; import de.bwaldvogel.mongo.wire.MongoWireProtocolHandler; import de.bwaldvogel.mongo.wire.message.MongoServer; public class MemoryBackendTest { private static final int PORT = 37017; private ChannelFactory factory; private Channel serverChannel; private Mongo mongo; @Before public void setUp() throws Exception{ MongoServerBackend backend = new MemoryBackend(); final MongoServer mongoServer = new MongoServer( backend ); factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool() , Executors.newCachedThreadPool() ); final ServerBootstrap bootstrap = new ServerBootstrap( factory ); bootstrap.setOption( "child.bufferFactory", new HeapChannelBufferFactory( ByteOrder.LITTLE_ENDIAN ) ); // Set up the pipeline factory. bootstrap.setPipelineFactory( new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception{ return Channels.pipeline( new MongoWireEncoder(), new MongoWireProtocolHandler(), new MongoDatabaseHandler( mongoServer ) ); } } ); serverChannel = bootstrap.bind( new InetSocketAddress( PORT ) ); mongo = new MongoClient( "localhost" , PORT ); } @After public void tearDown(){ mongo.close(); serverChannel.close().awaitUninterruptibly(); factory.releaseExternalResources(); } @Test public void testMaxBsonSize() throws Exception{ int maxBsonObjectSize = mongo.getMaxBsonObjectSize(); assertThat( maxBsonObjectSize ).isEqualTo( 16777216 ); } @Test public void testListDatabaseNames() throws Exception{ assertThat( mongo.getDatabaseNames() ).isEmpty(); mongo.getDB( "testdb" ).getCollection( "testcollection" ).insert( new BasicDBObject() ); assertThat( mongo.getDatabaseNames() ).containsExactly( "testdb" ); mongo.getDB( "bar" ).getCollection( "testcollection" ).insert( new BasicDBObject() ); assertThat( mongo.getDatabaseNames() ).containsExactly( "bar", "testdb" ); } @Test public void testIllegalCommand() throws Exception{ try { mongo.getDB( "testdb" ).command( "foo" ).throwOnError(); fail( "MongoException expected" ); } catch ( MongoException e ) { assertThat( e.getMessage() ).contains( "no such cmd" ); } try { mongo.getDB( "bar" ).command( "foo" ).throwOnError(); fail( "MongoException expected" ); } catch ( MongoException e ) { assertThat( e.getMessage() ).contains( "no such cmd" ); } } @Test public void testQuery() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); DBObject obj = collection.findOne( new BasicDBObject( "_id" , 1 ) ); assertThat( obj ).isNull(); assertThat( collection.count() ).isEqualTo( 0 ); } @Test public void testQueryAll() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); List<Object> inserted = new ArrayList<Object>(); for ( int i = 0; i < 10; i++ ) { BasicDBObject obj = new BasicDBObject( "_id" , i ); collection.insert( obj ); inserted.add( obj ); } assertThat( collection.count() ).isEqualTo( 10 ); assertThat( collection.find().toArray() ).isEqualTo( inserted ); } @Test public void testInsert() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); assertThat( collection.count() ).isEqualTo( 0 ); for ( int i = 0; i < 3; i++ ) { collection.insert( new BasicDBObject( "_id" , Integer.valueOf( i ) ) ); } assertThat( collection.count() ).isEqualTo( 3 ); } @Test public void testInsertDuplicate() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); assertThat( collection.count() ).isEqualTo( 0 ); collection.insert( new BasicDBObject( "_id" , 1 ) ); assertThat( collection.count() ).isEqualTo( 1 ); try { collection.insert( new BasicDBObject( "_id" , 1 ) ); fail( "MongoException expected" ); } catch ( MongoException e ) { assertThat( e.getMessage() ).contains( "duplicate key error" ); } try { collection.insert( new BasicDBObject( "_id" , 1.0 ) ); fail( "MongoException expected" ); } catch ( MongoException e ) { assertThat( e.getMessage() ).contains( "duplicate key error" ); } assertThat( collection.count() ).isEqualTo( 1 ); } @Test public void testInsertQuery() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); assertThat( collection.count() ).isEqualTo( 0 ); BasicDBObject insertedObject = new BasicDBObject( "_id" , 1 ); insertedObject.put( "foo", "bar" ); collection.insert( insertedObject ); assertThat( collection.findOne( insertedObject ) ).isEqualTo( insertedObject ); assertThat( collection.findOne( new BasicDBObject( "_id" , 1l ) ) ).isEqualTo( insertedObject ); assertThat( collection.findOne( new BasicDBObject( "_id" , 1.0 ) ) ).isEqualTo( insertedObject ); assertThat( collection.findOne( new BasicDBObject( "_id" , 1.0001 ) ) ).isNull(); assertThat( collection.findOne( new BasicDBObject( "foo" , "bar" ) ) ).isEqualTo( insertedObject ); assertThat( collection.findOne( new BasicDBObject( "foo" , null ) ) ).isEqualTo( insertedObject ); } @Test public void testInsertRemove() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); for ( int i = 0; i < 10; i++ ) { collection.insert( new BasicDBObject( "_id" , 1 ) ); collection.remove( new BasicDBObject( "_id" , 1 ) ); collection.insert( new BasicDBObject( "_id" , i ) ); collection.remove( new BasicDBObject( "_id" , i ) ); } collection.remove( new BasicDBObject( "doesnt exist" , 1 ) ); assertThat( collection.count() ).isEqualTo( 0 ); } @Test public void testUpdate() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); BasicDBObject object = new BasicDBObject( "_id" , 1 ); BasicDBObject newObject = new BasicDBObject( "_id" , 1 ); newObject.put( "foo", "bar" ); collection.insert( object ); collection.update( object, newObject ); assertThat( collection.findOne( object ) ).isEqualTo( newObject ); } @Test public void testUpsert() throws Exception{ DBCollection collection = mongo.getDB( "testdb" ).getCollection( "testcollection" ); BasicDBObject object = new BasicDBObject( "_id" , 1 ); BasicDBObject newObject = new BasicDBObject( "_id" , 1 ); newObject.put( "foo", "bar" ); collection.update( object, newObject, true, false ); assertThat( collection.findOne( object ) ).isEqualTo( newObject ); } @Test public void testDropDatabase() throws Exception{ mongo.getDB( "testdb" ).getCollection( "foo" ).insert( new BasicDBObject() ); assertThat( mongo.getDatabaseNames() ).containsExactly( "testdb" ); mongo.dropDatabase( "testdb" ); assertThat( mongo.getDatabaseNames() ).isEmpty(); } @Test public void testDropCollection() throws Exception{ DB db = mongo.getDB( "testdb" ); db.getCollection( "foo" ).insert( new BasicDBObject() ); assertThat( db.getCollectionNames() ).containsOnly( "foo" ); db.getCollection( "foo" ).drop(); assertThat( db.getCollectionNames() ).isEmpty(); } @Test public void testReplicaSetInfo() throws Exception{ // ReplicaSetStatus status = mongo.getReplicaSetStatus(); // System.out.println(status); // assertThat(status) } }
package guitests; import static org.junit.Assert.*; import java.util.Stack; import org.junit.Test; import seedu.taskitty.logic.commands.RedoCommand; import seedu.taskitty.logic.commands.UndoCommand; import seedu.taskitty.testutil.TestTask; import seedu.taskitty.testutil.TestTaskList; //@@ author A0139052L public class UndoAndRedoCommandTest extends TaskManagerGuiTest { Stack<TestTaskList> undoTestTaskListStack; Stack<TestTaskList> redoTestTaskListStack; Stack<String> undoCommandTextStack; Stack<String> redoCommandTextStack; TestTaskList currentList; @Test public void undoAndRedo() { // use a stack to hold all previous TestTaskList and command texts undoTestTaskListStack = new Stack<TestTaskList>(); redoTestTaskListStack = new Stack<TestTaskList>(); undoCommandTextStack = new Stack<String>(); redoCommandTextStack = new Stack<String>(); // store the current list into undo stack before running the command currentList = new TestTaskList(td.getTypicalTasks()); undoTestTaskListStack.push(currentList.copy()); currentList.addTaskToList(td.todo); String commandText = td.todo.getAddCommand(); commandBox.runCommand(commandText); undoCommandTextStack.push(commandText); undoTestTaskListStack.push(currentList.copy()); int targetIndex = currentList.size() / 2; commandText = "delete " + targetIndex; commandBox.runCommand(commandText); currentList.removeTaskFromList(targetIndex - 1); undoCommandTextStack.push(commandText); undoTestTaskListStack.push(currentList.copy()); commandText = "clear"; commandBox.runCommand(commandText); undoCommandTextStack.push(commandText); currentList = new TestTaskList(new TestTask[] {}); //test undo brings back the previous list and store the list before undoing and the command text to the redo stack runUndo(); // test if using accelerator for undo works runUndoUsingAccelerator(); //test if redo brings back the undone list runRedo(); undoTestTaskListStack.push(currentList.copy()); targetIndex = currentList.size('d'); commandText = td.event.getEditCommand(targetIndex, 'd'); commandBox.runCommand(commandText); currentList.editTaskFromList(targetIndex - 1, 'd', td.event); undoCommandTextStack.push(commandText); // clear redo stack when new undoable command has been given and check that there is no redo available redoCommandTextStack.clear(); redoTestTaskListStack.clear(); assertNoMoreRedos(); undoTestTaskListStack.push(currentList.copy()); targetIndex = currentList.size('t'); commandText = "done t" + targetIndex; commandBox.runCommand(commandText); TestTask taskToMark = currentList.getTaskFromList(targetIndex - 1, 't'); currentList.markTaskAsDoneInList(targetIndex - 1, 't', taskToMark); undoCommandTextStack.push(commandText); // run undo for all the commands until we get back original list and check no more undos after that runUndo(); runUndoUsingAccelerator(); runUndo(); runUndoUsingAccelerator(); assertNoMoreUndos(); // run redo for all undos done until we get back the latest list and check no more redos after that runRedoUsingAccelerator(); runRedo(); runRedoUsingAccelerator(); commandBox.runCommand("view all"); runRedo(); assertNoMoreRedos(); } @Test public void invalidCommand_noUndos() { commandBox.runCommand("adds party"); assertNoMoreUndos(); } private void runRedo() { TestTaskList undoneList = redoTestTaskListStack.pop(); String undoneCommandText = redoCommandTextStack.pop(); assertRedoSuccess(undoneList, undoneCommandText); undoTestTaskListStack.push(currentList.copy()); undoCommandTextStack.push(undoneCommandText); currentList = undoneList; } private void runRedoUsingAccelerator() { TestTaskList undoneList = redoTestTaskListStack.pop(); String undoneCommandText = redoCommandTextStack.pop(); assertRedoUsingAcceleratorSuccess(undoneList, undoneCommandText); undoTestTaskListStack.push(currentList.copy()); undoCommandTextStack.push(undoneCommandText); currentList = undoneList; } private void runUndoUsingAccelerator() { String previousCommandText = undoCommandTextStack.pop(); TestTaskList previousList = undoTestTaskListStack.pop(); assertUndoUsingAcceleratorSuccess(previousList, previousCommandText); redoTestTaskListStack.push(currentList.copy()); redoCommandTextStack.push(previousCommandText); currentList = previousList; } private void runUndo() { String previousCommandText = undoCommandTextStack.pop(); TestTaskList previousList = undoTestTaskListStack.pop(); assertUndoSuccess(previousList, previousCommandText); redoTestTaskListStack.push(currentList.copy()); redoCommandTextStack.push(previousCommandText); currentList = previousList; } private void assertUndoSuccess(TestTaskList expectedList, String commandText) { commandBox.runCommand("undo"); assertTrue(expectedList.isListMatching(taskListPanel)); assertResultMessage(UndoCommand.MESSAGE_UNDO_SUCCESS + commandText.trim()); } private void assertUndoUsingAcceleratorSuccess(TestTaskList expectedList, String commandText) { mainMenu.useUndoCommandUsingAccelerator(); assertTrue(expectedList.isListMatching(taskListPanel)); assertResultMessage(UndoCommand.MESSAGE_UNDO_SUCCESS + commandText.trim()); } private void assertNoMoreUndos() { commandBox.runCommand("undo"); assertResultMessage(UndoCommand.MESSAGE_NO_PREVIOUS_VALID_COMMANDS); } private void assertRedoSuccess(TestTaskList expectedList, String commandText) { commandBox.runCommand("redo"); assertTrue(expectedList.isListMatching(taskListPanel)); assertResultMessage(RedoCommand.MESSAGE_REDO_SUCCESS + commandText.trim()); } private void assertRedoUsingAcceleratorSuccess(TestTaskList expectedList, String commandText) { mainMenu.useRedoCommandUsingAccelerator(); assertTrue(expectedList.isListMatching(taskListPanel)); assertResultMessage(RedoCommand.MESSAGE_REDO_SUCCESS + commandText.trim()); } private void assertNoMoreRedos() { commandBox.runCommand("redo"); assertResultMessage(RedoCommand.MESSAGE_NO_RECENT_UNDO_COMMANDS); } }
package guitests; import guitests.guihandles.GuiHandle; import javafx.scene.Node; import javafx.stage.Stage; import seedu.tasklist.model.task.DeadlineTask; import seedu.tasklist.model.task.EventTask; import seedu.tasklist.model.task.FloatingTask; import seedu.tasklist.model.task.ReadOnlyDeadlineTask; import seedu.tasklist.model.task.ReadOnlyEventTask; import seedu.tasklist.model.task.ReadOnlyTask; //@@author A0143355J public class UpcomingTaskCardHandle extends GuiHandle { private static final String NAME_FIELD_ID = "#name"; private static final String DATE_ONE_FIELD_ID = "#firstDate"; private static final String DATE_TWO_FIELD_ID = "#secondDate"; private Node node; protected UpcomingTaskCardHandle(GuiRobot guiRobot, Stage primaryStage, Node node) { super(guiRobot, primaryStage, null); this.node = node; } /* * Returns the text inside the label */ protected String getTextFromLabel(String fieldId) { return getTextFromLabel(fieldId, node); } /* * Returns Task Name inside the UpcomingTaskCard */ protected String getTaskName() { return getTextFromLabel(NAME_FIELD_ID); } /* * Returns Deadline date from UpcomingTaskCard */ protected String getDeadline() { return getTextFromLabel(DATE_TWO_FIELD_ID); } /* * Returns Start Date from UpcomingTaskCard */ protected String getStartDate() { return getTextFromLabel(DATE_ONE_FIELD_ID); } /* * Returns End Date from UpcomingTaskCard */ protected String getEndDate() { return getTextFromLabel(DATE_TWO_FIELD_ID); } /* * Returns true if task is the same as the task inside UpcomingTaskCard */ public boolean isSameTask(ReadOnlyTask task) { String taskType = task.getType(); switch (taskType) { case FloatingTask.TYPE: return isSameName(task); case DeadlineTask.TYPE: return isSameName(task) && isSameDeadline(task); case EventTask.TYPE: return isSameName(task) && isSameStartDate(task) && isSameEndDate(task); default: return false; } } /* * Returns true if task has the same name as task inside UpcomingTaskCard */ private boolean isSameName(ReadOnlyTask task) { return getTaskName().equals(task.getName().fullName); } /* * Returns true if task has the same deadline as task inside UpcomingTaskCard */ private boolean isSameDeadline(ReadOnlyTask task) { return getDeadline().equals(((ReadOnlyDeadlineTask) task).getDeadlineStringForUpcomingTask()); } /* * Returns true if task has the same Start Date as task inside UpcomingTaskCard */ private boolean isSameStartDate(ReadOnlyTask task) { return getStartDate().equals(((ReadOnlyEventTask) task).getStartDateStringForUpcomingTask()); } /* * Returns true if task has the same End Date as task inside UpcomingTaskCard */ private boolean isSameEndDate(ReadOnlyTask task) { return getEndDate().equals(((ReadOnlyEventTask) task).getEndDateStringForUpcomingTask()); } }
package io.xn.dx.vendor; import com.fasterxml.jackson.databind.JsonNode; import org.apache.http.HttpResponse; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import java.io.IOException; public class JsonNodeHandler implements ResponseHandler<JsonNode> { @Override public JsonNode handleResponse(final HttpResponse response) throws IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 300 || status < 200) { throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } return Jackson.getReader().readTree(response.getEntity().getContent()); } }
package org.postgresql.util; /** * This class is used for holding SQLState codes. */ public enum PSQLState { UNKNOWN_STATE(""), TOO_MANY_RESULTS("0100E"), NO_DATA("02000"), INVALID_PARAMETER_TYPE("07006"), /** * We could establish a connection with the server for unknown reasons. Could be a network * problem. */ CONNECTION_UNABLE_TO_CONNECT("08001"), CONNECTION_DOES_NOT_EXIST("08003"), /** * The server rejected our connection attempt. Usually an authentication failure, but could be a * configuration error like asking for a SSL connection with a server that wasn't built with SSL * support. */ CONNECTION_REJECTED("08004"), /** * After a connection has been established, it went bad. */ CONNECTION_FAILURE("08006"), CONNECTION_FAILURE_DURING_TRANSACTION("08007"), /** * The server sent us a response the driver was not prepared for and is either bizarre datastream * corruption, a driver bug, or a protocol violation on the server's part. */ PROTOCOL_VIOLATION("08P01"), COMMUNICATION_ERROR("08S01"), NOT_IMPLEMENTED("0A000"), DATA_ERROR("22000"), STRING_DATA_RIGHT_TRUNCATION("22001"), NUMERIC_VALUE_OUT_OF_RANGE("22003"), BAD_DATETIME_FORMAT("22007"), DATETIME_OVERFLOW("22008"), DIVISION_BY_ZERO("22012"), MOST_SPECIFIC_TYPE_DOES_NOT_MATCH("2200G"), INVALID_PARAMETER_VALUE("22023"), INVALID_CURSOR_STATE("24000"), TRANSACTION_STATE_INVALID("25000"), ACTIVE_SQL_TRANSACTION("25001"), NO_ACTIVE_SQL_TRANSACTION("25P01"), IN_FAILED_SQL_TRANSACTION("25P02"), INVALID_SQL_STATEMENT_NAME("26000"), INVALID_AUTHORIZATION_SPECIFICATION("28000"), STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL("2F003"), INVALID_SAVEPOINT_SPECIFICATION("3B000"), DEADLOCK_DETECTED("40P01"), SYNTAX_ERROR("42601"), UNDEFINED_COLUMN("42703"), UNDEFINED_OBJECT("42704"), WRONG_OBJECT_TYPE("42809"), NUMERIC_CONSTANT_OUT_OF_RANGE("42820"), DATA_TYPE_MISMATCH("42821"), UNDEFINED_FUNCTION("42883"), INVALID_NAME("42602"), DATATYPE_MISMATCH("42804"), CANNOT_COERCE("42846"), OUT_OF_MEMORY("53200"), OBJECT_NOT_IN_STATE("55000"), OBJECT_IN_USE("55006"), QUERY_CANCELED("57014"), SYSTEM_ERROR("60000"), IO_ERROR("58030"), UNEXPECTED_ERROR("99999"); private final String state; PSQLState(String state) { this.state = state; } public String getState() { return this.state; } public static boolean isConnectionError(String psqlState) { return PSQLState.CONNECTION_UNABLE_TO_CONNECT.getState().equals(psqlState) || PSQLState.CONNECTION_DOES_NOT_EXIST.getState().equals(psqlState) || PSQLState.CONNECTION_REJECTED.getState().equals(psqlState) || PSQLState.CONNECTION_FAILURE.getState().equals(psqlState) || PSQLState.CONNECTION_FAILURE_DURING_TRANSACTION.getState().equals(psqlState); } }
package rhomobile; import j2me.util.LinkedList; import j2me.util.StringParser; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.microedition.io.HttpConnection; import net.rim.blackberry.api.browser.Browser; import net.rim.blackberry.api.browser.BrowserSession; import net.rim.blackberry.api.invoke.Invoke; import net.rim.device.api.browser.field.RenderingOptions; import net.rim.device.api.io.http.HttpHeaders; import net.rim.device.api.system.Application; import net.rim.device.api.system.ApplicationManager; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.Characters; import net.rim.device.api.system.Display; import net.rim.device.api.system.EncodedImage; import net.rim.device.api.system.KeyListener; import net.rim.device.api.system.SystemListener; //import javax.microedition.io.file.FileSystemListener; import net.rim.device.api.system.TrackwheelListener; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.BitmapField; import net.rim.device.api.ui.component.Dialog; import net.rim.device.api.ui.component.Menu; import net.rim.device.api.ui.container.PopupScreen; import net.rim.device.api.ui.container.VerticalFieldManager; //import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.Manager; import net.rim.device.api.math.Fixed32; //import net.rim.device.api.system.EventInjector.KeyCodeEvent; import net.rim.blackberry.api.invoke.MessageArguments; import com.rho.*; //import com.rho.db.DBAdapter; import com.rho.rubyext.GeoLocation; import com.rho.net.NetResponse; import com.rho.net.RhoConnection; import com.rho.net.URI; import com.rho.sync.ClientRegister; import com.rho.sync.SyncThread; import com.rho.sync.ISyncStatusListener; import com.rho.file.Jsr75File; import com.rho.RhodesApp; import com.xruby.runtime.lang.RubyProgram; final public class RhodesApplication extends RhodesApplicationPlatform implements SystemListener, ISyncStatusListener { // Menu Labels public static final String LABEL_HOME = "Home"; public static final String LABEL_REFRESH = "Refresh"; public static final String LABEL_BACK = "Back"; public static final String LABEL_SYNC = "Sync"; public static final String LABEL_OPTIONS = "Options"; public static final String LABEL_LOG = "Log"; public static final String LABEL_SEPARATOR = "separator"; public static final String LABEL_CLOSE = "Close"; public static final String LABEL_EXIT = "Exit"; public static final String LABEL_NONE = "none"; private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("RhodesApplication"); class CKeyListener implements KeyListener{ public boolean keyChar(char key, int status, int time) { if( key == Characters.ENTER ) { return openLink(); //return true; } return false; } public boolean keyDown(int keycode, int time) { int nKey = Keypad.key(keycode); if ( nKey == Keypad.KEY_ESCAPE ) { /*if ( m_bSkipKeyPress ) m_bSkipKeyPress = false; else*/ //back(); RHODESAPP().navigateBack(); return true; } return false; } public boolean keyRepeat(int keycode, int time) {return false;} public boolean keyStatus(int keycode, int time) {return false;} public boolean keyUp(int keycode, int time) {return false;} }; class CTrackwheelListener implements TrackwheelListener{ public boolean trackwheelClick(int status, int time) { return openLink(); //return true; } public boolean trackwheelRoll(int amount, int status, int time) { return false; } public boolean trackwheelUnclick(int status, int time) {return false;} } public void navigateUrl(String url){ PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread( RHODESAPP().canonicalizeRhoUrl(url), null, null, null); thread.start(); } public void navigateUrlWithEvent(String url, Object ev){ PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread( RHODESAPP().canonicalizeRhoUrl(url), null, null, ev); thread.start(); } public void addMenuItem(String label, String value){ LOG.TRACE("Adding menu item: label: " + label + ", value: " + value); _mainScreen.addCustomMenuItem(label, value); } //private String m_strAppBackUrl =""; public void resetMenuItems() { _mainScreen.setMenuItems(new Vector()); //m_strAppBackUrl = ""; RHODESAPP().setAppBackUrl(""); } public void postUrl(String url, String body, HttpHeaders headers) { postUrl(url, body, headers, null); } public void postUrl(String url, String body, HttpHeaders headers, Runnable callback){ PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread( RHODESAPP().canonicalizeRhoUrl(url), headers, body.getBytes(), null, callback); thread.setInternalRequest(true); thread.start(); } public static class NetCallback { public NetResponse m_response; public void waitForResponse() { synchronized(this) { try{ this.wait(); }catch(InterruptedException exc){} } } public void setResponse(NetResponse resp) { synchronized(this) { m_response = resp; this.notifyAll(); } } } public void postUrlWithCallback(String url, String body, HttpHeaders headers, NetCallback netCallback){ PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread( RHODESAPP().canonicalizeRhoUrl(url), headers, body.getBytes(), null); thread.setNetCallback(netCallback); thread.start(); } void saveCurrentLocation(String url) { if (RhoConf.getInstance().getBool("KeepTrackOfLastVisitedPage")) { RhoConf.getInstance().setString("LastVisitedPage",url,true); LOG.TRACE("Saved LastVisitedPage: " + url); } } boolean restoreLocation() { LOG.TRACE("Restore Location to LastVisitedPage"); if (RhoConf.getInstance().getBool("KeepTrackOfLastVisitedPage")) { String url = RhoConf.getInstance().getString("LastVisitedPage"); if (url.length()>0) { LOG.TRACE("Navigating to LastVisitedPage: " + url); if ( _history.size() == 0 ) _history.addElement(url); navigateUrl(url); return true; } } return false; } public void navigateBack() { String url = ""; if ( _history.size() <= 1 ) { if ( RhoConf.getInstance().getBool("bb_disable_closebyback")) return; _mainScreen.close(); return; } int nPos = _history.size()-2; url = (String)_history.elementAt(nPos); _history.removeElementAt(nPos+1); // this.m_oBrowserAdapter.goBack(); saveCurrentLocation(url); navigateUrl(url); } /* void back() { String url = m_strAppBackUrl; if ( url.length() == 0) { if ( _history.size() <= 1 ) { if ( RhoConf.getInstance().getBool("bb_disable_closebyback")) return; _mainScreen.close(); return; } int nPos = _history.size()-2; url = (String)_history.elementAt(nPos); _history.removeElementAt(nPos+1); // this.m_oBrowserAdapter.goBack(); }else if ( url.equalsIgnoreCase("close")) { _mainScreen.close(); return; }else addToHistory(url,null); saveCurrentLocation(url); navigateUrl(url); }*/ String removeSemicolon(String str) { if ( str == null ) return null; int nCol = str.indexOf(';'); if ( nCol >= 0 ) return str.substring(0,nCol); return str; } public void addToHistory(String strUrl, String refferer ) { strUrl = removeSemicolon(strUrl); refferer = removeSemicolon(refferer); strUrl = RHODESAPP().canonicalizeRhoUrl(strUrl); // if ( !strUrl.startsWith(_httpRoot) && !isExternalUrl(strUrl) ) // strUrl = _httpRoot + (strUrl.startsWith("/") ? strUrl.substring(1) : strUrl); int nPos = -1; for( int i = 0; i < _history.size(); i++ ){ if ( strUrl.equalsIgnoreCase((String)_history.elementAt(i)) ){ nPos = i; break; } /*String strUrl1 = strUrl + "/index"; if ( strUrl1.equalsIgnoreCase((String)_history.elementAt(i)) ){ nPos = i; break; }*/ if ( refferer != null && refferer.equalsIgnoreCase((String)_history.elementAt(i)) ){ nPos = i; break; } } if ( nPos == -1 ){ boolean bReplace = RhoConnection.findIndex(strUrl) != -1; if ( bReplace ) _history.setElementAt(strUrl, _history.size()-1 ); else _history.addElement(strUrl); } else{ _history.setSize(nPos+1); _history.setElementAt(strUrl, _history.size()-1 ); } saveCurrentLocation(strUrl); } private boolean m_bOpenLink = false; private String m_strGetLink, m_strEmailMenu, m_strCallMenu, m_strChangeOptionMenu; boolean openLink(){ LOG.TRACE("openLink"); try{ m_bOpenLink = true; //TODO: catch by ID? if (m_strGetLink==null) { Version.SoftVersion ver = Version.getSoftVersion(); if ( ver.nMajor > 4 ) m_strGetLink = RhoAppAdapter.getMessageText("open_link_menu"); else m_strGetLink = RhoAppAdapter.getMessageText("get_link_menu"); } if (m_strEmailMenu==null) m_strEmailMenu = RhoAppAdapter.getMessageText("email_menu"); if (m_strCallMenu==null) m_strCallMenu = RhoAppAdapter.getMessageText("call_menu"); if (m_strChangeOptionMenu==null) m_strChangeOptionMenu = RhoAppAdapter.getMessageText("change_option_menu"); Menu menu = _mainScreen.getMenu(0); int size = menu.getSize(); for(int i=0; i<size; i++) { MenuItem item = menu.getItem(i); String label = item.toString(); if( label.equalsIgnoreCase(m_strGetLink) ||label.indexOf(m_strEmailMenu)>=0 || label.indexOf(m_strCallMenu)>=0 || label.equalsIgnoreCase(m_strChangeOptionMenu) ) { item.run(); return true; } } /* String strMenuItems = ""; for(int i=0; i<size; i++) { MenuItem item = menu.getItem(i); strMenuItems += item.toString() + ";"; } LOG.ERROR("Cannot find link menu item in menu: " + strMenuItems );*/ }finally { m_bOpenLink = false; } // MenuItem item = _mainScreen.getSavedGetLinkItem(); // if ( item != null ) { // item.run(); return false; } private IBrowserAdapter m_oBrowserAdapter; private CMainScreen _mainScreen = null; private SyncStatusPopup _syncStatusPopup = null; private String _lastStatusMessage = null; private String _hideStatus = null; //private HttpConnection _currentConnection; private Vector _history; private static boolean m_isFullBrowser = false; private static PushListeningThread _pushListeningThread = null; private static RhodesApplication _instance; public static RhodesApplication getInstance(){ return _instance; } private static RhodesApp RHODESAPP(){ return RhodesApp.getInstance(); } public static boolean isFullBrowser(){ return m_isFullBrowser; } void invalidateMainScreen() { _mainScreen.invalidate(); } static String m_strCmdLine = "", m_strSecurityToken = ""; public static void main(String[] args) { LOG.INFO_EVENT("main start"); try{ if ( args != null ) { for( int i = 0; i < args.length; i++) { if ( i > 0 ) m_strCmdLine += " "; m_strCmdLine += args[i]; if ( args[i].startsWith("security_token=") ) m_strSecurityToken = args[i].substring(15); } } _instance = new RhodesApplication(); LOG.INFO_EVENT( "RhodesApplication created" ); _instance.enterEventDispatcher(); }catch(Exception exc) { if ( RhoConf.getInstance() != null ) LOG.ERROR("Error in application.", exc); RhoConf.sendLog(); throw new RuntimeException("Application failed and will exit. Log will send to log server." + exc.toString()); }catch(Throwable e) { if ( RhoConf.getInstance() != null ) LOG.ERROR("Error in application.", e); RhoConf.sendLog(); throw new RuntimeException("Application failed and will exit. Log will send to log server." + e.toString()); } } void doClose(){ LOG.TRACE("Rhodes DO CLOSE *** onPlatformClose(); if ( _pushListeningThread != null ) _pushListeningThread.stop(); if ( ClientRegister.getInstance() != null ) ClientRegister.getInstance().Destroy(); if ( SyncThread.getInstance() != null ) SyncThread.getInstance().Destroy(); GeoLocation.stop(); RhoRuby.RhoRubyStop(); try{ RhoClassFactory.getNetworkAccess().close(); }catch(IOException exc){ LOG.ERROR(exc); } RhoLogger.close(); } private int m_activateHookNo = 0; private Hashtable m_activateHooks; public static abstract class ActivateHook { public abstract void run(); }; public int addActivateHook(ActivateHook hook) { synchronized(m_activateHooks) { int no = ++m_activateHookNo; m_activateHooks.put(new Integer(no), hook); return no; } } public void removeActivateHook(int no) { synchronized (m_activateHooks) { m_activateHooks.remove(new Integer(no)); } } private void runActivateHooks() { synchronized(m_activateHooks) { if (m_activateHooks != null && m_activateHooks.size() != 0) { Enumeration e = m_activateHooks.elements(); while(e.hasMoreElements()) { ActivateHook hook = (ActivateHook)e.nextElement(); hook.run(); } m_activateHooks.clear(); return; } } } private static Object m_eventRubyInit = new Object(); private static boolean m_bRubyInit = false; public void activate() { if (!m_bActivate) rhodes_activate(); else RhoRuby.rho_ruby_activateApp(); super.activate(); } private boolean m_bActivate = false; private void rhodes_activate() { if ( !m_bStartupFinish ) { this.invokeLater( new Runnable() { public void run() { //LOG.INFO_EVENT("Activate wait till Startup finish"); rhodes_activate(); } }, 100, false ); return; } m_bActivate = true; //DO NOT DO ANYTHING before doStartupWork //doStartupWork(); showSplashScreen(); LOG.TRACE("Rhodes start activate *** UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { if ( !m_bRubyInit ) { synchronized (m_eventRubyInit) { try{ m_eventRubyInit.wait(); }catch(Exception e) { LOG.ERROR("wait failed", e); } } } if ( !RhoRuby.rho_ruby_isValid() ) { LOG.ERROR("Cannot initialize Rho framework. Application will exit."); Dialog.alert("Cannot initialize Rho framework. Application will exit. Log will send to log server."); RhoConf.sendLog(); System.exit(1); } runActivateHooks(); RhoRuby.rho_ruby_activateApp(); if(!restoreLocation()) { navigateHome(); } onPlatformActivate(); LOG.TRACE("Rhodes end activate *** } }); super.activate(); } void initRuby()throws Exception { try { RhoRuby.RhoRubyStart(""); com.rho.db.DBAdapter.initAttrManager(); SyncThread sync = null; try{ sync = SyncThread.Create( new RhoClassFactory() ); }catch(Exception exc){ LOG.ERROR("Create sync failed.", exc); } if (sync != null) { sync.setStatusListener(this); } RhoRuby.RhoRubyInitApp(); RhoRuby.call_config_conflicts(); RhoConf.getInstance().conflictsResolved(); }finally { m_bRubyInit = true; synchronized (m_eventRubyInit) { m_eventRubyInit.notifyAll(); } } } public void deactivate() { LOG.TRACE("Rhodes deactivate *** RhoRuby.rho_ruby_deactivateApp(); // SyncEngine.stop(null); GeoLocation.stop(); RingtoneManager.stop(); super.deactivate(); } synchronized public void setSyncStatusPopup(SyncStatusPopup popup) { _syncStatusPopup = popup; if (_syncStatusPopup != null) { _syncStatusPopup.showStatus(_lastStatusMessage); } else { _lastStatusMessage = null; } } synchronized public void showStatus(String status, String hide) { _lastStatusMessage = status; _hideStatus = hide; invokeLater( new Runnable() { public void run() { if (_syncStatusPopup != null) { _syncStatusPopup.showStatus(_lastStatusMessage); }else { SyncStatusPopup popup = new SyncStatusPopup(_lastStatusMessage, _hideStatus); RhodesApplication.getInstance().setSyncStatusPopup(popup); pushScreen(popup); } } }); } synchronized public void reportStatus(String status, int error) { _lastStatusMessage = status; //LOG.INFO("Sync status: " + status); //if (_syncStatusPopup == null && error != 0) { // createStatusPopup(); //} else invokeLater( new Runnable() { public void run() { if (_syncStatusPopup != null) { _syncStatusPopup.showStatus(_lastStatusMessage); }else { SyncStatusPopup popup = new SyncStatusPopup(_lastStatusMessage, null); RhodesApplication.getInstance().setSyncStatusPopup(popup); pushScreen(popup); } } }); } public void createStatusPopup(String status) { _lastStatusMessage = status; invokeLater( new Runnable() { public void run() { if (_syncStatusPopup == null) { SyncStatusPopup popup = new SyncStatusPopup(_lastStatusMessage, null); RhodesApplication.getInstance().setSyncStatusPopup(popup); pushScreen(popup); } } }); } static class SyncStatusPopup extends PopupScreen { LabelField _labelStatus; public SyncStatusPopup(String status, String hide) { super( new VerticalFieldManager( Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR) ); add(_labelStatus = new LabelField(status != null ? status : "", Field.FIELD_HCENTER)); add(new LabelField("")); if ( hide == null ) hide = RhoAppAdapter.getMessageText("hide"); ButtonField hideButton = new ButtonField( hide, Field.FIELD_HCENTER ); hideButton.setChangeListener( new HideListener(this) ); add(hideButton); } public void showStatus(String status) { if (status == null) return; //synchronized (Application.getEventLock()) { _labelStatus.setText(status); } protected boolean keyDown( int keycode, int status ) { if ( Keypad.key( keycode ) == Keypad.KEY_ESCAPE ) { close(); RhodesApplication.getInstance().setSyncStatusPopup(null); return true; } return super.keyDown( keycode, status ); } private class HideListener implements FieldChangeListener { SyncStatusPopup owner; public HideListener(SyncStatusPopup _owner) { super(); owner = _owner; } public void fieldChanged(Field field, int context) { owner.close(); RhodesApplication.getInstance().setSyncStatusPopup(null); } } } class CMainScreen extends RhoMainScreen{ protected boolean navigationMovement(int dx, int dy, int status, int time) { if (m_oBrowserAdapter.navigationMovement(dx, dy, status, time)) { updateLayout(); return true; } return super.navigationMovement(dx, dy, status, time); } int m_nOrientation = -1; protected void onChangeOrientation(int x, int y, int nOrientation) { if ( m_nOrientation == -1 ) { m_nOrientation = nOrientation; return; } if ( m_nOrientation != nOrientation && m_bRubyInit ) { try{ RhodesApp.getInstance().callScreenRotationCallback(x, y, m_nOrientation==1 ? 90 : -90); }catch(Exception exc) { LOG.ERROR("Screen rotation callback failed.", exc); } //this.invalidate(); //this.updateDisplay(); } m_nOrientation = nOrientation; } protected boolean navigationClick(int status, int time) { //LOG.INFO("navigationClick: " + status); return super.navigationClick(status, time); } protected boolean onTouchUnclick() { return openLink(); } private Vector menuItems = new Vector(); private MenuItem homeItem = new MenuItem("", 200000, 10) { public void run() { navigateHome(); } }; private MenuItem refreshItem = new MenuItem("", 200000, 10) { public void run() { refreshCurrentPage(); } }; private MenuItem backItem = new MenuItem("", 200000, 10) { public void run() { //back(); RHODESAPP().navigateBack(); } }; private MenuItem syncItem = new MenuItem("", 200000, 10) { public void run() { //RhodesApplication.getInstance().createStatusPopup(); SyncThread.doSyncAllSources(true); } }; private MenuItem optionsItem = new MenuItem("", 200000, 10) { public void run() { String curUrl = RhoRuby.getOptionsPage(); curUrl = RHODESAPP().canonicalizeRhoUrl(curUrl); addToHistory(curUrl, null ); navigateUrl(curUrl); } }; private MenuItem logItem = new MenuItem("", 200000, 10) { public void run() { showLogScreen(); } }; private MenuItem separatorItem = MenuItem.separator(200000); private MenuItem closeItem = new MenuItem("", 200000, 10) { public void run() { close(); } }; private MenuItem savedGetLinkItem = null; protected void makeMenu(Menu menu, int instance) { if (m_bOpenLink) { super.makeMenu(menu, instance); return; } menu.deleteAll(); // Don't draw menu if menuItems is null if (menuItems == null) return; ContextMenu contextMenu = ContextMenu.getInstance(); contextMenu.clear(); // Draw default menu if (menuItems != null && menuItems.size() == 0) { updateMenuItemsLabel(); contextMenu.addItem(homeItem); contextMenu.addItem(refreshItem); contextMenu.addItem(syncItem); contextMenu.addItem(optionsItem); contextMenu.addItem(logItem); contextMenu.addItem(separatorItem); contextMenu.addItem(closeItem); } // Draw menu from rhodes framework Enumeration elements = menuItems.elements(); while (elements.hasMoreElements()) { MenuItem item = (MenuItem)elements.nextElement(); contextMenu.addItem(item); } this.makeContextMenu(contextMenu); menu.add(contextMenu); } public void addCustomMenuItem(String label, final String value) { final String _label = label; // Is this a default item? If so, use the existing menu item we have. if (value.equalsIgnoreCase(RhodesApplication.LABEL_BACK)) { setDefaultItemToMenuItems(label, backItem); }else if ( label.equalsIgnoreCase("back") ){ RHODESAPP().setAppBackUrl(value); }else if (value.equalsIgnoreCase(RhodesApplication.LABEL_HOME)) { setDefaultItemToMenuItems(label, homeItem); } else if (value.equalsIgnoreCase(RhodesApplication.LABEL_REFRESH)) { setDefaultItemToMenuItems(label, refreshItem); } else if (value.equalsIgnoreCase(RhodesApplication.LABEL_SYNC)) { setDefaultItemToMenuItems(label, syncItem); } else if (value.equalsIgnoreCase(RhodesApplication.LABEL_OPTIONS)) { setDefaultItemToMenuItems(label, optionsItem); } else if (value.equalsIgnoreCase(RhodesApplication.LABEL_LOG)) { setDefaultItemToMenuItems(label, logItem); } else if (label.equalsIgnoreCase(RhodesApplication.LABEL_SEPARATOR) || (value != null && value.equalsIgnoreCase(RhodesApplication.LABEL_SEPARATOR))) { menuItems.addElement(separatorItem); } else if (value.equalsIgnoreCase(RhodesApplication.LABEL_CLOSE) || value.equalsIgnoreCase(RhodesApplication.LABEL_EXIT)) { setDefaultItemToMenuItems(label, closeItem); } else if (label.equalsIgnoreCase(RhodesApplication.LABEL_NONE)) { menuItems = null; } else { MenuItem itemToAdd = new MenuItem(label, 200000, 10) { public void run() { try{ RHODESAPP().loadUrl(value); }catch(Exception exc) { LOG.ERROR("Execute menu item: '" + _label + "' failed.", exc); } /* if (value != null && value.startsWith("callback:") ) { String url = RHODESAPP().canonicalizeRhoUrl(value.substring(9)); RhoRubyHelper helper = new RhoRubyHelper(); helper.postUrl(url, ""); }else { String url = RHODESAPP().canonicalizeRhoUrl(value); addToHistory(url, null ); navigateUrl(url); }*/ } }; menuItems.addElement(itemToAdd); } } void updateMenuItemsLabel() { homeItem.setText(RhoAppAdapter.getMessageText("home_menu")); refreshItem.setText(RhoAppAdapter.getMessageText("refresh_menu")); backItem.setText(RhoAppAdapter.getMessageText("back_menu")); syncItem.setText(RhoAppAdapter.getMessageText("sync_menu")); optionsItem.setText(RhoAppAdapter.getMessageText("options_menu")); logItem.setText(RhoAppAdapter.getMessageText("log_menu")); closeItem.setText(RhoAppAdapter.getMessageText("close_menu")); } private void setDefaultItemToMenuItems(String label, MenuItem item) { item.setText(label); menuItems.addElement(item); } public void close() { LOG.TRACE("Calling Screen.close"); if (com.rho.Capabilities.RUNAS_SERVICE) Application.getApplication().requestBackground(); else { doClose(); super.close(); } } /* public boolean onClose() { doClose(); return super.onClose(); //System.exit(0); //return true; }*/ public boolean onMenu(int instance) { // TODO Auto-generated method stub return super.onMenu(instance); } public Vector getMenuItems() { return menuItems; } public void setMenuItems(Vector menuItems) { this.menuItems = menuItems; } public MenuItem getSavedGetLinkItem() { return savedGetLinkItem; } } public void showSplashScreen() { SplashScreen splash = RHODESAPP().getSplashScreen(); InputStream is = null; try { RubyProgram obj = new xruby.version.main(); String pngname = "/apps/app/loading.png"; String pngbbname = "/apps/app/loading.bb.png"; is = obj.getClass().getResourceAsStream(pngbbname); if (is == null) { is = obj.getClass().getResourceAsStream(pngname); } if ( is != null ) { int size = is.available(); byte[] data = new byte[size]; for (int offset = 0; offset < size;) { int n = is.read(data, offset, size - offset); if (n < 0) break; offset += n; } EncodedImage img = EncodedImage.createEncodedImage(data, 0, size); long nFlags = 0; if (splash.isFlag(SplashScreen.HCENTER) ) nFlags |= Field.FIELD_HCENTER; if (splash.isFlag(SplashScreen.VCENTER) ) nFlags |= Field.FIELD_VCENTER; int scaleX = 65536, scaleY = 65536; int currentWidthFixed32 = Fixed32.toFP(img.getWidth()); int currentHeightFixed32 = Fixed32.toFP(img.getHeight()); int screenWidthFixed32 = Fixed32.toFP(Display.getWidth()); int screenHeightFixed32 = Fixed32.toFP(Display.getHeight()); if (splash.isFlag(SplashScreen.VZOOM) ) scaleY = Fixed32.div(currentHeightFixed32, screenHeightFixed32); else scaleY = Fixed32.div(currentHeightFixed32, currentHeightFixed32); if (splash.isFlag(SplashScreen.HZOOM) ) scaleX = Fixed32.div(currentWidthFixed32, screenWidthFixed32); else scaleX = Fixed32.div(currentWidthFixed32, currentWidthFixed32); EncodedImage img2 = img; if ( scaleX != 65536 || scaleY != 65536) img2 = img.scaleImage32(scaleX, scaleY); Bitmap bitmap = img2.getBitmap(); splash.start(); BitmapField imageField = new BitmapField(bitmap, nFlags); _mainScreen.deleteAll(); _mainScreen.add(imageField); } } catch (Exception e) { LOG.ERROR("Can't show splash screen", e); }finally { if ( is != null ) try{is.close();}catch(IOException exc){} is = null; } pushScreen(_mainScreen); } public void showLogScreen() { LogScreen screen = new LogScreen(); //Push this screen to display it to the user. UiApplication.getUiApplication().pushScreen(screen); } boolean m_bStartupFinish = false; private void doStartupWork() { /* if (_mainScreen!=null) return; if ( com.rho.Capabilities.RUNAS_SERVICE && ApplicationManager.getApplicationManager().inStartup() )// || isWaitForSDCardAtStartup() ) { this.invokeLater( new Runnable() { public void run() { doStartupWork(); } } ); return; }*/ try{ if ( com.rho.Capabilities.RUNAS_SERVICE ) { while( ApplicationManager.getApplicationManager().inStartup() ) { LOG.INFO_EVENT("inStartup"); Thread.sleep(1000); } if ( !Jsr75File.isSDCardExist() ) { LOG.INFO_EVENT("isSDCardExist"); Thread.sleep(5000); //Wait till SDCard may appear } } RhoLogger.InitRhoLog(); if ( AppBuildConfig.getItem("security_token") != null && AppBuildConfig.getItem("security_token").compareTo(m_strSecurityToken) != 0) { LOG.INFO("This is hidden app and can be started only with security key."); System.exit(0); return; } LOG.INFO(" STARTING RHODES: *** RhodesApp.setStartParameters(m_strCmdLine); RhodesApp.Create(RhoConf.getInstance().getRhoRootPath()); CKeyListener list = new CKeyListener(); CTrackwheelListener wheel = new CTrackwheelListener(); this._history = new Vector(); synchronized (Application.getEventLock()) { _mainScreen = new CMainScreen(); _mainScreen.addKeyListener(list); _mainScreen.addTrackwheelListener(wheel); //pushScreen(_mainScreen); createBrowserControl(); } LOG.INFO_EVENT("createBrowserControl" ); try { RhoClassFactory.getNetworkAccess().configure(); } catch(IOException exc) { LOG.ERROR(exc.getMessage()); } LOG.INFO_EVENT("getNetworkAccess"); //PrimaryResourceFetchThread.Create(this); LOG.INFO("RHODES STARTUP COMPLETED: *** m_bStartupFinish = true; if ( com.rho.Capabilities.RUNAS_SERVICE && !m_bActivate && RhoConf.getInstance().getBool("activate_at_startup")) { this.invokeLater( new Runnable() { public void run() { rhodes_activate(); } }); } }catch(Exception exc) { LOG.ERROR("doStartupWork failed", exc); LOG.ERROR_EVENT("doStartupWork failed", exc); }catch(Throwable exc) { LOG.ERROR("doStartupWork crashed.", exc); LOG.ERROR_EVENT("doStartupWork failed", exc); return; } } public void executeJavascript(String strJavascript) { final String url = strJavascript; this.invokeLater( new Runnable() { public void run() { m_oBrowserAdapter.executeJavascript(url); } } ); } private Hashtable cookies = new Hashtable(); public String getCookie(String url) { URI uri = new URI(url); String baseUrl = uri.getPathNoFragmentNoQuery(); Object c = cookies.get(baseUrl); if (c instanceof String) return (String)c; return null; } public void setCookie(String url, String cookie) { URI uri = new URI(url); String baseUrl = uri.getPathNoFragmentNoQuery(); cookies.put(baseUrl, cookie); m_oBrowserAdapter.setCookie(url, cookie); } private void createBrowserControl() { //touch;5 String strFullBrowser = RhoConf.getInstance().getString("use_bb_full_browser"); boolean bTouch = strFullBrowser.indexOf("touch") >= 0; boolean bBB5 = strFullBrowser.indexOf("5") >= 0; if ( bTouch || bBB5 ) { if ( bTouch ) m_isFullBrowser = _mainScreen.isTouchScreen(); if (!m_isFullBrowser && bBB5 ) { Version.SoftVersion ver = Version.getSoftVersion(); m_isFullBrowser = ver.nMajor >= 5; } }else if ( RhoConf.getInstance().getBool("use_bb_full_browser") ) { Version.SoftVersion ver = Version.getSoftVersion(); if ( ver.nMajor > 4 || ( ver.nMajor == 4 && ver.nMinor >= 6 ) ) m_isFullBrowser = true; } if ( m_isFullBrowser ) { Version.SoftVersion ver = Version.getSoftVersion(); if ( ver.nMajor >= 5 ) m_oBrowserAdapter = new BrowserAdapter5(_mainScreen, this); else m_oBrowserAdapter = new BrowserAdapter(_mainScreen, this, RhoConf.getInstance().getBool("bb_loadimages_async") ); m_oBrowserAdapter.setFullBrowser(); }else m_oBrowserAdapter = new BrowserAdapter(_mainScreen, this, RhoConf.getInstance().getBool("bb_loadimages_async")); } // SystemListener methods public void powerUp() { LOG.INFO_EVENT("POWER UP" ); if ( com.rho.Capabilities.RUNAS_SERVICE) { //invokeStartupWork(); this.requestBackground(); } } public void powerOff() { LOG.TRACE(" POWER DOWN *** // _mainScreen = null; // doClose(); } public void batteryLow() { } public void batteryGood() { } public void batteryStatusChange(int status) { } // end of SystemListener methods private RhodesApplication() { LOG.INFO_OUT(" Construct RhodesApplication() *** m_activateHooks = new Hashtable(); this.addSystemListener(this); PrimaryResourceFetchThread.Create(this); //this.addFileSystemListener(this); /* if ( com.rho.Capabilities.RUNAS_SERVICE && ApplicationManager.getApplicationManager().inStartup() ) { EventLogger.logEvent(0x4c9d3452d87922f2L, "inStartup".getBytes()); LOG.INFO_OUT("We are in the phone startup, don't start Rhodes yet, leave it to power up call"); } else { invokeStartupWork(); }*/ } public void refreshCurrentPage(){ navigateUrl((String)_history.lastElement()); } void navigateHome() { String strHomePage = RhoRuby.getStartPage(); String strStartPage = RhodesApp.getInstance().canonicalizeRhoUrl(strHomePage); _history.removeAllElements(); _history.addElement(strStartPage); navigateUrl(strStartPage); } public void close() { this.invokeLater(new Runnable() { public void run() { _mainScreen.close(); } }); } public void processConnection(HttpConnection connection, Object e) { // cancel previous request /*if (_currentConnection != null) { try { _currentConnection.close(); } catch (IOException e1) { } } _currentConnection = connection;*/ RHODESAPP().getSplashScreen().hide(); m_oBrowserAdapter.processConnection(connection, e); } public static class PrimaryResourceFetchThread {//extends Thread { private static class HttpServerThread extends RhoThread { private Object m_mxStackCommands;// = new Mutex(); private LinkedList m_stackCommands = new LinkedList(); boolean m_bExit = false; private static final int INTERVAL_INFINITE = Integer.MAX_VALUE/1000; static final int WAIT_BEFOREKILL_SECONDS = 3; HttpServerThread() { super(new RhoClassFactory()); m_mxStackCommands = getSyncObject(); start(epNormal); } public void run() { _application.doStartupWork(); if (!_application.m_bStartupFinish) { return; } LOG.INFO( "Starting HttpServerThread main routine..." ); //wait(80); try{ _application.initRuby(); }catch(Exception e) { LOG.ERROR("initRuby failed.", e); return; }catch(Throwable exc) { LOG.ERROR("initRuby crashed.", exc); return; } if ( com.rho.Capabilities.ENABLE_PUSH ) { if ( PushListeningThread.isMDSPushEnabled() ) { _pushListeningThread = new PushListeningThread(); _pushListeningThread.start(); } } while( !m_bExit ) { while(!m_stackCommands.isEmpty()) { PrimaryResourceFetchThread oCmd = null; synchronized(m_mxStackCommands) { oCmd = (PrimaryResourceFetchThread)m_stackCommands.removeFirst(); } try{ oCmd.processCommand(); }catch(Exception e) { LOG.ERROR("Process command failed.", e); }catch(Throwable exc) { LOG.ERROR("Process command crashed.", exc); } } synchronized(m_mxStackCommands) { if ( m_stackCommands.isEmpty() ) wait(INTERVAL_INFINITE); } } LOG.INFO( "Exit HttpServerThread main routine..." ); } void addCommand(PrimaryResourceFetchThread oCmd) { synchronized(m_mxStackCommands) { m_stackCommands.add(oCmd); } stopWait(); } }; private static HttpServerThread m_oFetchThread; private static RhodesApplication _application; private static Runnable _callback; private Object _event; private byte[] _postData; private HttpHeaders _requestHeaders; private String _url; private boolean m_bInternalRequest = false; private boolean m_bActivateApp = false; NetCallback m_netCallback; public void setInternalRequest(boolean b) { m_bInternalRequest = b; } public PrimaryResourceFetchThread(String url, HttpHeaders requestHeaders, byte[] postData, Object event) { _url = url; _requestHeaders = requestHeaders; _postData = postData; _event = event; //_callback = null; } public PrimaryResourceFetchThread(String url, HttpHeaders requestHeaders, byte[] postData, Object event, Runnable callback) { _url = url; _requestHeaders = requestHeaders; _postData = postData; _event = event; if ( callback != null ) _callback = callback; } public void setNetCallback(NetCallback netCallback) { m_netCallback = netCallback; m_bInternalRequest = true; } public PrimaryResourceFetchThread(boolean bActivateApp) { m_bActivateApp = bActivateApp; } static void Create(RhodesApplication app) { if ( m_oFetchThread != null ) return; _application = app; m_oFetchThread = new HttpServerThread(); } public void Destroy() { m_oFetchThread.m_bExit = true; m_oFetchThread.stop(HttpServerThread.WAIT_BEFOREKILL_SECONDS); m_oFetchThread = null; } public void start() { m_oFetchThread.addCommand(this); } static class RhoTextMessage implements javax.wireless.messaging.TextMessage { String m_strAddress = "", m_strBody = ""; RhoTextMessage(String strAddr, String strBody) { super(); m_strAddress = strAddr; m_strBody = strBody; } public String getPayloadText() { return m_strBody; } public void setPayloadText(String arg0) { m_strBody = arg0; } public String getAddress() { return m_strAddress; } public Date getTimestamp() { return null; } public void setAddress(String addr) { m_strAddress = addr; } }; void processCommand()throws IOException { if ( m_bActivateApp ) { RhoRuby.rho_ruby_activateApp(); return; } URI uri = new URI(_url); String strMsgBody = ""; String query = uri.getQueryString(); if (query != null) { StringParser tok = new StringParser(query, "&"); while (tok.hasMoreElements()) { String pair = (String)tok.nextElement(); StringParser nv = new StringParser(pair, "="); String name = (String)nv.nextElement(); String value = (String)nv.nextElement(); if (name == null || value == null) continue; if (name.equals("rho_open_target") && value.equals("_blank")) { RhoRubyHelper helper = new RhoRubyHelper(); helper.open_url(_url); return; } if (name.equals("body")) { strMsgBody = value; } } } if ( uri.getScheme().equalsIgnoreCase("sms")) { RhoTextMessage msg = new RhoTextMessage(uri.getPath(), URI.urlDecode(strMsgBody) ); MessageArguments args = new MessageArguments( msg ); Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, args); return; } HttpConnection connection = Utilities.makeConnection(_url, _requestHeaders, _postData, null); if ( m_bInternalRequest ) { try{ int nRespCode = connection.getResponseCode(); if ( m_netCallback != null ) { String strRespBody = ""; InputStream is = connection.openInputStream(); if ( is != null ) { byte[] buffer = new byte[is.available()]; is.read(buffer); strRespBody = new String(buffer); } m_netCallback.setResponse( new NetResponse(strRespBody, nRespCode) ); } }catch(IOException exc) { LOG.ERROR("Callback failed: " + _url, exc); if ( m_netCallback != null ) m_netCallback.setResponse( new NetResponse("", 500) ); } } else { _application.processConnection(connection, _event); } if (_callback != null ) { _callback.run(); _callback = null; } } } }
package com.intellij.ui; import com.intellij.icons.AllIcons; import com.intellij.jna.JnaLoader; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationActivationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.AppIconScheme; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.util.IconUtil; import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.UIUtil; import com.sun.jna.platform.win32.WinDef; import org.apache.commons.imaging.common.BinaryOutputStream; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.geom.Area; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteOrder; import java.util.HashMap; import java.util.Map; public abstract class AppIcon { private static final Logger LOG = Logger.getInstance(AppIcon.class); private static AppIcon ourIcon; @NotNull public static AppIcon getInstance() { if (ourIcon == null) { if (SystemInfo.isMac) { ourIcon = new MacAppIcon(); } else if (SystemInfo.isWin7OrNewer && JnaLoader.isLoaded()) { ourIcon = new Win7AppIcon(); } else { ourIcon = new EmptyIcon(); } } return ourIcon; } public abstract boolean setProgress(Project project, Object processId, AppIconScheme.Progress scheme, double value, boolean isOk); public abstract boolean hideProgress(Project project, Object processId); public abstract void setErrorBadge(Project project, String text); public abstract void setOkBadge(Project project, boolean visible); public abstract void requestAttention(@Nullable Project project, boolean critical); public abstract void requestFocus(IdeFrame frame); private static abstract class BaseIcon extends AppIcon { private ApplicationActivationListener myAppListener; protected Object myCurrentProcessId; protected double myLastValue; @Override public final boolean setProgress(Project project, Object processId, AppIconScheme.Progress scheme, double value, boolean isOk) { if (!isAppActive() && Registry.is("ide.appIcon.progress") && (myCurrentProcessId == null || myCurrentProcessId.equals(processId))) { return _setProgress(getIdeFrame(project), processId, scheme, value, isOk); } else { return false; } } @Override public final boolean hideProgress(Project project, Object processId) { if (Registry.is("ide.appIcon.progress")) { return _hideProgress(getIdeFrame(project), processId); } else { return false; } } @Override public final void setErrorBadge(Project project, String text) { if (!isAppActive() && Registry.is("ide.appIcon.badge")) { _setOkBadge(getIdeFrame(project), false); _setTextBadge(getIdeFrame(project), text); } } @Override public final void setOkBadge(Project project, boolean visible) { if (!isAppActive() && Registry.is("ide.appIcon.badge")) { _setTextBadge(getIdeFrame(project), null); _setOkBadge(getIdeFrame(project), visible); } } @Override public final void requestAttention(@Nullable Project project, boolean critical) { if (!isAppActive() && Registry.is("ide.appIcon.requestAttention")) { _requestAttention(getIdeFrame(project), critical); } } public abstract boolean _setProgress(IdeFrame frame, Object processId, AppIconScheme.Progress scheme, double value, boolean isOk); public abstract boolean _hideProgress(IdeFrame frame, Object processId); public abstract void _setTextBadge(IdeFrame frame, String text); public abstract void _setOkBadge(IdeFrame frame, boolean visible); public abstract void _requestAttention(IdeFrame frame, boolean critical); protected abstract IdeFrame getIdeFrame(@Nullable Project project); private boolean isAppActive() { Application app = ApplicationManager.getApplication(); if (app != null && myAppListener == null) { myAppListener = new ApplicationActivationListener() { @Override public void applicationActivated(@NotNull IdeFrame ideFrame) { if (Registry.is("ide.appIcon.progress")) { _hideProgress(ideFrame, myCurrentProcessId); } _setOkBadge(ideFrame, false); _setTextBadge(ideFrame, null); } }; app.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC, myAppListener); } return app != null && app.isActive(); } } @SuppressWarnings("UseJBColor") static class MacAppIcon extends BaseIcon { private BufferedImage myAppImage; private final Map<Object, AppImage> myProgressImagesCache = new HashMap<>(); private BufferedImage getAppImage() { assertIsDispatchThread(); try { if (myAppImage != null) return myAppImage; Object app = getApp(); Image appImage = (Image)getAppMethod("getDockIconImage").invoke(app); if (appImage == null) return null; myAppImage = ImageUtil.toBufferedImage(appImage); } catch (NoSuchMethodException e) { return null; } catch (Exception e) { LOG.error(e); } return myAppImage; } @Override public void _setTextBadge(IdeFrame frame, String text) { assertIsDispatchThread(); try { getAppMethod("setDockIconBadge", String.class).invoke(getApp(), text); } catch (NoSuchMethodException ignored) { } catch (Exception e) { LOG.error(e); } } @Override public void requestFocus(IdeFrame frame) { assertIsDispatchThread(); try { getAppMethod("requestForeground", boolean.class).invoke(getApp(), true); } catch (NoSuchMethodException ignored) { } catch (Exception e) { LOG.error(e); } } @Override public void _requestAttention(IdeFrame frame, boolean critical) { assertIsDispatchThread(); try { getAppMethod("requestUserAttention", boolean.class).invoke(getApp(), critical); } catch (NoSuchMethodException ignored) { } catch (Exception e) { LOG.error(e); } } @Override protected IdeFrame getIdeFrame(@Nullable Project project) { return null; } @Override public boolean _hideProgress(IdeFrame frame, Object processId) { assertIsDispatchThread(); if (getAppImage() == null) return false; if (myCurrentProcessId != null && !myCurrentProcessId.equals(processId)) return false; setDockIcon(getAppImage()); myProgressImagesCache.remove(myCurrentProcessId); myCurrentProcessId = null; myLastValue = 0; return true; } @Override public void _setOkBadge(IdeFrame frame, boolean visible) { assertIsDispatchThread(); if (getAppImage() == null) return; AppImage img = createAppImage(); if (visible) { Icon okIcon = AllIcons.Mac.AppIconOk512; int myImgWidth = img.myImg.getWidth(); if (myImgWidth != 128) { okIcon = IconUtil.scale(okIcon, frame != null ? frame.getComponent() : null, myImgWidth / 128f); } int x = myImgWidth - okIcon.getIconWidth(); int y = 0; okIcon.paintIcon(JOptionPane.getRootFrame(), img.myG2d, x, y); } setDockIcon(img.myImg); } // white 80% transparent private static final Color PROGRESS_BACKGROUND_COLOR = new Color(255, 255, 255, 217); private static final Color PROGRESS_OUTLINE_COLOR = new Color(140, 139, 140); @Override public boolean _setProgress(IdeFrame frame, Object processId, AppIconScheme.Progress scheme, double value, boolean isOk) { assertIsDispatchThread(); if (getAppImage() == null) return false; myCurrentProcessId = processId; if (myLastValue > value) return true; if (Math.abs(myLastValue - value) < 0.02d) return true; try { double progressHeight = (myAppImage.getHeight() * 0.13); double xInset = (myAppImage.getWidth() * 0.05); double yInset = (myAppImage.getHeight() * 0.15); final double width = myAppImage.getWidth() - xInset * 2; final double y = myAppImage.getHeight() - progressHeight - yInset; Area borderArea = new Area( new RoundRectangle2D.Double( xInset - 1, y - 1, width + 2, progressHeight + 2, (progressHeight + 2), (progressHeight + 2 ))); Area backgroundArea = new Area(new Rectangle2D.Double(xInset, y, width, progressHeight)); backgroundArea.intersect(borderArea); Area progressArea = new Area(new Rectangle2D.Double(xInset + 1, y + 1,(width - 2) * value, progressHeight - 1)); progressArea.intersect(borderArea); AppImage appImg = myProgressImagesCache.get(myCurrentProcessId); if (appImg == null) myProgressImagesCache.put(myCurrentProcessId, appImg = createAppImage()); appImg.myG2d.setColor(PROGRESS_BACKGROUND_COLOR); appImg.myG2d.fill(backgroundArea); final Color color = isOk ? scheme.getOkColor() : scheme.getErrorColor(); appImg.myG2d.setColor(color); appImg.myG2d.fill(progressArea); appImg.myG2d.setColor(PROGRESS_OUTLINE_COLOR); appImg.myG2d.draw(backgroundArea); appImg.myG2d.draw(borderArea); setDockIcon(appImg.myImg); myLastValue = value; } catch (Exception e) { LOG.error(e); } finally { myCurrentProcessId = null; } return true; } private AppImage createAppImage() { BufferedImage appImage = getAppImage(); assert appImage != null; @SuppressWarnings("UndesirableClassUsage") BufferedImage current = new BufferedImage(appImage.getWidth(), appImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = current.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); UIUtil.drawImage(g, appImage, 0, 0, null); return new AppImage(current, g); } private static class AppImage { BufferedImage myImg; Graphics2D myG2d; AppImage(BufferedImage img, Graphics2D g2d) { myImg = img; myG2d = g2d; } } static void setDockIcon(BufferedImage image) { try { getAppMethod("setDockIconImage", Image.class).invoke(getApp(), image); } catch (Exception e) { LOG.error(e); } } private static Method getAppMethod(final String name, Class... args) throws NoSuchMethodException, ClassNotFoundException { return getAppClass().getMethod(name, args); } private static Object getApp() throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { return getAppClass().getMethod("getApplication").invoke(null); } private static Class<?> getAppClass() throws ClassNotFoundException { return Class.forName("com.apple.eawt.Application"); } } @SuppressWarnings("UseJBColor") private static class Win7AppIcon extends BaseIcon { @Override public boolean _setProgress(IdeFrame frame, Object processId, AppIconScheme.Progress scheme, double value, boolean isOk) { myCurrentProcessId = processId; if (Math.abs(myLastValue - value) < 0.02d) { return true; } try { if (isValid(frame)) { Win7TaskBar.setProgress(frame, value, isOk); } } catch (Throwable e) { LOG.error(e); } myLastValue = value; myCurrentProcessId = null; return true; } @Override public boolean _hideProgress(IdeFrame frame, Object processId) { if (myCurrentProcessId != null && !myCurrentProcessId.equals(processId)) { return false; } try { if (isValid(frame)) { Win7TaskBar.hideProgress(frame); } } catch (Throwable e) { LOG.error(e); } myCurrentProcessId = null; myLastValue = 0; return true; } private static byte[] writeTransparentIco(BufferedImage src) throws IOException { LOG.assertTrue(BufferedImage.TYPE_INT_ARGB == src.getType() || BufferedImage.TYPE_4BYTE_ABGR == src.getType()); int bitCount = 32; try (ByteArrayOutputStream os = new ByteArrayOutputStream(); BinaryOutputStream bos = new BinaryOutputStream(os, ByteOrder.LITTLE_ENDIAN)) { int scan_line_size = (bitCount * src.getWidth() + 7) / 8; if ((scan_line_size % 4) != 0) scan_line_size += 4 - (scan_line_size % 4); // pad scan line to 4 byte size. int t_scan_line_size = (src.getWidth() + 7) / 8; if ((t_scan_line_size % 4) != 0) t_scan_line_size += 4 - (t_scan_line_size % 4); // pad scan line to 4 byte size. int imageSize = 40 + src.getHeight() * scan_line_size + src.getHeight() * t_scan_line_size; // ICONDIR bos.write2Bytes(0); // reserved bos.write2Bytes(1); // 1=ICO, 2=CUR bos.write2Bytes(1); // count // ICONDIRENTRY int iconDirEntryWidth = src.getWidth(); int iconDirEntryHeight = src.getHeight(); if (iconDirEntryWidth > 255 || iconDirEntryHeight > 255) { iconDirEntryWidth = 0; iconDirEntryHeight = 0; } bos.write(iconDirEntryWidth); bos.write(iconDirEntryHeight); bos.write(0); bos.write(0); // reserved bos.write2Bytes(1); // color planes bos.write2Bytes(bitCount); bos.write4Bytes(imageSize); bos.write4Bytes(22); // image offset // BITMAPINFOHEADER bos.write4Bytes(40); // size bos.write4Bytes(src.getWidth()); bos.write4Bytes(2 * src.getHeight()); bos.write2Bytes(1); // planes bos.write2Bytes(bitCount); bos.write4Bytes(0); // compression bos.write4Bytes(0); // image size bos.write4Bytes(0); // x pixels per meter bos.write4Bytes(0); // y pixels per meter bos.write4Bytes(0); // colors used, 0 = (1 << bitCount) (ignored) bos.write4Bytes(0); // colors important int bit_cache = 0; int bits_in_cache = 0; int row_padding = scan_line_size - (bitCount * src.getWidth() + 7) / 8; for (int y = src.getHeight() - 1; y >= 0; y for (int x = 0; x < src.getWidth(); x++) { int argb = src.getRGB(x, y); bos.write(0xff & argb); bos.write(0xff & (argb >> 8)); bos.write(0xff & (argb >> 16)); bos.write(0xff & (argb >> 24)); } for (int x = 0; x < row_padding; x++) bos.write(0); } int t_row_padding = t_scan_line_size - (src.getWidth() + 7) / 8; for (int y = src.getHeight() - 1; y >= 0; y for (int x = 0; x < src.getWidth(); x++) { int argb = src.getRGB(x, y); int alpha = 0xff & (argb >> 24); bit_cache <<= 1; if (alpha == 0) bit_cache |= 1; bits_in_cache++; if (bits_in_cache >= 8) { bos.write(0xff & bit_cache); bit_cache = 0; bits_in_cache = 0; } } if (bits_in_cache > 0) { bit_cache <<= (8 - bits_in_cache); bos.write(0xff & bit_cache); bit_cache = 0; bits_in_cache = 0; } for (int x = 0; x < t_row_padding; x++) bos.write(0); } return os.toByteArray(); } } private static final Color errorBadgeShadowColor = new Color(0, 0, 0, 102); private static final Color errorBadgeMainColor = new Color(255, 98, 89); private static final Color errorBadgeTextBackgroundColor = new Color(0, 0, 0, 39); @Override public void _setTextBadge(IdeFrame frame, String text) { if (!isValid(frame)) { return; } WinDef.HICON icon = null; if (text != null) { try { int size = 16; BufferedImage image = UIUtil.createImage(frame.getComponent(), size, size, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); int shadowRadius = 16; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setPaint(errorBadgeShadowColor); g.fillRoundRect(size / 2 - shadowRadius / 2, size / 2 - shadowRadius / 2, shadowRadius, shadowRadius, size, size); int mainRadius = 14; g.setPaint(errorBadgeMainColor); g.fillRoundRect(size / 2 - mainRadius / 2, size / 2 - mainRadius / 2, mainRadius, mainRadius, size, size); Font font = g.getFont(); g.setFont(new Font(font.getName(), Font.BOLD, 9)); FontMetrics fontMetrics = g.getFontMetrics(); int textWidth = fontMetrics.stringWidth(text); int textHeight = UIUtil.getHighestGlyphHeight(text, font, g); g.setPaint(errorBadgeTextBackgroundColor); g.fillOval( size / 2 - textWidth / 2, size / 2 - textHeight / 2, textWidth, textHeight); g.setColor(Color.white); g.drawString(text, size / 2 - textWidth / 2, size / 2 - fontMetrics.getHeight() / 2 + fontMetrics.getAscent()); byte[] bytes = writeTransparentIco(image); icon = Win7TaskBar.createIcon(bytes); } catch (Throwable e) { LOG.error(e); } } try { Win7TaskBar.setOverlayIcon(frame, icon, icon != null); } catch (Throwable e) { LOG.error(e); } } private WinDef.HICON myOkIcon; @Override public void _setOkBadge(IdeFrame frame, boolean visible) { if (!isValid(frame)) { return; } WinDef.HICON icon = null; if (visible) { synchronized (Win7AppIcon.class) { if (myOkIcon == null) { try { BufferedImage image = ImageIO.read(getClass().getResource("/mac/appIconOk512.png")); byte[] bytes = writeTransparentIco(image); myOkIcon = Win7TaskBar.createIcon(bytes); } catch (Throwable e) { LOG.error(e); myOkIcon = null; } } icon = myOkIcon; } } try { Win7TaskBar.setOverlayIcon(frame, icon, false); } catch (Throwable e) { LOG.error(e); } } @Override public void _requestAttention(IdeFrame frame, boolean critical) { try { if (isValid(frame)) { Win7TaskBar.attention(frame); } } catch (Throwable e) { LOG.error(e); } } @Override protected IdeFrame getIdeFrame(@Nullable Project project) { return WindowManager.getInstance().getIdeFrame(project); } @Override public void requestFocus(IdeFrame frame) { } private static boolean isValid(IdeFrame frame) { return frame != null && ((Component)frame).isDisplayable(); } } private static class EmptyIcon extends AppIcon { @Override public boolean setProgress(Project project, Object processId, AppIconScheme.Progress scheme, double value, boolean isOk) { return false; } @Override public boolean hideProgress(Project project, Object processId) { return false; } @Override public void setErrorBadge(Project project, String text) { } @Override public void setOkBadge(Project project, boolean visible) { } @Override public void requestAttention(@Nullable Project project, boolean critical) { } @Override public void requestFocus(IdeFrame frame) { } } private static void assertIsDispatchThread() { Application app = ApplicationManager.getApplication(); if (app == null) { assert EventQueue.isDispatchThread(); } else if (!app.isUnitTestMode()) { app.assertIsDispatchThread(); } } }
package py4j.reflection; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import py4j.Py4JException; import py4j.Py4JJavaException; /** * <p> * A MethodInvoker translates a call made in a Python Program into a call to a * Java method. * </p> * <p> * A MethodInvoker is tailored to a particular set of actual parameters and * indicates how far the calling context is from the method signature. * </p> * <p> * For example, a call to method1(String) from Python can be translated to a * call to method1(char) in Java, with a cost of 1. * </p> * * @author Barthelemy Dagenais * */ public class MethodInvoker { public final static int INVALID_INVOKER_COST = -1; public final static int MAX_DISTANCE = 100000000; private static boolean allNoConverter(List<TypeConverter> converters) { boolean allNo = true; for (TypeConverter converter : converters) { if (converter != TypeConverter.NO_CONVERTER) { allNo = false; break; } } return allNo; } private static int buildConverters(List<TypeConverter> converters, Class<?>[] parameters, Class<?>[] arguments) { int cost = 0; int tempCost = -1; int size = arguments.length; for (int i = 0; i < size; i++) { if (arguments[i] == null) { if (parameters[i].isPrimitive()) { tempCost = -1; } else { int distance = TypeUtil.computeDistance(new Object().getClass(), parameters[i]); tempCost = Math.abs(MAX_DISTANCE - distance); converters.add(TypeConverter.NO_CONVERTER); } } else if (parameters[i].isAssignableFrom(arguments[i])) { tempCost = TypeUtil .computeDistance(parameters[i], arguments[i]); converters.add(TypeConverter.NO_CONVERTER); } else if (TypeUtil.isNumeric(parameters[i]) && TypeUtil.isNumeric(arguments[i])) { tempCost = TypeUtil.computeNumericConversion(parameters[i], arguments[i], converters); } else if (TypeUtil.isCharacter(parameters[i])) { tempCost = TypeUtil.computeCharacterConversion(parameters[i], arguments[i], converters); } else if (TypeUtil.isBoolean(parameters[i]) && TypeUtil.isBoolean(arguments[i])) { tempCost = 0; converters.add(TypeConverter.NO_CONVERTER); } if (tempCost != -1) { cost += tempCost; tempCost = -1; } else { cost = -1; break; } } return cost; } public static MethodInvoker buildInvoker(Constructor<?> constructor, Class<?>[] arguments) { MethodInvoker invoker = null; int size = arguments.length; int cost = 0; List<TypeConverter> converters = new ArrayList<TypeConverter>(); if (arguments == null || size == 0) { invoker = new MethodInvoker(constructor, null, 0); } else { cost = buildConverters(converters, constructor.getParameterTypes(), arguments); } if (cost == -1) { invoker = INVALID_INVOKER; } else { TypeConverter[] convertersArray = null; if (!allNoConverter(converters)) { convertersArray = converters.toArray(new TypeConverter[0]); } invoker = new MethodInvoker(constructor, convertersArray, cost); } return invoker; } public static MethodInvoker buildInvoker(Method method, Class<?>[] arguments) { MethodInvoker invoker = null; int size = arguments.length; int cost = 0; List<TypeConverter> converters = new ArrayList<TypeConverter>(); if (arguments == null || size == 0) { invoker = new MethodInvoker(method, null, 0); } else { cost = buildConverters(converters, method.getParameterTypes(), arguments); } if (cost == -1) { invoker = INVALID_INVOKER; } else { TypeConverter[] convertersArray = null; if (!allNoConverter(converters)) { convertersArray = converters.toArray(new TypeConverter[0]); } invoker = new MethodInvoker(method, convertersArray, cost); } return invoker; } private int cost; private TypeConverter[] converters; private Method method; private Constructor<?> constructor; private final Logger logger = Logger.getLogger(MethodInvoker.class .getName()); public static final MethodInvoker INVALID_INVOKER = new MethodInvoker( (Method) null, null, INVALID_INVOKER_COST); public MethodInvoker(Constructor<?> constructor, TypeConverter[] converters, int cost) { super(); this.constructor = constructor; this.converters = converters; this.cost = cost; } public MethodInvoker(Method method, TypeConverter[] converters, int cost) { super(); this.method = method; this.converters = converters; this.cost = cost; } public Constructor<?> getConstructor() { return constructor; } public TypeConverter[] getConverters() { return converters; } public int getCost() { return cost; } public Method getMethod() { return method; } public Object invoke(Object obj, Object[] arguments) { Object returnObject = null; try { Object[] newArguments = arguments; if (converters != null) { int size = arguments.length; newArguments = new Object[size]; for (int i = 0; i < size; i++) { newArguments[i] = converters[i].convert(arguments[i]); } } if (method != null) { method.setAccessible(true); returnObject = method.invoke(obj, newArguments); } else if (constructor != null) { constructor.setAccessible(true); returnObject = constructor.newInstance(newArguments); } } catch (InvocationTargetException ie) { logger.log(Level.WARNING, "Exception occurred in client code.", ie); throw new Py4JJavaException(ie.getCause()); } catch (Exception e) { logger.log( Level.WARNING, "Could not invoke method or received an exception while invoking.", e); throw new Py4JException(e); } return returnObject; } public boolean isVoid() { if (constructor != null) { return false; } else { return method.getReturnType().equals(void.class); } } }
package steamcondenser.steam.community; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import steamcondenser.SteamCondenserException; /** * The SteamId class represents a Steam Community profile (also called Steam ID) * * @author Sebastian Staudt */ public class SteamId { private static Map<Object, SteamId> steamIds = new HashMap<Object, SteamId>(); private String customUrl; private String favoriteGame; private float favoriteGameHoursPlayed; private long fetchTime; private SteamId[] friends; private Map<String, String> games; private SteamGroup[] groups; private String headLine; private float hoursPlayed; private String imageUrl; private Map<String, String> links; private String location; private Date memberSince; private Map<String, Float> mostPlayedGames; private String onlineState; private String privacyState; private String realName; private String stateMessage; private String nickname; private long steamId64; private float steamRating; private String steamRatingText; private String summary; private boolean vacBanned; private int visibilityState; /** * Converts the 64bit SteamID as used and reported by the Steam Community * to a SteamID reported by game servers */ public static String convertCommunityIdToSteamId(long communityId) throws SteamCondenserException { long steamId1 = communityId % 2; long steamId2 = communityId - 76561197960265728L; if(steamId2 <= 0) { throw new SteamCondenserException("SteamID " + communityId + " is too small."); } steamId2 = (steamId2 - steamId1) / 2; return "STEAM_0:" + steamId1 + ":" + steamId2; } /** * Converts the SteamID as reported by game servers to a 64bit SteamID */ public static long convertSteamIdToCommunityId(String steamId) throws SteamCondenserException { if(steamId.equals("STEAM_ID_LAN") || steamId.equals("BOT")) { throw new SteamCondenserException("Cannot convert SteamID \"" + steamId + "\" to a community ID."); } if(!steamId.matches("^STEAM_[0-1]:[0-1]:[0-9]+$")) { throw new SteamCondenserException("SteamID \"" + steamId + "\" doesn't have the correct format."); } String[] tmpId = steamId.substring(6).split(":"); return Long.valueOf(tmpId[1]) + Long.valueOf(tmpId[2]) * 2 + 76561197960265728L; } public static SteamId create(long id) throws SteamCondenserException { return SteamId.create((Object) id, true, false); } public static SteamId create(String id) throws SteamCondenserException { return SteamId.create((Object) id, true, false); } public static SteamId create(long id, boolean fetch) throws SteamCondenserException { return SteamId.create((Object) id, fetch, false); } public static SteamId create(String id, boolean fetch) throws SteamCondenserException { return SteamId.create((Object) id, fetch, false); } public static SteamId create(long id, boolean fetch, boolean bypassCache) throws SteamCondenserException { return SteamId.create((Object) id, fetch, bypassCache); } public static SteamId create(String id, boolean fetch, boolean bypassCache) throws SteamCondenserException { return SteamId.create((Object) id, fetch, bypassCache); } private static SteamId create(Object id, boolean fetch, boolean bypassCache) throws SteamCondenserException { if(SteamId.isCached(id) && !bypassCache) { SteamId steamId = SteamId.steamIds.get(id); if(fetch && !steamId.isFetched()) { steamId.fetchData(); } return steamId; } else { return new SteamId(id, fetch); } } public static boolean isCached(Object id) { return SteamId.steamIds.containsKey(id); } /** * Creates a new SteamId object for the given ID and fetches the data if * fetchData is set to true * * @param id * Either the custom URL or numeric ID of the SteamID * @param fetchData * If set to true, the data of this SteamID will be fetched from * Steam Community * @throws SteamCondenserException */ private SteamId(Object id, boolean fetchData) throws SteamCondenserException { if(id instanceof String) { this.customUrl = (String) id; } else { this.steamId64 = (Long) id; } if(fetchData) { this.fetchData(); } } public boolean cache() { if(!SteamId.steamIds.containsKey(this.steamId64)) { SteamId.steamIds.put(this.steamId64, this); if(this.customUrl != null && !SteamId.steamIds.containsKey(this.customUrl)) { SteamId.steamIds.put(this.customUrl, this); } return true; } return false; } /** * This method fetches the data of this person's SteamID * * @throws SteamCondenserException */ private void fetchData() throws SteamCondenserException { try { String url = this.getBaseUrl() + "?xml=1"; DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); URL urlObject = new URL(url); URLConnection urlConnection = urlObject.openConnection(); InputStreamReader inputReader = new InputStreamReader(urlConnection.getInputStream(), "UTF-8"); Element profile = parser.parse(new InputSource(inputReader)).getDocumentElement(); if(profile.getElementsByTagName("error").getLength() > 0) { throw new SteamCondenserException(profile.getElementsByTagName("error").item(0).getTextContent()); } if(profile.getElementsByTagName("privacyMessage").getLength() > 0) { throw new SteamCondenserException(profile.getElementsByTagName("privacyMessage").item(0).getTextContent()); } String avatarIconUrl = profile.getElementsByTagName("avatarIcon").item(0).getTextContent(); this.imageUrl = avatarIconUrl.substring(0, avatarIconUrl.length() - 4); this.onlineState = profile.getElementsByTagName("onlineState").item(0).getTextContent(); this.privacyState = profile.getElementsByTagName("privacyState").item(0).getTextContent(); this.stateMessage = profile.getElementsByTagName("stateMessage").item(0).getTextContent(); this.nickname = profile.getElementsByTagName("steamID").item(0).getTextContent(); this.steamId64 = Long.parseLong(profile.getElementsByTagName("steamID64").item(0).getTextContent()); this.vacBanned = (profile.getElementsByTagName("vacBanned").item(0).getTextContent().equals("1")); this.visibilityState = Integer.parseInt(profile.getElementsByTagName("visibilityState").item(0).getTextContent()); if(this.privacyState.compareTo("public") == 0) { this.customUrl = profile.getElementsByTagName("customURL").item(0).getTextContent(); if(this.customUrl.isEmpty()) { this.customUrl = null; } Element favoriteGame = (Element) profile.getElementsByTagName("favoriteGame").item(0); if(favoriteGame != null) { this.favoriteGame = favoriteGame.getElementsByTagName("name").item(0).getTextContent(); this.favoriteGameHoursPlayed = Float.parseFloat(favoriteGame.getElementsByTagName("hoursPlayed2wk").item(0).getTextContent()); } this.headLine = profile.getElementsByTagName("headline").item(0).getTextContent(); this.hoursPlayed = Float.parseFloat(profile.getElementsByTagName("hoursPlayed2Wk").item(0).getTextContent()); this.location = profile.getElementsByTagName("location").item(0).getTextContent(); this.memberSince = DateFormat.getDateInstance(DateFormat.LONG,Locale.ENGLISH).parse(profile.getElementsByTagName("memberSince").item(0).getTextContent()); this.realName = profile.getElementsByTagName("realname").item(0).getTextContent(); this.steamRating = Float.parseFloat(profile.getElementsByTagName("steamRating").item(0).getTextContent()); this.summary = profile.getElementsByTagName("summary").item(0).getTextContent(); this.mostPlayedGames = new HashMap<String, Float>(); Element mostPlayedGamesNode = (Element) profile.getElementsByTagName("mostPlayedGames").item(0); if(mostPlayedGamesNode != null) { NodeList mostPlayedGameList = mostPlayedGamesNode.getElementsByTagName("mostPlayedGame"); for(int i = 0; i < mostPlayedGameList.getLength(); i++) { Element mostPlayedGame = (Element) mostPlayedGameList.item(i); this.mostPlayedGames.put(mostPlayedGame.getElementsByTagName("gameName").item(0).getTextContent(), Float.parseFloat(mostPlayedGame.getElementsByTagName("hoursPlayed").item(0).getTextContent())); } } Element groupsNode = (Element) profile.getElementsByTagName( "groups").item(0); if(groupsNode != null) { NodeList groupsNodeList = ((Element) groupsNode).getElementsByTagName("group"); this.groups = new SteamGroup[groupsNodeList.getLength()]; for(int i = 0; i < groupsNodeList.getLength(); i++) { Element group = (Element) groupsNodeList.item(i); this.groups[i] = SteamGroup.create(Long.parseLong(group.getElementsByTagName("groupID64").item(0).getTextContent()), false); } } this.links = new HashMap<String, String>(); Element weblinksNode = (Element) profile.getElementsByTagName("weblinks").item(0); if(weblinksNode != null) { NodeList weblinksList = weblinksNode.getElementsByTagName("weblink"); for(int i = 0; i < weblinksList.getLength(); i++) { Element weblink = (Element) weblinksList.item(i); this.links.put(weblink.getElementsByTagName("title").item(0).getTextContent(), weblink.getElementsByTagName("link").item(0).getTextContent()); } } } } catch(Exception e) { throw new SteamCondenserException("XML data could not be parsed."); } this.fetchTime = new Date().getTime(); } /** * Fetches the friends of this user * * @throws SteamCondenserException */ private void fetchFriends() throws SteamCondenserException { try { String url = this.getBaseUrl() + "/friends?xml=1"; DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); URL urlObject = new URL(url); URLConnection urlConnection = urlObject.openConnection(); InputStreamReader inputReader = new InputStreamReader(urlConnection.getInputStream(), "UTF-8"); Element friendsData = parser.parse(new InputSource(inputReader)).getDocumentElement(); Element friendsNode = (Element) friendsData.getElementsByTagName("friends").item(0); NodeList friendsNodeList = ((Element) friendsNode).getElementsByTagName("friend"); this.friends = new SteamId[friendsNodeList.getLength()]; for(int i = 0; i < friendsNodeList.getLength(); i++) { Element friend = (Element) friendsNodeList.item(i); this.friends[i] = SteamId.create(friend.getTextContent(), false); } } catch(Exception e) { throw new SteamCondenserException("XML data could not be parsed."); } } /** * Fetches the games this user owns * * @throws SteamCondenserException */ private void fetchGames() throws SteamCondenserException { try { String url = this.getBaseUrl() + "/games?xml=1"; DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); URL urlObject = new URL(url); URLConnection urlConnection = urlObject.openConnection(); InputStreamReader inputReader = new InputStreamReader(urlConnection.getInputStream(), "UTF-8"); Element gamesData = parser.parse(new InputSource(inputReader)).getDocumentElement(); Element gamesNode = (Element) gamesData.getElementsByTagName("games").item(0); NodeList gamesNodeList = ((Element) gamesNode).getElementsByTagName("game"); this.games = new HashMap<String, String>(); for(int i = 0; i < gamesNodeList.getLength(); i++) { Element game = (Element) gamesNodeList.item(i); String gameName = game.getElementsByTagName("name").item(0).getTextContent(); Node globalStatsLinkNode = game.getElementsByTagName("globalStatsLink").item(0); if(globalStatsLinkNode != null) { String friendlyName = globalStatsLinkNode.getTextContent(); Pattern regex = Pattern.compile("http://steamcommunity.com/stats/([0-9a-zA-Z:]+)/achievements/"); Matcher matcher = regex.matcher(friendlyName); matcher.find(0); friendlyName = matcher.group(1).toLowerCase(); this.games.put(gameName, friendlyName); } else { this.games.put(gameName, null); } } } catch(Exception e) { throw new SteamCondenserException("XML data could not be parsed."); } } public String getAvatarFullUrl() { return this.imageUrl + "_full.jpg"; } public String getAvatarIconUrl() { return this.imageUrl + ".jpg"; } public String getAvatarMediumUrl() { return this.imageUrl + "_medium.jpg"; } public String getBaseUrl() { if(this.customUrl == null) { return "http://steamcommunity.com/profiles/" + this.steamId64; } else { return "http://steamcommunity.com/id/" + this.customUrl; } } public String getCustomUrl() { return this.customUrl; } public String getFavoriteGame() { return this.favoriteGame; } public float getFavoriteGameHoursPlayed() { return this.favoriteGameHoursPlayed; } public long getFetchTime() { return this.fetchTime; } public SteamId[] getFriends() throws SteamCondenserException { if(this.friends == null) { this.fetchFriends(); } return this.friends; } public Map<String, String> getGames() throws SteamCondenserException { if(this.games == null) { this.fetchGames(); } return this.games; } public GameStats getGameStats(String gameName) throws SteamCondenserException { gameName = gameName.toLowerCase(); String friendlyName; this.getGames(); if(this.games.containsKey(gameName)) { friendlyName = this.games.get(gameName); } else if(this.games.containsValue(gameName)) { friendlyName = gameName; } else { throw new SteamCondenserException("Stats for game " + gameName + " do not exist."); } if(this.customUrl == null) { return GameStats.createGameStats(this.steamId64, friendlyName); } else { return GameStats.createGameStats(this.customUrl, friendlyName); } } public SteamGroup[] getGroups() { return this.groups; } public String getHeadLine() { return this.headLine; } public float getHoursPlayed() { return this.hoursPlayed; } public Map<String, String> getLinks() { return this.links; } public String getLocation() { return this.location; } /** * Returns the date of registration for the Steam account belonging to this * SteamID * * @return The date of the Steam account registration */ public Date getMemberSince() { return this.memberSince; } public String getNickname() { return this.nickname; } public String getRealName() { return this.realName; } public String getStateMessage() { return this.stateMessage; } public long getSteamId64() { return this.steamId64; } public float getSteamRating() { return this.steamRating; } public String getSteamRatingText() { return this.steamRatingText; } public String getSummary() { return this.summary; } public boolean getVacBanned() { return this.vacBanned; } public int getVisibilityState() { return this.visibilityState; } /** * Returns whether the owner of this SteamID is VAC banned */ public boolean isBanned() { return this.vacBanned; } public boolean isFetched() { return this.fetchTime != 0; } /** * Returns whether the owner of this SteamId is playing a game */ public boolean isInGame() { return this.onlineState.equals("in-game"); } /** * Returns whether the owner of this SteamID is currently logged into Steam * * @return True if the user is currenly online or false otherwise */ public boolean isOnline() { return (this.onlineState.equals("online") || this.onlineState.equals("in-game")); } }
package awesomeRB.tests; import static org.junit.Assert.*; import org.junit.Test; import awesomeRB.RBTree; public class RBTreeTest { private RBTree createSomeTestTree1() { RBTree tree = new RBTree(); tree.insert(1); tree.insert(12); tree.insert(13); tree.insert(2); return tree; } private RBTree createSomeTestTree2() { RBTree tree = new RBTree(); tree.insert(13); tree.insert(7); tree.insert(8); tree.insert(16); tree.insert(9); tree.insert(6); tree.insert(5); tree.insert(19); tree.insert(15); tree.insert(4); tree.insert(1); return tree; } @Test public void emptyNewTreeTest() { RBTree tree = new RBTree(); assertEquals(true, tree.empty()); } @Test public void containsTest1() { RBTree tree = createSomeTestTree1(); assertEquals(true, tree.contains(12)); assertEquals(true, tree.contains(2)); assertEquals(true, tree.contains(13)); assertEquals(false, tree.contains(495)); assertEquals(false, tree.contains(10)); } @Test public void containsTest2() { RBTree tree = createSomeTestTree2(); assertEquals(true, tree.contains(1)); } @Test public void insertTest1() { RBTree tree = new RBTree(); tree.insert(1); tree.insert(2); tree.insert(3); tree.insert(4); assertEquals("<Tree [ 1 x [ 2 x [ 3 x [ 4 x x ] ] ] ]>", tree.toString()); } @Test public void insertTest2() { RBTree tree = createSomeTestTree1(); assertEquals("<Tree [ 1 x [ 12 [ 2 x x ] [ 13 x x ] ] ]>", tree.toString()); } @Test public void insertTest3() { RBTree tree = createSomeTestTree2(); assertEquals(false, tree.empty()); } @Test public void rotateLeftTest1() { RBTree tree = createSomeTestTree1(); tree.leftRotate(tree.getRoot().getRightChild()); assertEquals("<Tree [ 1 x [ 13 [ 12 [ 2 x x ] x ] x ] ]>", tree.toString()); } @Test public void rotateRightTest1() { RBTree tree = createSomeTestTree1(); tree.rightRotate(tree.getRoot().getRightChild()); assertEquals("<Tree [ 1 x [ 2 x [ 12 x [ 13 x x ] ] ] ]>", tree.toString()); } @Test public void deleteTest1() { RBTree tree = new RBTree(); tree.insert(3); tree.delete(3); assertEquals(true, tree.empty()); } @Test public void deleteTest2() { RBTree tree = createSomeTestTree1(); tree.delete(13); assertEquals(false, tree.contains(13)); assertEquals(3, tree.size()); assertEquals(12, tree.max()); } @Test public void minTest1() { RBTree tree = createSomeTestTree1(); assertEquals(1, tree.min()); } @Test public void maxTest1() { RBTree tree = createSomeTestTree1(); assertEquals(13, tree.max()); } @Test public void toIntArrayTest1() { RBTree tree = createSomeTestTree1(); int[] expected = {1, 2, 12, 13}; assertArrayEquals(expected, tree.toIntArray()); } @Test public void toIntArrayTest2() { RBTree tree = new RBTree(); tree.insert(7); tree.insert(3); tree.insert(300); tree.insert(5); tree.insert(6); int[] expected = {3, 5, 6, 7, 300}; assertArrayEquals(expected, tree.toIntArray()); } @Test public void sizeTest1() { RBTree tree = new RBTree(); tree.insert(1); assertEquals(1, tree.size()); } @Test public void sizeTest2() { RBTree tree = createSomeTestTree1(); assertEquals(4, tree.size()); } @Test public void insertSizeTest1() { RBTree tree = createSomeTestTree1(); tree.insert(6); assertEquals(5, tree.size()); } //TODO isValidTest() //TODO maxDepthTest() //TODO minLeafDepthTest() }
package org.jpos.q2.iso; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import org.jpos.q2.QFactory; import org.jpos.q2.QBeanSupport; import org.jpos.q2.Q2ConfigurationException; import org.jdom.Element; import org.jpos.space.Space; import org.jpos.space.LocalSpace; import org.jpos.space.SpaceListener; import org.jpos.space.TransientSpace; import org.jpos.iso.MUX; import org.jpos.iso.ISOSource; import org.jpos.iso.ISOMsg; import org.jpos.iso.ISOUtil; import org.jpos.iso.ISORequestListener; import org.jpos.iso.ISOException; import org.jpos.util.NameRegistrar; import org.jpos.util.NameRegistrar.NotFoundException; /** * @author Alejandro Revilla * @version $Revision$ $Date$ * @jmx:mbean description="QMUX" extends="org.jpos.q2.QBeanSupportMBean" */ public class QMUX extends QBeanSupport implements SpaceListener, MUX, QMUXMBean { LocalSpace sp; String in, out, unhandled; String spaceName; List listeners; public QMUX () { super (); sp = TransientSpace.getSpace (); listeners = new ArrayList (); } public void initService () throws Q2ConfigurationException { Element e = getPersist (); in = e.getChildTextTrim ("in"); out = e.getChildTextTrim ("out"); addListeners (); unhandled = e.getChildTextTrim ("unhandled"); } public void startService () { sp.addListener (in, this); NameRegistrar.register ("mux."+getName (), this); } public void stopService () { NameRegistrar.unregister ("mux."+getName ()); sp.removeListener (in, this); } /** * @return MUX with name using NameRegistrar * @throws NameRegistrar.NotFoundException * @see NameRegistrar */ public static MUX getMUX (String name) throws NameRegistrar.NotFoundException { return (MUX) NameRegistrar.get ("mux."+name); } /** * @param m message to send * @param timeout amount of time in millis to wait for a response * @return response or null */ public ISOMsg request (ISOMsg m, long timeout) throws ISOException { String key = getKey (m); String req = key + ".req"; sp.out (req, m); sp.out (out, m, timeout-1); ISOMsg resp = (ISOMsg) sp.in (key, timeout); if (resp == null && sp.inp (req) == null) { // possible race condition, retry for a few extra seconds resp = (ISOMsg) sp.in (key, 10000); } return resp; } public void notify (Object k, Object value) { Object obj = sp.inp (k); if (obj instanceof ISOMsg) { ISOMsg m = (ISOMsg) obj; try { String key = getKey (m); String req = key + ".req"; if (sp.inp (req) != null) { sp.out (key, m); return; } } catch (ISOException e) { getLog().warn ("notify", e); } processUnhandled (m); } } protected String getKey (ISOMsg m) throws ISOException { return out + "." + (m.hasField(41)?ISOUtil.zeropad((String)m.getValue(41),16) : "") + (m.hasField (11) ? ISOUtil.zeropad((String) m.getValue(11),6) : Long.toString (System.currentTimeMillis())); } /** * @jmx:managed-attribute description="input queue" */ public synchronized void setInQueue (String in) { this.in = in; getPersist().getChild("in").setText (in); setModified (true); } /** * @jmx:managed-attribute description="input queue" */ public String getInQueue () { return in; } /** * @jmx:managed-attribute description="output queue" */ public synchronized void setOutQueue (String out) { this.out = out; getPersist().getChild("out").setText (out); setModified (true); } /** * @jmx:managed-attribute description="output queue" */ public String getOutQueue () { return out; } /** * @jmx:managed-attribute description="unhandled queue" */ public synchronized void setUnhandledQueue (String unhandled) { this.unhandled = unhandled; getPersist().getChild("unhandled").setText (unhandled); setModified (true); } /** * @jmx:managed-attribute description="unhandled queue" */ public String getUnhandledQueue () { return unhandled; } private void addListeners () throws Q2ConfigurationException { QFactory factory = getFactory (); Iterator iter = getPersist().getChildren ( "request-listener" ).iterator(); while (iter.hasNext()) { Element l = (Element) iter.next(); ISORequestListener listener = (ISORequestListener) factory.newInstance (l.getAttributeValue ("class")); factory.setLogger (listener, l); factory.setConfiguration (listener, l); addISORequestListener (listener); } } public void addISORequestListener(ISORequestListener l) { listeners.add (l); } protected void processUnhandled (ISOMsg m) { ISOSource source = m.getSource (); if (source != null) { Iterator iter = listeners.iterator(); while (iter.hasNext()) if (((ISORequestListener)iter.next()).process (source, m)) return; } if (unhandled != null) sp.out (unhandled, m, 120000); } }
package ifc.beans; import java.util.Random; import java.util.StringTokenizer; import lib.MultiMethodTest; import util.ValueChanger; import util.utils; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyAttribute; import com.sun.star.beans.PropertyChangeEvent; import com.sun.star.beans.XPropertyChangeListener; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.beans.XVetoableChangeListener; import com.sun.star.lang.EventObject; /** * Testing <code>com.sun.star.beans.XPropertySet</code> * interface methods : * <ul> * <li><code>getPropertySetInfo()</code></li> * <li><code>setPropertyValue()</code></li> * <li><code>getPropertyValue()</code></li> * <li><code>addPropertyChangeListener()</code></li> * <li><code>removePropertyChangeListener()</code></li> * <li><code>addVetoableChangeListener()</code></li> * <li><code>removeVetoableChangeListener()</code></li> * </ul> * @see com.sun.star.beans.XPropertySet */ public class _XPropertySet extends MultiMethodTest { public XPropertySet oObj = null; /** * Flag that indicates change listener was called. */ boolean propertyChanged = false; /** * Listener that must be called on bound property changing. */ public class MyChangeListener implements XPropertyChangeListener { /** * Just set <code>propertyChanged</code> flag to true. */ public void propertyChange(PropertyChangeEvent e) { propertyChanged = true; } public void disposing (EventObject obj) {} }; XPropertyChangeListener PClistener = new MyChangeListener(); /** * Flag that indicates veto listener was called. */ boolean vetoableChanged = false; /** * Listener that must be called on constrained property changing. */ public class MyVetoListener implements XVetoableChangeListener { /** * Just set <code>vetoableChanged</code> flag to true. */ public void vetoableChange(PropertyChangeEvent e) { vetoableChanged = true; } public void disposing (EventObject obj) {} }; XVetoableChangeListener VClistener = new MyVetoListener(); /** * Structure that collects three properties of each type to test : * Constrained, Bound and Normal. */ public class PropsToTest { String constrained = null; String bound = null; String normal = null; } PropsToTest PTT = new PropsToTest(); /** * Tests method <code>getPropertySetInfo</code>. After test completed * call {@link #getPropsToTest} method to retrieve different kinds * of properties to test then. <p> * Has OK status if not null <code>XPropertySetInfo</code> * object returned.<p> * Since <code>getPropertySetInfo</code> is optional, it may return null, * if it is not implemented. This method uses then an object relation * <code>PTT</code> (Properties To Test) to determine available properties. * All tests for services without <code>getPropertySetInfo</code> must * provide this object relation. */ public void _getPropertySetInfo() { XPropertySetInfo propertySetInfo = oObj.getPropertySetInfo(); if (propertySetInfo == null) { log.println("getPropertySetInfo() method returned null"); tRes.tested("getPropertySetInfo()", true) ; String[] ptt = (String[]) tEnv.getObjRelation("PTT"); PTT.normal=ptt[0]; PTT.bound=ptt[1]; PTT.constrained=ptt[2]; } else { tRes.tested("getPropertySetInfo()", true ); getPropsToTest(propertySetInfo); } return; } // end of getPropertySetInfo() /** * Tests change listener which added for bound properties. * Adds listener to bound property (if it exists), then changes * its value and check if listener was called. <p> * Method tests to be successfully completed before : * <ul> * <li> <code>getPropertySetInfo</code> : in this method test * one of bound properties is retrieved. </li> * </ul> <p> * Has OK status if NO bound properties exist or if listener * was successfully called. */ public void _addPropertyChangeListener() { requiredMethod("getPropertySetInfo()"); propertyChanged = false; if ( PTT.bound.equals("none") ) { log.println("*** No bound properties found ***"); tRes.tested("addPropertyChangeListener()", true) ; } else { try { oObj.addPropertyChangeListener(PTT.bound,PClistener); Object gValue = oObj.getPropertyValue(PTT.bound); oObj.setPropertyValue(PTT.bound, ValueChanger.changePValue(gValue)); } catch (com.sun.star.beans.PropertyVetoException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.IllegalArgumentException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } // end of try-catch tRes.tested("addPropertyChangeListener()", propertyChanged); if (!propertyChanged) { log.println("propertyChangeListener wasn't called for '"+ PTT.bound+"'"); } } //endif return; } // end of addPropertyChangeListener() /** * Tests vetoable listener which added for constrained properties. * Adds listener to constrained property (if it exists), then changes * its value and check if listener was called. <p> * Method tests to be successfully completed before : * <ul> * <li> <code>getPropertySetInfo</code> : in this method test * one of constrained properties is retrieved. </li> * </ul> <p> * Has OK status if NO constrained properties exist or if listener * was successfully called. */ public void _addVetoableChangeListener() { requiredMethod("getPropertySetInfo()"); vetoableChanged = false; if ( PTT.constrained.equals("none") ) { log.println("*** No constrained properties found ***"); tRes.tested("addVetoableChangeListener()", true) ; } else { try { oObj.addVetoableChangeListener(PTT.constrained,VClistener); Object gValue = oObj.getPropertyValue(PTT.constrained); oObj.setPropertyValue(PTT.constrained, ValueChanger.changePValue(gValue)); } catch (com.sun.star.beans.PropertyVetoException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.IllegalArgumentException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } // end of try-catch tRes.tested("addVetoableChangeListener()",vetoableChanged); if (!vetoableChanged) { log.println("vetoableChangeListener wasn't called for '"+ PTT.constrained+"'"); } } //endif return; } // end of addVetoableChangeListener() /** * Tests <code>setPropertyValue</code> method. * Stores value before call, and compares it with value after * call. <p> * Method tests to be successfully completed before : * <ul> * <li> <code>getPropertySetInfo</code> : in this method test * one of normal properties is retrieved. </li> * </ul> <p> * Has OK status if NO normal properties exist or if value before * method call is not equal to value after. */ public void _setPropertyValue() { requiredMethod("getPropertySetInfo()"); Object gValue = null; Object sValue = null; if ( PTT.normal.equals("none") ) { log.println("*** No changeable properties found ***"); tRes.tested("setPropertyValue()", true) ; } else { try { gValue = oObj.getPropertyValue(PTT.normal); sValue = ValueChanger.changePValue(gValue); oObj.setPropertyValue(PTT.normal, sValue); sValue = oObj.getPropertyValue(PTT.normal); } catch (com.sun.star.beans.PropertyVetoException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.normal+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.IllegalArgumentException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.normal+"'"); e.printStackTrace(log); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.normal+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.normal+"'"); e.printStackTrace(log); } // end of try-catch tRes.tested("setPropertyValue()",(! gValue.equals(sValue))); } //endif return; } // end of setPropertyValue() /** * Tests <code>getPropertyValue</code> method. * Just call this method and checks for no exceptions <p> * Method tests to be successfully completed before : * <ul> * <li> <code>getPropertySetInfo</code> : in this method test * one of normal properties is retrieved. </li> * </ul> <p> * Has OK status if NO normal properties exist or if no * exceptions were thrown. */ public void _getPropertyValue() { requiredMethod("getPropertySetInfo()"); String toCheck = PTT.normal; if ( PTT.normal.equals("none") ) { toCheck = oObj.getPropertySetInfo().getProperties()[0].Name; log.println("All properties are Read Only"); log.println("Using: "+toCheck); } try { oObj.getPropertyValue(toCheck); tRes.tested("getPropertyValue()",true); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("Exception occured while trying to get property '"+ PTT.normal+"'"); e.printStackTrace(log); tRes.tested("getPropertyValue()",false); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Exception occured while trying to get property '"+ PTT.normal+"'"); e.printStackTrace(log); tRes.tested("getPropertyValue()",false); } // end of try-catch return; } /** * Tests <code>removePropertyChangeListener</code> method. * Removes change listener, then changes bound property value * and checks if the listener was NOT called. * Method tests to be successfully completed before : * <ul> * <li> <code>addPropertyChangeListener</code> : here listener * was added. </li> * </ul> <p> * Has OK status if NO bound properties exist or if listener * was not called and no exceptions arose. */ public void _removePropertyChangeListener() { requiredMethod("addPropertyChangeListener()"); propertyChanged = false; if ( PTT.bound.equals("none") ) { log.println("*** No bound properties found ***"); tRes.tested("removePropertyChangeListener()", true) ; } else { try { propertyChanged = false; oObj.removePropertyChangeListener(PTT.bound,PClistener); Object gValue = oObj.getPropertyValue(PTT.bound); oObj.setPropertyValue(PTT.bound, ValueChanger.changePValue(gValue)); } catch (com.sun.star.beans.PropertyVetoException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.IllegalArgumentException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.bound+"'"); e.printStackTrace(log); } // end of try-catch tRes.tested("removePropertyChangeListener()",!propertyChanged); if (propertyChanged) { log.println("propertyChangeListener was called after removing"+ " for '"+PTT.bound+"'"); } } //endif return; } // end of removePropertyChangeListener() /** * Tests <code>removeVetoableChangeListener</code> method. * Removes vetoable listener, then changes constrained property value * and checks if the listener was NOT called. * Method tests to be successfully completed before : * <ul> * <li> <code>addPropertyChangeListener</code> : here vetoable listener * was added. </li> * </ul> <p> * Has OK status if NO constrained properties exist or if listener * was NOT called and no exceptions arose. */ public void _removeVetoableChangeListener() { requiredMethod("addVetoableChangeListener()"); vetoableChanged = false; if ( PTT.constrained.equals("none") ) { log.println("*** No constrained properties found ***"); tRes.tested("removeVetoableChangeListener()", true) ; } else { try { oObj.removeVetoableChangeListener(PTT.constrained,VClistener); Object gValue = oObj.getPropertyValue(PTT.constrained); oObj.setPropertyValue(PTT.constrained, ValueChanger.changePValue(gValue)); } catch (com.sun.star.beans.PropertyVetoException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.IllegalArgumentException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Exception occured while trying to change "+ "property '"+ PTT.constrained+"'"); e.printStackTrace(log); } // end of try-catch tRes.tested("removeVetoableChangeListener()",!vetoableChanged); if (vetoableChanged) { log.println("vetoableChangeListener was called after "+ "removing for '"+PTT.constrained+"'"); } } //endif return; } // end of removeVetoableChangeListener() /** * Gets the properties being tested. Searches and stores by one * property of each kind (Bound, Vetoable, Normal). */ public PropsToTest getPropsToTest(XPropertySetInfo xPSI) { Property[] properties = xPSI.getProperties(); String bound = ""; String constrained = ""; String normal = ""; for (int i = 0; i < properties.length; i++) { Property property = properties[i]; String name = property.Name; log.println("Checking '"+name+"'"); boolean isWritable = ((property.Attributes & PropertyAttribute.READONLY) == 0); boolean isNotNull = ((property.Attributes & PropertyAttribute.MAYBEVOID) == 0); boolean isBound = ((property.Attributes & PropertyAttribute.BOUND) != 0); boolean isConstr = ((property.Attributes & PropertyAttribute.CONSTRAINED) != 0); boolean canChange = false; if ( !isWritable ) log.println("Property '"+name+"' is READONLY"); if (name.endsWith("URL")) isWritable = false; if (name.startsWith("Fill")) isWritable = false; if (name.startsWith("Font")) isWritable = false; if (name.startsWith("IsNumbering")) isWritable = false; if (name.startsWith("LayerName")) isWritable = false; if (name.startsWith("Line")) isWritable = false; if (name.startsWith("TextWriting")) isWritable = false; //if (name.equals("xinterfaceA") || name.equals("xtypeproviderA") //|| name.equals("arAnyA")) isWritable=false; if ( isWritable && isNotNull ) canChange = isChangeable(name); if ( isWritable && isNotNull && isBound && canChange) { bound+=name+";"; } if ( isWritable && isNotNull && isConstr && canChange) { constrained+=name+";"; } if ( isWritable && isNotNull && canChange) normal+=name+";"; } // endfor //get a random bound property PTT.bound=getRandomString(bound); log.println("Bound: "+PTT.bound); //get a random constrained property PTT.constrained=getRandomString(constrained); log.println("Constrained: "+PTT.constrained); //get a random normal property PTT.normal=getRandomString(normal); return PTT; } /** * Retrieves one random property name from list (property names separated * by ';') of property names. */ public String getRandomString(String str) { String gRS = "none"; Random rnd = new Random(); if (str.equals("")) str = "none"; StringTokenizer ST=new StringTokenizer(str,";"); int nr = rnd.nextInt(ST.countTokens()); if (nr < 1) nr+=1; for (int i=1; i<nr+1; i++) gRS = ST.nextToken(); return gRS; } public boolean isChangeable(String name) { boolean hasChanged = false; try { Object getProp = oObj.getPropertyValue(name); log.println("Getting: "+getProp); if (name.equals("xinterfaceA")) { System.out.println("drin"); } Object setValue = null; if (getProp != null) { if (!utils.isVoid(getProp)) setValue = ValueChanger.changePValue(getProp); else log.println("Property '"+name+ "' is void but MAYBEVOID isn't set"); } else log.println("Property '"+name+"'is null and can't be changed"); if (name.equals("LineStyle")) setValue = null; if (setValue != null) { log.println("Setting to :"+setValue); oObj.setPropertyValue(name, setValue); hasChanged = (! getProp.equals(oObj.getPropertyValue(name))); } else log.println("Couldn't change Property '"+name+"'"); } catch (com.sun.star.beans.PropertyVetoException e) { log.println("'" + name + "' throws exception '" + e + "'"); e.printStackTrace(log); } catch (com.sun.star.lang.IllegalArgumentException e) { log.println("'" + name + "' throws exception '" + e + "'"); e.printStackTrace(log); } catch (com.sun.star.beans.UnknownPropertyException e) { log.println("'" + name + "' throws exception '" + e + "'"); e.printStackTrace(log); } catch (com.sun.star.lang.WrappedTargetException e) { log.println("'" + name + "' throws exception '" + e + "'"); e.printStackTrace(log); } catch (com.sun.star.uno.RuntimeException e) { log.println("'" + name + "' throws exception '" + e + "'"); e.printStackTrace(log); } catch (java.lang.ArrayIndexOutOfBoundsException e) { log.println("'" + name + "' throws exception '" + e + "'"); e.printStackTrace(log); } return hasChanged; } /** * Forces environment recreation. */ protected void after() { disposeEnvironment(); } } // finish class _XPropertySet
package bakatxt.core; import java.util.ArrayList; import java.util.LinkedList; import bakatxt.gui.BakaUI; import bakatxt.international.BakaTongue; public class BakaProcessor { private static String COMMAND_EDIT = "EDIT"; private static String COMMAND_ADD = "ADD"; private static String SPACE = " "; private static String STRING_NULL = "null"; private static Database _database; private static BakaParser _parser; private static LinkedList<Task> _displayTasks; private static ReverseAction _ra; private static Integer editStage = 0; private static Task originalTask; private static Task editTask; private static boolean _choosingLanguage = false; enum CommandType { HELP, ADD, DELETE, SHOW, DISPLAY, CLEAR, DEFAULT, REMOVE, EDIT, UNDO, REDO, LANGUAGE, SEARCH, EXIT } public BakaProcessor() { _database = Database.getInstance(); _parser = new BakaParser(); _displayTasks = _database.getAllTasks(); _ra = new ReverseAction(); } private void displayTask(String input) { input = input.trim(); if (input.contains(SPACE)) { String content = _parser.getString(input); if (content.equals("day")) { String currentDate = _parser.getDate("today").trim(); _displayTasks = _database.getTasksWithDate(currentDate); System.out.println("aloha"); } else if (content.equals("week")) { // TODO } else { _displayTasks = _database.getAllTasks(); } } else { _displayTasks = _database.getAllTasks(); } } private void searchTask(String input) { String title = _parser.getString(input).trim(); _displayTasks = _database.getTaskWithTitle(title); } public LinkedList<Task> getAllTasks() { return _displayTasks; } private void clearTask() { _database.clear(); _displayTasks = _database.getAllTasks(); } public void executeCommand(String input) { if (_choosingLanguage) { BakaTongue.setLanguage(input); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); _choosingLanguage = false; input = "display"; } input = BakaTongue.toEnglish(input); String command = _parser.getCommand(input); if (!command.equals(COMMAND_EDIT) && editStage > 0) { executeCommand(COMMAND_EDIT + SPACE + input); return; } CommandType commandType; /* * The command word will be stored as a string and it will get * CommandType value but will return DEFAULT if a wrong command is * entered */ try { commandType = CommandType.valueOf(command); } catch (IllegalArgumentException e) { commandType = CommandType.DEFAULT; } switch (commandType) { case HELP : showHelp(); return; case ADD : addTask(input, command); break; case REMOVE : case DELETE : deleteTask(input, command); break; case SHOW : case DISPLAY : displayTask(input); return; case CLEAR : clearTask(); break; case EDIT : editTask(input, command); break; case UNDO : _ra.undo(); break; case REDO : _ra.redo(); break; case LANGUAGE : languageSelector(input); return; case EXIT : _database.close(); System.exit(0); break; case SEARCH : searchTask(input); return; case DEFAULT : addTaskWithNoCommandWord(input); break; default : break; } _displayTasks = _database.getAllTasks(); } private void showHelp() { _displayTasks = new LinkedList<Task>(); for (CommandType c : CommandType.values()) { String cmd = c.toString(); if (cmd.equals("DEFAULT") || cmd.equals("HELP")) { continue; } String languageKey = "COMMAND_" + cmd; Task command = new Task(BakaTongue.getString(languageKey)); command.setDate(BakaTongue.getString("COMMAND_HELP")); _displayTasks.add(command); } } private void languageSelector(String input) { input = input.trim(); if (input.contains(SPACE)) { BakaTongue.setLanguage(_parser.getString(input)); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); _displayTasks = _database.getAllTasks(); } else { _choosingLanguage = true; _displayTasks = BakaTongue.languageChoices(); BakaUI.setAlertMessageText(BakaTongue .getString("MESSAGE_LANGUAGE_CHOICE")); } } private void addTaskWithNoCommandWord(String input) { UserInput inputCmd; Task task; task = _parser.add(COMMAND_ADD + SPACE + input); inputCmd = new UserInput(COMMAND_ADD, task); _ra.execute(inputCmd); } private void editTask(String input, String command) { UserInput inputCmd; String nextStagePrompt; String parsedDateTime; if (editStage == 0) { editStage = 5; String index = _parser.getString(input).trim(); int trueIndex = Integer.valueOf(index.trim()) - 1; _displayTasks = _database.getAllTasks(); editTask = _displayTasks.get(trueIndex); originalTask = new Task(editTask); BakaUI.setInputBoxText(editTask.getTitle()); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_TITLE")); } else { input = _parser.getString(input); switch (editStage) { case 5 : editTitle(input); break; case 4 : editVenue(input); break; case 3 : editDate(input); break; case 2 : editTime(input); break; case 1 : editDescription(input, command); break; default : break; } editStage } } private void editDescription(String input, String command) { UserInput inputCmd; String nextStagePrompt; if (input.equals(BakaTongue.getString("USER_PROMPT_DESCRIPTION"))) { input = null; } editTask.setDescription(input); inputCmd = new UserInput(command, originalTask, editTask); _ra.execute(inputCmd); nextStagePrompt = ""; BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("MESSAGE_WELCOME")); } private void editTime(String input) { String nextStagePrompt; String parsedDateTime; if (input.equals(BakaTongue.getString("USER_PROMPT_TIME"))) { input = null; } parsedDateTime = _parser.getTime(input); editTask.setTime(parsedDateTime); nextStagePrompt = editTask.getDescription(); if (nextStagePrompt == null) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_DESCRIPTION"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_DESCRIPTION")); } private void editDate(String input) { String nextStagePrompt; String parsedDateTime; if (input.equals(BakaTongue.getString("USER_PROMPT_DATE"))) { input = null; } parsedDateTime = _parser.getDate(input); editTask.setDate(parsedDateTime); nextStagePrompt = editTask.getTime(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_TIME"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_TIME")); } private void editVenue(String input) { String nextStagePrompt; if (input.equals(BakaTongue.getString("USER_PROMPT_VENUE"))) { input = null; } editTask.setVenue(input); nextStagePrompt = editTask.getDate(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_DATE"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_DATE")); } private void editTitle(String input) { String nextStagePrompt; if (input.trim().isEmpty()) { editTask.setTitle(originalTask.getTitle()); } else { editTask.setTitle(input); } nextStagePrompt = editTask.getVenue(); if (nextStagePrompt.equals(STRING_NULL)) { nextStagePrompt = BakaTongue.getString("USER_PROMPT_VENUE"); } BakaUI.setInputBoxText(nextStagePrompt); BakaUI.setAlertMessageText(BakaTongue.getString("ALERT_EDIT_MODE") + BakaTongue.getString("ALERT_EDIT_VENUE")); } private void deleteTask(String input, String command) { UserInput inputCmd; Task task; String content = _parser.getString(input).trim(); ArrayList<Integer> listOfIndex = _parser.getIndexList(content); _displayTasks = _database.getAllTasks(); for (int i = 0; i < listOfIndex.size(); i++) { int trueIndex = listOfIndex.get(i); task = _displayTasks.get(trueIndex - 1); inputCmd = new UserInput(command, task); _ra.execute(inputCmd); } } private void addTask(String input, String command) { UserInput inputCmd; Task task; task = _parser.add(input); inputCmd = new UserInput(command, task); _ra.execute(inputCmd); _database.getAllTasks(); } }
package edu.isep.sixcolors.controller; import edu.isep.sixcolors.model.*; import java.util.ArrayList; /** * Game controller : Main controller of the game * Manages inputs and outputs to and from the view */ public class Game { /** * Array representing the players playing the current game */ private Player[] players; /** * Create a new game with 2 players * * @param players Number of players */ public Game() { this.players = new Player[2]; for(int i = 0; i < this.players.length; i++) { this.players[i] = new Player(); } } /** * Get a specific player from its id * @param id * @return Player */ public Player getPlayer(int id) { // TODO check if the given id belongs to the players array keys range return players[id]; } /** * Get all the players of the current game * @return Player[] */ public Player[] getPlayers() { return this.players; } /** * Updates the board for a players turn * @param currentPlayer * @param board */ private void updateBoard(Player currentPlayer, Board board){ for(int i = 0; i< board.getTiles().length ; i++) { for(int j = 0; j<board.getTiles().length; j++) { //Tile by tile Tile tile = board.getTile(i, j); //Modifications are only made from tiles owned by currentPlayer if (tile.getOwner() == currentPlayer){ //Updates the color of an owned tile if necessary if (tile.getColor() != currentPlayer.getControlledColor()) tile.setColor(currentPlayer.getControlledColor()); //Updates the neighboring tiles of the previously owned tile // TODO Neighboring cells can i think be re-analyzed as tiles previously owned. if (i != 0) UpdateTile(currentPlayer, board.getTile(i, j-1)); //Left if (i != board.getTiles().length) UpdateTile(currentPlayer, board.getTile(i, j+1)); //Right if (j != 0) UpdateTile(currentPlayer, board.getTile(i-1, j)); if (j != board.getTiles().length) UpdateTile(currentPlayer, board.getTile(i+1, j)); //Down } } } } /** * Used in updateBoard to update the owner and color of a tile if it's not already owned and is the correct color * @param currentPlayer * @param tile */ private void UpdateTile(Player currentPlayer, Tile tile){ if(tile.getOwner() == null && tile.getColor() == currentPlayer.getControlledColor()){ tile.setOwner(currentPlayer); tile.setColor(currentPlayer.getControlledColor()); } } }
package hudson.remoting; import org.junit.Ignore; import org.objectweb.asm.ClassReader; import org.objectweb.asm.attrs.StackMapAttribute; import java.io.IOException; /** * @author Kohsuke Kawaguchi */ @Ignore public class PrefetchTest extends RmiTestBase { public void testPrefetch() throws Exception { VerifyTask vt = new VerifyTask(); assertTrue( channel.preloadJar(vt,ClassReader.class)); assertFalse(channel.preloadJar(vt,ClassReader.class)); // TODO: how can I do a meaningful test of this feature? System.out.println(channel.call(vt)); } private static class VerifyTask extends CallableBase<String,IOException> { public String call() throws IOException { StackMapAttribute sma = new StackMapAttribute(); return Which.jarFile(sma.getClass()).getPath(); } private static final long serialVersionUID = 1L; } }
package javax.time.calendar; import static javax.time.calendar.DayOfWeek.TUESDAY; import static javax.time.calendar.DayOfWeek.WEDNESDAY; import static javax.time.calendar.ISODateTimeRule.YEAR; import static javax.time.calendar.ISOPeriodUnit.DECADES; import static javax.time.calendar.ISOPeriodUnit.MONTHS; import static javax.time.calendar.ISOPeriodUnit.YEARS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.Serializable; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.TimeSource; import javax.time.calendar.format.CalendricalParseException; import javax.time.calendar.format.DateTimeFormatters; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test Year. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ @Test public class TestYear { @BeforeMethod public void setUp() { } @Test(groups={"implementation"}) public void test_interfaces() { assertTrue(Calendrical.class.isAssignableFrom(Year.class)); assertTrue(Serializable.class.isAssignableFrom(Year.class)); assertTrue(Comparable.class.isAssignableFrom(Year.class)); assertTrue(DateAdjuster.class.isAssignableFrom(Year.class)); assertTrue(CalendricalMatcher.class.isAssignableFrom(Year.class)); } @Test(groups={"tck"}) public void test_rule() { assertEquals(Year.rule().getName(), "Year"); assertEquals(Year.rule().getType(), Year.class); } // now() @Test(groups={"tck"}) public void now() { Year expected = Year.now(Clock.systemDefaultZone()); Year test = Year.now(); for (int i = 0; i < 100; i++) { if (expected.equals(test)) { return; } expected = Year.now(Clock.systemDefaultZone()); test = Year.now(); } assertEquals(test, expected); } // now(Clock) @Test(groups={"tck"}) public void now_Clock() { Instant instant = Instant.of(OffsetDateTime.of(2010, 12, 31, 0, 0, ZoneOffset.UTC)); Clock clock = Clock.clock(TimeSource.fixed(instant), ZoneId.UTC); Year test = Year.now(clock); assertEquals(test.getValue(), 2010); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void now_Clock_nullClock() { Year.now(null); } @Test(groups={"tck"}) public void test_factory_int_singleton() { for (int i = -4; i <= 2104; i++) { Year test = Year.of(i); assertEquals(test.getValue(), i); assertEquals(Year.of(i), test); } } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_factory_int_tooLow() { Year.of(Year.MIN_YEAR - 1); } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_factory_int_tooHigh() { Year.of(Year.MAX_YEAR + 1); } @Test(groups={"tck"}) public void test_factory_Calendricals() { assertEquals(Year.from(LocalDate.of(2007, 7, 15)), Year.of(2007)); assertEquals(Year.from(MockCenturyFieldRule.INSTANCE.field(20), MockYearOfCenturyFieldRule.INSTANCE.field(7)), Year.of(2007)); assertEquals(Year.from(YEAR.field(2007)), Year.of(2007)); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_factory_Calendricals_invalid_clash() { Year.from(TUESDAY, WEDNESDAY.toField()); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_factory_Calendricals_invalid_noDerive() { Year.from(LocalTime.of(12, 30)); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_factory_Calendricals_invalid_empty() { Year.from(); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_Calendricals_nullArray() { Year.from((Calendrical[]) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_Calendricals_null() { Year.from((Calendrical) null); } // get() @Test(groups={"tck"}) public void test_get() { Year test = Year.of(1999); assertEquals(test.get(YEAR), YEAR.field(1999)); assertEquals(test.get(MockDecadeOfCenturyFieldRule.INSTANCE).getValue(), 9); } @Test(groups={"implementation"}) public void test_get_same() { Year test = Year.of(1999); assertSame(test.get(Year.rule()), test); } @Test(groups={"tck"}) public void test_get_unsupportedField() { assertEquals(Year.of(1999).get(ISODateTimeRule.WEEK_BASED_YEAR), null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_get_null() { Year.of(1999).get((CalendricalRule<?>) null); } // isLeap() @Test(groups={"tck"}) public void test_isLeap() { assertEquals(Year.of(1999).isLeap(), false); assertEquals(Year.of(2000).isLeap(), true); assertEquals(Year.of(2001).isLeap(), false); assertEquals(Year.of(2007).isLeap(), false); assertEquals(Year.of(2008).isLeap(), true); assertEquals(Year.of(2009).isLeap(), false); assertEquals(Year.of(2010).isLeap(), false); assertEquals(Year.of(2011).isLeap(), false); assertEquals(Year.of(2012).isLeap(), true); assertEquals(Year.of(2095).isLeap(), false); assertEquals(Year.of(2096).isLeap(), true); assertEquals(Year.of(2097).isLeap(), false); assertEquals(Year.of(2098).isLeap(), false); assertEquals(Year.of(2099).isLeap(), false); assertEquals(Year.of(2100).isLeap(), false); assertEquals(Year.of(2101).isLeap(), false); assertEquals(Year.of(2102).isLeap(), false); assertEquals(Year.of(2103).isLeap(), false); assertEquals(Year.of(2104).isLeap(), true); assertEquals(Year.of(2105).isLeap(), false); assertEquals(Year.of(-500).isLeap(), false); assertEquals(Year.of(-400).isLeap(), true); assertEquals(Year.of(-300).isLeap(), false); assertEquals(Year.of(-200).isLeap(), false); assertEquals(Year.of(-100).isLeap(), false); assertEquals(Year.of(0).isLeap(), true); assertEquals(Year.of(100).isLeap(), false); assertEquals(Year.of(200).isLeap(), false); assertEquals(Year.of(300).isLeap(), false); assertEquals(Year.of(400).isLeap(), true); assertEquals(Year.of(500).isLeap(), false); } // next() @Test(groups={"tck"}) public void test_next() { assertEquals(Year.of(2007).next(), Year.of(2008)); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_next_max() { Year.of(Year.MAX_YEAR).next(); } // previous() @Test(groups={"tck"}) public void test_previous() { assertEquals(Year.of(2007).previous(), Year.of(2006)); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_previous_min() { Year.of(Year.MIN_YEAR).previous(); } // plus(PeriodProvider) @Test(groups={"tck"}) public void test_plus_PeriodProvider() { PeriodProvider provider = Period.of(1, 2, 3, 4, 5, 6, 7); assertEquals(Year.of(2007).plus(provider), Year.of(2008)); } @Test(groups={"tck"}) public void test_plus_PeriodProvider_normalized() { PeriodProvider provider = PeriodFields.of(5, DECADES).with(3, YEARS).with(25, MONTHS); assertEquals(Year.of(2007).plus(provider), Year.of(2007 + 50 + 3)); // months ignored } @Test(groups={"tck"}) public void test_plus_PeriodProvider_otherFieldsIgnored() { PeriodProvider provider = Period.of(1, 27, 3, 4, 5, 6, 7); assertEquals(Year.of(2007).plus(provider), Year.of(2008)); // months ignored } @Test(groups={"implementation"}) public void test_plus_PeriodProvider_zero_same() { Year base = Year.of(2007); assertSame(base.plus(Period.ZERO), base); } @Test(groups={"tck"}) public void test_plus_PeriodProvider_zero_equal() { Year base = Year.of(2007); assertEquals(base.plus(Period.ZERO), base); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plus_PeriodProvider_invalidPeriod() { PeriodProvider provider = PeriodField.of(20, MockOtherChronology.OTHER_MONTHS); Year.of(2010).plus(provider); } @Test(expectedExceptions=ArithmeticException.class, groups={"tck"}) public void test_plus_PeriodProvider_bigPeriod() { long years = 20L + Integer.MAX_VALUE; PeriodProvider provider = PeriodField.of(years, YEARS); Year.of(-40).plus(provider); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_plus_PeriodProvider_null() { Year.of(2007).plus((PeriodProvider) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_plus_PeriodProvider_badProvider() { Year.of(2007).plus(new MockPeriodProviderReturnsNull()); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plus_PeriodProvider_invalidTooLarge() { PeriodProvider provider = Period.ofYears(1); Year.of(Year.MAX_YEAR).plus(provider); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plus_PeriodProvider_invalidTooSmall() { PeriodProvider provider = Period.ofYears(-1); Year.of(Year.MIN_YEAR).plus(provider); } // plusYears() @Test(groups={"tck"}) public void test_plusYears() { assertEquals(Year.of(2007).plusYears(-1), Year.of(2006)); assertEquals(Year.of(2007).plusYears(0), Year.of(2007)); assertEquals(Year.of(2007).plusYears(1), Year.of(2008)); assertEquals(Year.of(2007).plusYears(2), Year.of(2009)); assertEquals(Year.of(Year.MAX_YEAR - 1).plusYears(1), Year.of(Year.MAX_YEAR)); assertEquals(Year.of(Year.MAX_YEAR).plusYears(0), Year.of(Year.MAX_YEAR)); assertEquals(Year.of(Year.MIN_YEAR + 1).plusYears(-1), Year.of(Year.MIN_YEAR)); assertEquals(Year.of(Year.MIN_YEAR).plusYears(0), Year.of(Year.MIN_YEAR)); } @Test(groups={"implementation"}) public void test_plusYear_zero_same() { Year base = Year.of(2007); assertSame(base.plusYears(0), base); } @Test(groups={"tck"}) public void test_plusYear_zero_equals() { Year base = Year.of(2007); assertEquals(base.plusYears(0), base); } @Test(groups={"tck"}) public void test_plusYears_big() { long years = 20L + Year.MAX_YEAR; assertEquals(Year.of(-40).plusYears(years), Year.of((int) (-40L + years))); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plusYears_max() { Year.of(Year.MAX_YEAR).plusYears(1); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plusYears_maxLots() { Year.of(Year.MAX_YEAR).plusYears(1000); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plusYears_min() { Year.of(Year.MIN_YEAR).plusYears(-1); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_plusYears_minLots() { Year.of(Year.MIN_YEAR).plusYears(-1000); } // minus(PeriodProvider) @Test(groups={"tck"}) public void test_minus_PeriodProvider() { PeriodProvider provider = Period.of(1, 2, 3, 4, 5, 6, 7); assertEquals(Year.of(2007).minus(provider), Year.of(2006)); } @Test(groups={"tck"}) public void test_minus_PeriodProvider_normalized() { PeriodProvider provider = PeriodFields.of(5, DECADES).with(3, YEARS).with(25, MONTHS); assertEquals(Year.of(2007).minus(provider), Year.of(2007 - 50 - 3)); // months ignored } @Test(groups={"tck"}) public void test_minus_PeriodProvider_otherFieldsIgnored() { PeriodProvider provider = Period.of(1, 27, 3, 4, 5, 6, 7); assertEquals(Year.of(2007).minus(provider), Year.of(2006)); // months ignored } @Test(groups={"implementation"}) public void test_minus_PeriodProvider_zero_same() { Year base = Year.of(2007); assertSame(base.minus(Period.ZERO), base); } @Test(groups={"tck"}) public void test_minus_PeriodProvider_zero_equals() { Year base = Year.of(2007); assertEquals(base.minus(Period.ZERO), base); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_minus_PeriodProvider_null() { Year.of(2007).minus((PeriodProvider) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_minus_PeriodProvider_badProvider() { Year.of(2007).minus(new MockPeriodProviderReturnsNull()); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minus_PeriodProvider_invalidPeriod() { PeriodProvider provider = PeriodField.of(20, MockOtherChronology.OTHER_MONTHS); Year.of(2010).minus(provider); } @Test(expectedExceptions=ArithmeticException.class, groups={"tck"}) public void test_minus_PeriodProvider_bigPeriod() { long years = 20L + Integer.MAX_VALUE; PeriodProvider provider = PeriodField.of(years, YEARS); Year.of(40).minus(provider); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minus_PeriodProvider_invalidTooLarge() { PeriodProvider provider = Period.ofYears(-1); Year.of(Year.MAX_YEAR).minus(provider); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minus_PeriodProvider_invalidTooSmall() { PeriodProvider provider = Period.ofYears(1); Year.of(Year.MIN_YEAR).minus(provider); } // minusYears() @Test(groups={"tck"}) public void test_minusYears() { assertEquals(Year.of(2007).minusYears(-1), Year.of(2008)); assertEquals(Year.of(2007).minusYears(0), Year.of(2007)); assertEquals(Year.of(2007).minusYears(1), Year.of(2006)); assertEquals(Year.of(2007).minusYears(2), Year.of(2005)); assertEquals(Year.of(Year.MAX_YEAR - 1).minusYears(-1), Year.of(Year.MAX_YEAR)); assertEquals(Year.of(Year.MAX_YEAR).minusYears(0), Year.of(Year.MAX_YEAR)); assertEquals(Year.of(Year.MIN_YEAR + 1).minusYears(1), Year.of(Year.MIN_YEAR)); assertEquals(Year.of(Year.MIN_YEAR).minusYears(0), Year.of(Year.MIN_YEAR)); } @Test(groups={"implementation"}) public void test_minusYear_zero_same() { Year base = Year.of(2007); assertSame(base.minusYears(0), base); } @Test(groups={"tck"}) public void test_minusYear_zero_equals() { Year base = Year.of(2007); assertEquals(base.minusYears(0), base); } @Test(groups={"tck"}) public void test_minusYears_big() { long years = 20L + Year.MAX_YEAR; assertEquals(Year.of(40).minusYears(years), Year.of((int) (40L - years))); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minusYears_max() { Year.of(Year.MAX_YEAR).minusYears(-1); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minusYears_maxLots() { Year.of(Year.MAX_YEAR).minusYears(-1000); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minusYears_min() { Year.of(Year.MIN_YEAR).minusYears(1); } @Test(expectedExceptions=CalendricalException.class, groups={"tck"}) public void test_minusYears_minLots() { Year.of(Year.MIN_YEAR).minusYears(1000); } // adjustDate(LocalDate) @Test(groups={"tck"}) public void test_adjustDate() { LocalDate base = LocalDate.of(2007, 2, 12); for (int i = -4; i <= 2104; i++) { LocalDate result = Year.of(i).adjustDate(base); assertEquals(result, LocalDate.of(i, 2, 12)); } } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_adjustDate_nullLocalDate() { Year test = Year.of(1); test.adjustDate((LocalDate) null); } // adjustDate(LocalDate,DateResolver) @Test(groups={"tck"}) public void test_adjustDate_strictResolver() { LocalDate base = LocalDate.of(2007, 2, 12); for (int i = -4; i <= 2104; i++) { LocalDate result = Year.of(i).adjustDate(base, DateResolvers.strict()); assertEquals(result, LocalDate.of(i, 2, 12)); } } @Test(expectedExceptions=InvalidCalendarFieldException.class, groups={"tck"}) public void test_adjustDate_strictResolver_feb29() { LocalDate base = LocalDate.of(2008, 2, 29); Year test = Year.of(2007); try { test.adjustDate(base, DateResolvers.strict()); } catch (InvalidCalendarFieldException ex) { assertEquals(ex.getRule(), ISODateTimeRule.DAY_OF_MONTH); throw ex; } } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_adjustDate_resolver_nullLocalDate() { Year test = Year.of(1); test.adjustDate((LocalDate) null, DateResolvers.strict()); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_adjustDate_resolver_nullResolver() { LocalDate date = LocalDate.of(2007, 1, 1); Year test = Year.of(1); test.adjustDate(date, (DateResolver) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_adjustDate_resolver_badResolver() { LocalDate date = LocalDate.of(2007, 1, 31); Year test = Year.of(2); test.adjustDate(date, new MockDateResolverReturnsNull()); } // matchesCalendrical(Calendrical) @Test(groups={"tck"}) public void test_matchesCalendrical_notLeapYear() { LocalDate work = LocalDate.of(2007, 3, 2); for (int i = -4; i <= 2104; i++) { for (int j = -4; j <= 2104; j++) { Year test = Year.of(j); assertEquals(test.matchesCalendrical(work), work.getYear() == j); } work = work.plusYears(1); } } @Test(groups={"tck"}) public void test_matchesCalendrical_noData() { assertEquals(Year.of(2009).matchesCalendrical(LocalTime.of(12, 30)), false); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_matchesCalendrical_nullLocalDate() { Year test = Year.of(1); test.matchesCalendrical((LocalDate) null); } // lengthInDays() @Test(groups={"tck"}) public void test_lengthInDays() { assertEquals(Year.of(1999).lengthInDays(), 365); assertEquals(Year.of(2000).lengthInDays(), 366); assertEquals(Year.of(2001).lengthInDays(), 365); assertEquals(Year.of(2007).lengthInDays(), 365); assertEquals(Year.of(2008).lengthInDays(), 366); assertEquals(Year.of(2009).lengthInDays(), 365); assertEquals(Year.of(2010).lengthInDays(), 365); assertEquals(Year.of(2011).lengthInDays(), 365); assertEquals(Year.of(2012).lengthInDays(), 366); assertEquals(Year.of(2095).lengthInDays(), 365); assertEquals(Year.of(2096).lengthInDays(), 366); assertEquals(Year.of(2097).lengthInDays(), 365); assertEquals(Year.of(2098).lengthInDays(), 365); assertEquals(Year.of(2099).lengthInDays(), 365); assertEquals(Year.of(2100).lengthInDays(), 365); assertEquals(Year.of(2101).lengthInDays(), 365); assertEquals(Year.of(2102).lengthInDays(), 365); assertEquals(Year.of(2103).lengthInDays(), 365); assertEquals(Year.of(2104).lengthInDays(), 366); assertEquals(Year.of(2105).lengthInDays(), 365); assertEquals(Year.of(-500).lengthInDays(), 365); assertEquals(Year.of(-400).lengthInDays(), 366); assertEquals(Year.of(-300).lengthInDays(), 365); assertEquals(Year.of(-200).lengthInDays(), 365); assertEquals(Year.of(-100).lengthInDays(), 365); assertEquals(Year.of(0).lengthInDays(), 366); assertEquals(Year.of(100).lengthInDays(), 365); assertEquals(Year.of(200).lengthInDays(), 365); assertEquals(Year.of(300).lengthInDays(), 365); assertEquals(Year.of(400).lengthInDays(), 366); assertEquals(Year.of(500).lengthInDays(), 365); } // isValidMonthDay(MonthOfYear) @Test(groups={"tck"}) public void test_isValidMonthDay_june() { Year test = Year.of(2007); MonthDay monthDay = MonthDay.of(6, 30); assertEquals(test.isValidMonthDay(monthDay), true); } @Test(groups={"tck"}) public void test_isValidMonthDay_febNonLeap() { Year test = Year.of(2007); MonthDay monthDay = MonthDay.of(2, 29); assertEquals(test.isValidMonthDay(monthDay), false); } @Test(groups={"tck"}) public void test_isValidMonthDay_febLeap() { Year test = Year.of(2008); MonthDay monthDay = MonthDay.of(2, 29); assertEquals(test.isValidMonthDay(monthDay), true); } @Test(groups={"tck"}) public void test_isValidMonthDay_null() { Year test = Year.of(2008); assertEquals(test.isValidMonthDay(null), false); } // // getEstimatedEra() // public void test_getEstimatedEra() { // assertEquals(Year.isoYear(2).getEstimatedEra(), Era.AD); // assertEquals(Year.isoYear(1).getEstimatedEra(), Era.AD); // assertEquals(Year.isoYear(0).getEstimatedEra(), Era.BC); // assertEquals(Year.isoYear(-1).getEstimatedEra(), Era.BC); // // getYearOfEstimatedEra() // public void test_getYearOfEstimatedEra() { // assertEquals(Year.isoYear(2).getYearOfEstimatedEra(), 2); // assertEquals(Year.isoYear(1).getYearOfEstimatedEra(), 1); // assertEquals(Year.isoYear(0).getYearOfEstimatedEra(), 1); // assertEquals(Year.isoYear(-1).getYearOfEstimatedEra(), 2); // // getISOCentury() // public void test_getISOCentury() { // assertEquals(Year.isoYear(2008).getISOCentury(), 20); // assertEquals(Year.isoYear(101).getISOCentury(), 1); // assertEquals(Year.isoYear(100).getISOCentury(), 1); // assertEquals(Year.isoYear(99).getISOCentury(), 0); // assertEquals(Year.isoYear(1).getISOCentury(), 0); // assertEquals(Year.isoYear(0).getISOCentury(), 0); // assertEquals(Year.isoYear(-1).getISOCentury(), 0); // assertEquals(Year.isoYear(-99).getISOCentury(), 0); // assertEquals(Year.isoYear(-100).getISOCentury(), -1); // assertEquals(Year.isoYear(-101).getISOCentury(), -1); // // getYearOfISOCentury() // public void test_getYearOfISOCentury() { // assertEquals(Year.isoYear(2008).getYearOfISOCentury(), 8); // assertEquals(Year.isoYear(101).getYearOfISOCentury(), 1); // assertEquals(Year.isoYear(100).getYearOfISOCentury(), 0); // assertEquals(Year.isoYear(99).getYearOfISOCentury(), 99); // assertEquals(Year.isoYear(1).getYearOfISOCentury(), 1); // assertEquals(Year.isoYear(0).getYearOfISOCentury(), 0); // assertEquals(Year.isoYear(-1).getYearOfISOCentury(), 1); // assertEquals(Year.isoYear(-99).getYearOfISOCentury(), 99); // assertEquals(Year.isoYear(-100).getYearOfISOCentury(), 0); // assertEquals(Year.isoYear(-101).getYearOfISOCentury(), 1); // atMonth(MonthOfYear) @Test(groups={"tck"}) public void test_atMonth() { Year test = Year.of(2008); assertEquals(test.atMonth(MonthOfYear.JUNE), YearMonth.of(2008, 6)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_atMonth_nullMonth() { Year test = Year.of(2008); test.atMonth((MonthOfYear) null); } // atMonth(int) @Test(groups={"tck"}) public void test_atMonth_int() { Year test = Year.of(2008); assertEquals(test.atMonth(6), YearMonth.of(2008, 6)); } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_atMonth_int_invalidMonth() { Year test = Year.of(2008); try { test.atMonth(13); } catch (IllegalCalendarFieldValueException ex) { assertEquals(ex.getRule(), ISODateTimeRule.MONTH_OF_YEAR); throw ex; } } // atMonthDay(MonthOfYear) @Test(groups={"tck"}) public void test_atMonthDay() { Year test = Year.of(2008); assertEquals(test.atMonthDay(MonthDay.of(6, 30)), LocalDate.of(2008, 6, 30)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_atMonthDay_nullMonthDay() { Year test = Year.of(2008); test.atMonthDay((MonthDay) null); } @Test(expectedExceptions=InvalidCalendarFieldException.class, groups={"tck"}) public void test_atMonthDay_invalidMonthDay() { Year test = Year.of(2008); try { test.atMonthDay(MonthDay.of(6, 31)); } catch (InvalidCalendarFieldException ex) { assertEquals(ex.getRule(), ISODateTimeRule.DAY_OF_MONTH); throw ex; } } // atDay(int) @Test(groups={"tck"}) public void test_atDay_notLeapYear() { Year test = Year.of(2007); LocalDate expected = LocalDate.of(2007, 1, 1); for (int i = 1; i <= 365; i++) { assertEquals(test.atDay(i), expected); expected = expected.plusDays(1); } } @Test(expectedExceptions=InvalidCalendarFieldException.class, groups={"tck"}) public void test_atDay_notLeapYear_day366() { Year test = Year.of(2007); try { test.atDay(366); } catch (InvalidCalendarFieldException ex) { assertEquals(ex.getRule(), ISODateTimeRule.DAY_OF_YEAR); throw ex; } } @Test(groups={"tck"}) public void test_atDay_leapYear() { Year test = Year.of(2008); LocalDate expected = LocalDate.of(2008, 1, 1); for (int i = 1; i <= 366; i++) { assertEquals(test.atDay(i), expected); expected = expected.plusDays(1); } } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_atDay_day0() { Year test = Year.of(2007); try { test.atDay(0); } catch (InvalidCalendarFieldException ex) { assertEquals(ex.getRule(), ISODateTimeRule.DAY_OF_YEAR); throw ex; } } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_atDay_day367() { Year test = Year.of(2007); try { test.atDay(367); } catch (InvalidCalendarFieldException ex) { assertEquals(ex.getRule(), ISODateTimeRule.DAY_OF_YEAR); throw ex; } } // toField() @Test(groups={"tck"}) public void test_toField() { assertEquals(Year.of(2010).toField(), YEAR.field(2010)); } // compareTo() @Test(groups={"tck"}) public void test_compareTo() { for (int i = -4; i <= 2104; i++) { Year a = Year.of(i); for (int j = -4; j <= 2104; j++) { Year b = Year.of(j); if (i < j) { assertEquals(a.compareTo(b), -1); assertEquals(b.compareTo(a), 1); assertEquals(a.isAfter(b), false); assertEquals(a.isBefore(b), true); assertEquals(b.isAfter(a), true); assertEquals(b.isBefore(a), false); } else if (i > j) { assertEquals(a.compareTo(b), 1); assertEquals(b.compareTo(a), -1); assertEquals(a.isAfter(b), true); assertEquals(a.isBefore(b), false); assertEquals(b.isAfter(a), false); assertEquals(b.isBefore(a), true); } else { assertEquals(a.compareTo(b), 0); assertEquals(b.compareTo(a), 0); assertEquals(a.isAfter(b), false); assertEquals(a.isBefore(b), false); assertEquals(b.isAfter(a), false); assertEquals(b.isBefore(a), false); } } } } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_compareTo_nullYear() { Year doy = null; Year test = Year.of(1); test.compareTo(doy); } // equals() / hashCode() @Test(groups={"tck"}) public void test_equals() { for (int i = -4; i <= 2104; i++) { Year a = Year.of(i); for (int j = -4; j <= 2104; j++) { Year b = Year.of(j); assertEquals(a.equals(b), i == j); assertEquals(a.hashCode() == b.hashCode(), i == j); } } } @Test(groups={"tck"}) public void test_equals_same() { Year test = Year.of(2011); assertEquals(test.equals(test), true); } @Test(groups={"tck"}) public void test_equals_nullYear() { Year doy = null; Year test = Year.of(1); assertEquals(test.equals(doy), false); } @Test(groups={"tck"}) public void test_equals_incorrectType() { Year test = Year.of(1); assertEquals(test.equals("Incorrect type"), false); } // toString() @Test(groups={"tck"}) public void test_toString() { for (int i = -4; i <= 2104; i++) { Year a = Year.of(i); assertEquals(a.toString(), "" + i); } } @DataProvider(name="badParseData") Object[][] provider_badParseData() { return new Object[][] { {"", 0}, {"-00", 1}, {"--01-0", 1}, {"A01", 0}, {"200", 0}, {"2009/12", 4}, {"-0000-10", 0}, {"-12345678901-10", 11}, {"+1-10", 1}, {"+12-10", 1}, {"+123-10", 1}, {"+1234-10", 0}, {"12345-10", 0}, {"+12345678901-10", 11}, }; } @Test(dataProvider="badParseData", expectedExceptions=CalendricalParseException.class, groups={"tck"}) public void factory_parse_fail(String text, int pos) { try { Year.parse(text); fail(String.format("Parse should have failed for %s at position %d", text, pos)); } catch (CalendricalParseException ex) { assertEquals(ex.getParsedString(), text); assertEquals(ex.getErrorIndex(), pos); throw ex; } } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_parse_nullText() { Year.parse(null); } // parse(DateTimeFormatter) @Test(groups={"tck"}) public void factory_parse_formatter() { Year t = Year.parse("2010 12", DateTimeFormatters.pattern("yyyy MM")); assertEquals(t, Year.of(2010)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_parse_formatter_nullText() { Year.parse((String) null, DateTimeFormatters.basicIsoDate()); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_parse_formatter_nullFormatter() { Year.parse("2010", null); } // parse() @DataProvider(name="goodParseData") Object[][] provider_goodParseData() { return new Object[][] { {"0000", Year.of(0)}, {"9999", Year.of(9999)}, {"2000", Year.of(2000)}, {"+12345678", Year.of(12345678)}, {"+123456", Year.of(123456)}, {"-1234", Year.of(-1234)}, {"-12345678", Year.of(-12345678)}, {"+" + Year.MAX_YEAR, Year.of(Year.MAX_YEAR)}, {"" + Year.MIN_YEAR, Year.of(Year.MIN_YEAR)}, }; } @Test(dataProvider="goodParseData", groups={"tck"}) public void factory_parse_success(String text, Year expected) { Year year = Year.parse(text); assertEquals(year, expected); } // toString(DateTimeFormatter) @Test(groups={"tck"}) public void test_toString_formatter() { String t = Year.of(2010).toString(DateTimeFormatters.pattern("yyyy")); assertEquals(t, "2010"); } @Test(groups={"tck"}) public void test_toString_formatter_non_standard() { String t = Year.of(2010).toString(DateTimeFormatters.pattern("yyyyyy")); assertEquals(t, "002010"); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_toString_formatter_null() { Year.of(2010).toString(null); } }
package rocks.matchmaker; import example.ast.Exchange; import example.ast.FilterNode; import example.ast.JoinNode; import example.ast.PlanNode; import example.ast.ProjectNode; import example.ast.ScanNode; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.function.Function; import java.util.stream.Stream; import static example.ast.Matchers.build; import static example.ast.Matchers.filter; import static example.ast.Matchers.join; import static example.ast.Matchers.plan; import static example.ast.Matchers.probe; import static example.ast.Matchers.project; import static example.ast.Matchers.scan; import static example.ast.Matchers.source; import static example.ast.Matchers.tableName; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static rocks.matchmaker.Capture.newCapture; import static rocks.matchmaker.Matcher.any; import static rocks.matchmaker.Matcher.equalTo; import static rocks.matchmaker.Matcher.isNull; import static rocks.matchmaker.Matcher.nullable; import static rocks.matchmaker.Matcher.typeOf; import static rocks.matchmaker.MatcherTest.PasswordProperty.has_digits; import static rocks.matchmaker.MatcherTest.PasswordProperty.has_lowercase; import static rocks.matchmaker.MatcherTest.PasswordProperty.has_uppercase; import static rocks.matchmaker.MatcherTest.PasswordProperty.length_at_least_8; import static rocks.matchmaker.PatternMatch.matchFor; import static rocks.matchmaker.Property.optionalProperty; import static rocks.matchmaker.Property.property; import static rocks.matchmaker.Property.self; @SuppressWarnings("WeakerAccess") public class MatcherTest { @Test void trivial_matchers() { //any assertMatch(any(), 42); assertMatch(any(), "John Doe"); //equalTo Matcher<Integer> theAnswer = equalTo(42); assertMatch(theAnswer, 42); assertNoMatch(theAnswer, 44); assertNoMatch(theAnswer, null); //no exception thrown Throwable throwable = assertThrows(IllegalArgumentException.class, () -> equalTo(null)); assertTrue(throwable.getMessage().contains("Use `Matcher.isNull()` instead")); //class based assertMatch(typeOf(Integer.class), 42); assertMatch(typeOf(Number.class), 42); assertNoMatch(typeOf(Integer.class), "John Doe"); //predicate-based assertMatch(typeOf(Integer.class).matching(x -> x > 0), 42); assertNoMatch(typeOf(Integer.class).matching(x -> x > 0), -1); } @Test void match_object() { assertMatch(project(), new ProjectNode(null)); assertNoMatch(project(), new ScanNode("t")); } @Test void property_matchers() { Matcher<String> aString = typeOf(String.class); Property<String, Integer> length = property(String::length); String string = "a"; assertMatch(aString.with(length.equalTo(1)), string); assertMatch(project().with(source().ofType(ScanNode.class)), new ProjectNode(new ScanNode("T"))); assertMatch(aString.with(length.matching(x -> x > 0)), string); assertMatch(aString.with(length.matching((Number x) -> x.intValue() > 0)), string); assertMatch(aString.with(length.matching((x, captures) -> Option.of(x.toString()))), string); assertMatch(aString.with(length.matching((x, captures) -> Option.of(x.toString()))), string); assertMatch(aString.with(length.matching(any())), string); assertMatch(aString.with(self().equalTo(string)), string); assertNoMatch(aString.with(length.equalTo(0)), string); assertNoMatch(project().with(source().ofType(ScanNode.class)), new ProjectNode(new ProjectNode(new ScanNode("T")))); assertNoMatch(aString.with(length.matching(x -> x < 1)), string); assertNoMatch(aString.with(length.matching((Number x) -> x.intValue() < 1)), string); assertNoMatch(aString.with(length.matching((x, captures) -> Option.empty())), string); assertNoMatch(aString.with(length.matching(typeOf(Void.class))), string); assertNoMatch(aString.with(self().equalTo("b")), string); } @Test void match_nested_properties() { Matcher<ProjectNode> matcher = project().with(source().matching(scan())); assertMatch(matcher, new ProjectNode(new ScanNode("t"))); assertNoMatch(matcher, new ScanNode("t")); assertNoMatch(matcher, new ProjectNode(null)); assertNoMatch(matcher, new ProjectNode(new ProjectNode(null))); } @Test void match_additional_properties() { Capture<List<String>> lowercase = newCapture(); String matchedValue = "A little string."; Matcher<List<String>> matcher = typeOf(String.class) .matching(s -> s.startsWith("A")) .matching((CharSequence s) -> s.length() > 0) .matching(endsWith("string.")) .matching((value, captures) -> Option.of(value).filter(v -> v.trim().equals(v))) .matching(hasLowercaseChars.capturedAs(lowercase)); List<String> lowercaseChars = characters("string.").collect(toList()); Match<List<String>> match = assertMatch(matcher, matchedValue, lowercaseChars); assertEquals(match.capture(lowercase), lowercaseChars); } private Extractor<String, String> endsWith(String suffix) { return (string, captures) -> Option.of(suffix).filter(__ -> string.endsWith(suffix)); } private Matcher<List<String>> hasLowercaseChars = typeOf(String.class).matching((string, captures) -> { List<String> lowercaseChars = characters(string).filter(this::isLowerCase).collect(toList()); return Option.of(lowercaseChars).filter(l -> !l.isEmpty()); }); private boolean isLowerCase(String string) { return string.toLowerCase().equals(string); } @Test void optional_properties() { Property<PlanNode, PlanNode> onlySource = optionalProperty(node -> Option.of(node.getSources()) .filter(sources -> sources.size() == 1) .map(sources -> sources.get(0))); Matcher<PlanNode> planNodeWithExactlyOneSource = plan() .with(onlySource.matching(any())); assertMatch(planNodeWithExactlyOneSource, new ProjectNode(new ScanNode("t"))); assertNoMatch(planNodeWithExactlyOneSource, new ScanNode("t")); assertNoMatch(planNodeWithExactlyOneSource, new JoinNode(new ScanNode("t"), new ScanNode("t"))); } @Test void capturing_matches_in_a_typesafe_manner() { Capture<FilterNode> filter = newCapture(); Capture<ScanNode> scan = newCapture(); Capture<String> name = newCapture(); Matcher<ProjectNode> matcher = project() .with(source().matching(filter().capturedAs(filter) .with(source().matching(scan().capturedAs(scan) .with(tableName().capturedAs(name)))))); ProjectNode tree = new ProjectNode(new FilterNode(new ScanNode("orders"), null)); Match<ProjectNode> match = assertMatch(matcher, tree); //notice the concrete type despite no casts: FilterNode capturedFilter = match.capture(filter); assertEquals(tree.getSource(), capturedFilter); assertEquals(((FilterNode) tree.getSource()).getSource(), match.capture(scan)); assertEquals("orders", match.capture(name)); } @Test void evidence_backed_matching_using_extractors() { Matcher<List<String>> stringWithVowels = typeOf(String.class).matching((x, captures) -> { List<String> vowels = characters(x).filter(c -> "aeiouy".contains(c.toLowerCase())).collect(toList()); return Option.of(vowels).filter(l -> !l.isEmpty()); }); Capture<List<String>> vowels = newCapture(); Match<List<String>> match = assertMatch(stringWithVowels.capturedAs(vowels), "John Doe", asList("o", "o", "e")); assertEquals(match.value(), match.capture(vowels)); assertNoMatch(stringWithVowels, "pqrst"); } private Stream<String> characters(String string) { return string.chars().mapToObj(c -> String.valueOf((char) c)); } @Test void no_match_means_no_captures() { Capture<Void> impossible = newCapture(); Matcher<Void> matcher = typeOf(Void.class).capturedAs(impossible); Match<Void> match = matcher.match(42); assertTrue(match.isEmpty()); Throwable throwable = assertThrows(NoSuchElementException.class, () -> match.capture(impossible)); assertTrue(() -> throwable.getMessage().contains("Empty match contains no value")); } @Test void unknown_capture_is_an_error() { Matcher<?> matcher = any(); Capture<?> unknownCapture = newCapture(); Match<?> match = matcher.match(42); Throwable throwable = assertThrows(NoSuchElementException.class, () -> match.capture(unknownCapture)); assertTrue(() -> throwable.getMessage().contains("unknown Capture")); //TODO make the error message somewhat help which capture was used, when the captures are human-discernable. } @Test void extractors_parameterized_with_captures() { Capture<JoinNode> root = newCapture(); Capture<JoinNode> parent = newCapture(); Capture<ScanNode> left = newCapture(); Capture<ScanNode> right = newCapture(); Capture<List<PlanNode>> caputres = newCapture(); Matcher<List<PlanNode>> accessingTheDesiredCaptures = plan().matching((node, params) -> Option.of(asList( params.get(left), params.get(right), params.get(root), params.get(parent) ))); Matcher<JoinNode> matcher = join().capturedAs(root) .with(probe().matching(join().capturedAs(parent) .with(probe().matching(scan().capturedAs(left))) .with(build().matching(scan().capturedAs(right))))) .with(build().matching(scan() .matching(accessingTheDesiredCaptures.capturedAs(caputres)))); ScanNode expectedLeft = new ScanNode("a"); ScanNode expectedRight = new ScanNode("b"); JoinNode expectedParent = new JoinNode(expectedLeft, expectedRight); JoinNode expectedRoot = new JoinNode(expectedParent, new ScanNode("c")); Match<JoinNode> match = assertMatch(matcher, expectedRoot); assertEquals(match.capture(caputres), asList(expectedLeft, expectedRight, expectedRoot, expectedParent)); } @Test void pattern_matching_for_single_result() { //We restrict the PatternMatch result type (here: Integer) //to achieve type safety in return type of the '.returns(...)' part. //We also restrict the type of the matchers used in cases (here: PlanNode) //to achieve type safety in input type of the '.returns(...)' part. Matcher<Integer> sourcesNumber = matchFor(PlanNode.class, Integer.class) .caseOf(scan()).returns(() -> 0) .caseOf(filter()).returns(() -> 1) .caseOf(project()).returns(() -> 1) .caseOf(join()).returns(() -> 2) .caseOf(plan()).returns(node -> node.getSources().size()) .returnFirst(); assertMatch(sourcesNumber, new ScanNode("t"), 0); assertMatch(sourcesNumber, new FilterNode(null, null), 1); assertMatch(sourcesNumber, new ProjectNode(null), 1); assertMatch(sourcesNumber, new JoinNode(null, null), 2); assertMatch(sourcesNumber, new Exchange(null, null, null), 3); } @Test void pattern_matching_for_single_result_with_negative_cases() { Matcher<Object> visitor = matchFor(Object.class, Object.class) .caseOf(typeOf(Integer.class)).returns(() -> "integer") .caseOf(typeOf(String.class)).returns(() -> "string") .returnFirst(); assertMatch(visitor, 42, "integer"); assertMatch(visitor, "John Doe", "string"); assertNoMatch(visitor, new Object()); assertNoMatch(visitor, null); } @Test void pattern_matching_for_multiple_results() { //Restricting the matcher return type (here: String) //also allows for easier definition of cases using predicates. Matcher<List<PasswordProperty>> passwordProperties = matchFor(String.class, PasswordProperty.class) .caseOf(s -> s.matches(".*?[A-Z].*")).returns(() -> has_uppercase) .caseOf(s -> s.matches(".*?[a-z].*")).returns(() -> has_lowercase) .caseOf(s -> s.matches(".*?[0-9].*")).returns(() -> has_digits) .caseOf(s -> s.length() >= 8).returns(() -> length_at_least_8) .returningAll(); assertMatch(passwordProperties, "foobar", asList(has_lowercase)); assertMatch(passwordProperties, "FooBar", asList(has_uppercase, has_lowercase)); assertMatch(passwordProperties, "1234567890", asList(has_digits, length_at_least_8)); assertMatch(passwordProperties, "aProperPassword111", asList(has_uppercase, has_lowercase, has_digits, length_at_least_8)); assertNoMatch(passwordProperties, ""); assertNoMatch(passwordProperties, "!@ } enum PasswordProperty { has_uppercase, has_lowercase, has_digits, length_at_least_8 } @Test void pattern_matching_for_single_result_with_captures() { Capture<ScanNode> scanNode = newCapture(); Matcher<PlanNode> joinMatcher = matchFor(PlanNode.class, PlanNode.class) .caseOf(join() .with(probe().matching(scan().capturedAs(scanNode))) ) .returns(Function.identity()) .caseOf(join() .with(build().matching(scan().capturedAs(scanNode))) ) .returns(Function.identity()) .returnFirst(); ScanNode scan = new ScanNode("t"); Match<PlanNode> first = assertMatch(joinMatcher, new JoinNode(scan, null)); assertEquals(scan, first.capture(scanNode)); Match<PlanNode> second = assertMatch(joinMatcher, new JoinNode(null, scan)); assertEquals(scan, second.capture(scanNode)); } @Test void narrows_down_tried_patterns_based_on_scope_type() { List<Class<?>> matchAttempts = new ArrayList<>(); PatternMatch<Object, Object> patternMatch = matchFor(Object.class, Object.class) .caseOf(registerMatch(Void.class, matchAttempts)).returns(Function.identity()) .caseOf(registerMatch(String.class, matchAttempts)).returns(Function.identity()) .caseOf(registerMatch(Integer.class, matchAttempts)).returns(Function.identity()) .caseOf(registerMatch(Number.class, matchAttempts)).returns(Function.identity()) .caseOf(registerMatch(Double.class, matchAttempts)).returns(Function.identity()) .caseOf(registerMatch(CharSequence.class, matchAttempts)).returns(Function.identity()) .caseOf(registerMatch(String.class, matchAttempts)).returns(Function.identity()); assertMatchAttempts(patternMatch.returnFirst(), 42, matchAttempts, Integer.class); assertMatchAttempts(patternMatch.returnFirst(), 0.1, matchAttempts, Number.class); assertMatchAttempts(patternMatch.returnFirst(), "foo", matchAttempts, String.class); assertMatchAttempts(patternMatch.returningAll(), 42, matchAttempts, Integer.class, Number.class); assertMatchAttempts(patternMatch.returningAll(), 0.1, matchAttempts, Number.class, Double.class); assertMatchAttempts(patternMatch.returningAll(), "foo", matchAttempts, String.class, CharSequence.class, String.class); assertMatchAttempts(patternMatch.returnFirst(), null, matchAttempts, Void.class); assertMatchAttempts(patternMatch.returningAll(), null, matchAttempts, Void.class, String.class, Integer.class, Number.class, Double.class, CharSequence.class, String.class); } private <T> Matcher<T> registerMatch(Class<T> scopeClass, List<Class<?>> matchAttemtpts) { return nullable(scopeClass).matching((x, captures) -> { matchAttemtpts.add(scopeClass); return Option.of(x); }); } private void assertMatchAttempts( Matcher<?> matcher, Object matchedObject, List<Class<?>> matchAttempts, Class<?>... expectedMatchAttempts ) { matcher.match(matchedObject); assertEquals(asList(expectedMatchAttempts), matchAttempts); matchAttempts.clear(); } @Test void null_not_matched_by_default() { assertNoMatch(any(), null); assertNoMatch(typeOf(Integer.class), null); //the predefined isNull matcher works as expected: assertMatch(isNull(), null); assertNoMatch(isNull(), 42); //nulls can be matched using the `nullable` matcher factory method as a starting point assertMatch(nullable(Integer.class), null); assertMatch(nullable(Integer.class), 42); //the nullable matchers work as expected when chained with predicates assertMatch(nullable(String.class).matching(value -> "John Doe".equals(value)), "John Doe"); assertNoMatch(nullable(String.class).matching(value -> "John Doe".equals(value)), null); //one has to be careful when basing off nullable matchers assertThrows(NullPointerException.class, () -> assertMatch(nullable(String.class).matching(x -> x.length() > 0), null)); } private <T> Match<T> assertMatch(Matcher<T> matcher, T expectedMatch) { return assertMatch(matcher, expectedMatch, expectedMatch); } private <T, R> Match<R> assertMatch(Matcher<R> matcher, T matchedAgainst, R expectedMatch) { Match<R> match = matcher.match(matchedAgainst); assertEquals(expectedMatch, match.value()); return match; } private <T> void assertNoMatch(Matcher<T> matcher, Object expectedNoMatch) { Match<T> match = matcher.match(expectedNoMatch); assertEquals(Match.empty(), match); } }
package unstable; import static org.loadui.testfx.controls.Commons.hasText; import java.util.List; import org.junit.Before; import org.junit.Test; import guitests.UITest; import prefs.Preferences; import ui.TestController; import ui.UI; import ui.issuepanel.PanelControl; public class BoardDuplicateTests extends UITest { PanelControl panelControl; @Before public void setupUIComponent() { UI ui = TestController.getUI(); panelControl = ui.getPanelControl(); Preferences testPref = UI.prefs; List<String> boardNames = testPref.getAllBoardNames(); boardNames.stream().forEach(testPref::removeBoard); } @Test public void duplicateNameTest() { // Save the current board traverseHubTurboMenu("Boards", "Save as"); waitUntilNodeAppears(hasText("OK")); // Use the default 'New Board' as board name // Workaround since we are unable to get text field into focus on Travis clickOn("OK"); waitAndAssertEquals(1, panelControl::getPanelCount); // Create a new panel, then save with the same name // Expected: Dialog shown to confirm duplicate name traverseHubTurboMenu("Panels", "Create"); traverseHubTurboMenu("Boards", "Save as"); waitUntilNodeAppears(hasText("OK")); // Sometimes not trigger if only click once doubleClickOn("OK"); waitUntilNodeAppears(hasText("A board by the name 'New Board' already exists.")); // Overwrite previous board, then open the board again // Expected: the board should contain 2 panels clickOn("Yes"); traverseHubTurboMenu("Boards", "Open", "New Board"); waitAndAssertEquals(2, panelControl::getPanelCount); // Create a new panel, then save with the same name to show warning dialog, // don't save and try to reopen board // Expected: Board is not overwritten, should contain 2 panels traverseHubTurboMenu("Panels", "Create"); traverseHubTurboMenu("Boards", "Save as"); waitUntilNodeAppears(hasText("OK")); clickOn("OK"); clickOn("No"); clickOn("Cancel"); traverseHubTurboMenu("Boards", "Open", "New Board"); // Abort saving changes waitUntilNodeAppears("No"); clickOn("No"); waitAndAssertEquals(2, panelControl::getPanelCount); } }
package utask.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static utask.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static utask.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static utask.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import utask.commons.core.EventsCenter; import utask.commons.events.model.UTaskChangedEvent; import utask.commons.events.ui.JumpToListRequestEvent; import utask.commons.events.ui.ShowHelpRequestEvent; import utask.logic.commands.ClearCommand; import utask.logic.commands.Command; import utask.logic.commands.CommandResult; import utask.logic.commands.CreateCommand; import utask.logic.commands.DeleteCommand; import utask.logic.commands.ExitCommand; import utask.logic.commands.FindCommand; import utask.logic.commands.HelpCommand; import utask.logic.commands.ListCommand; import utask.logic.commands.SelectCommand; import utask.logic.commands.exceptions.CommandException; import utask.model.Model; import utask.model.ModelManager; import utask.model.ReadOnlyUTask; import utask.model.UTask; import utask.model.tag.Tag; import utask.model.tag.UniqueTagList; import utask.model.task.Deadline; import utask.model.task.EventTask; import utask.model.task.Frequency; import utask.model.task.Name; import utask.model.task.ReadOnlyTask; import utask.model.task.Task; import utask.model.task.Timestamp; import utask.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; // These are for checking the correctness of the events raised private ReadOnlyUTask latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe public void handleLocalModelChangedEvent(UTaskChangedEvent abce) { latestSavedAddressBook = new UTask(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new UTask(model.getUTask()); // last // saved // assumed // date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and * that the result message is correct. Also confirms that both the 'address * book' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyUTask, * List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyUTask expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that * the result message is correct. Both the 'address book' and the 'last * shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyUTask, * List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { UTask expectedAddressBook = new UTask(model.getUTask()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that the result message is correct and * that a CommandException is thrown if expected and also confirms that the * following three parts of the LogicManager object's state are as * expected:<br> * - the internal address book data are same as those in the * {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyUTask expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } // Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); // Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getUTask()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new UTask(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new UTask(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new UTask(), Collections.emptyList()); } // @Test // public void execute_add_invalidArgsFormat() { // String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, CreateCommand.MESSAGE_USAGE); // assertCommandFailure("create valid Name /by invalidDate", expectedMessage); // assertCommandFailure("create valid Name /by 200217 /from invalid /tag important", expectedMessage); @Test public void execute_add_invalidTaskData() { //assertCommandFailure("create []\\[;]", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("create Valid Name /by Aa;a /from 1830 to 2030 /repeat Every Monday /tag urgent", Deadline.MESSAGE_DEADLINE_CONSTRAINTS); assertCommandFailure("create valid name /by 111111 /from /repeat Every Monday /tag urgent", Timestamp.MESSAGE_TIMESTAMP_CONSTRAINTS); assertCommandFailure("create valid name /by 111111 /from 0000 to 1200 /repeat Every Monday /tag ;a!!e", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.simpleTask(); UTask expectedAB = new UTask(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateCreateCommand(toBeAdded), String.format(CreateCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.simpleTask(); // setup starting state model.addTask(toBeAdded); // task already in internal address book // execute command and verify result assertCommandFailure(helper.generateCreateCommand(toBeAdded), CreateCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllPersons() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); UTask expectedAB = helper.generateAddressBook(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord, expectedMessage); // index missing assertCommandFailure(commandWord + " +1", expectedMessage); // index // should be // unsigned assertCommandFailure(commandWord + " -1", expectedMessage); // index // should be // unsigned assertCommandFailure(commandWord + " 0", expectedMessage); // index // cannot be assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new UTask()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); UTask expectedAB = helper.generateUTask(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generateTaskList(3); UTask expectedAB = helper.generateUTask(threePersons); expectedAB.removeTask(threePersons.get(1)); helper.addToModel(model, threePersons); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threePersons.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourPersons = helper.generateTaskList(p1, pTarget1, p2, pTarget2); UTask expectedAB = helper.generateUTask(fourPersons); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourPersons); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourPersons = helper.generateTaskList(p3, p1, p4, p2); UTask expectedAB = helper.generateUTask(fourPersons); List<Task> expectedList = fourPersons; helper.addToModel(model, fourPersons); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); UTask expectedAB = helper.generateUTask(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { private Task simpleTask() throws Exception { Name name = new Name("My debug task"); Deadline deadline = new Deadline("010117"); Timestamp timestamp = new Timestamp("1830 to 2030"); Frequency frequency = new Frequency("Every Monday"); Tag tag1 = new Tag("urgent"); Tag tag2 = new Tag("assignment"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new EventTask(name, deadline, timestamp, frequency, tags); } /** * Generates a valid task using the given seed. Running this function * with the same parameter values guarantees the returned task will * have the same state. Each unique seed will generate a unique Task * object. * * @param seed used to generate the task data field values */ private Task generateTask(int seed) throws Exception { return new EventTask(new Name("Task " + seed), new Deadline("010117"), new Timestamp("0000 to 2359"), new Frequency("Every " + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))); } /** Generates the correct add command based on the task given */ private String generateCreateCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("create "); cmd.append(p.getName().toString()); cmd.append(" /by ").append(p.getDeadline()); cmd.append(" /from ").append(p.getTimestamp()); cmd.append(" /repeat ").append(p.getFrequency()); UniqueTagList tags = p.getTags(); for (Tag t : tags) { cmd.append(" /tag ").append(t.tagName); } return cmd.toString(); } /** * Generates an UTask with auto-generated persons. */ private UTask generateAddressBook(int numGenerated) throws Exception { UTask uTask = new UTask(); addToUTask(uTask, numGenerated); return uTask; } /** * Generates an UTask based on the list of Tasks given. */ private UTask generateUTask(List<Task> tasks) throws Exception { UTask uTask = new UTask(); addToUTask(uTask, tasks); return uTask; } /** * Adds auto-generated Task objects to the given UTask * @param uTask * The UTask to which the Task will be added */ private void addToUTask(UTask uTask, int numGenerated) throws Exception { addToUTask(uTask, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given UTask */ private void addToUTask(UTask uTask, List<Task> tasksToAdd) throws Exception { for (Task p : tasksToAdd) { uTask.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model * The model to which the Persons will be added */ private void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Persons to the given model */ private void addToModel(Model model, List<Task> personsToAdd) throws Exception { for (Task p : personsToAdd) { model.addTask(p); } } /** * Generates a list of Persons based on the flags. */ private List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> persons = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { persons.add(generateTask(i)); } return persons; } private List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have * some dummy values. */ private Task generateTaskWithName(String name) throws Exception { return new EventTask(new Name(name), new Deadline("010117"), new Timestamp("0000 to 1300"), new Frequency("-"), new UniqueTagList(new Tag("tag"))); } } }
package tid.pce.pcepsession; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Inet4Address; import java.net.Socket; import java.util.LinkedList; import java.util.Timer; import java.util.logging.Logger; import tid.pce.pcep.PCEPProtocolViolationException; import tid.pce.pcep.constructs.ErrorConstruct; import tid.pce.pcep.messages.PCEPClose; import tid.pce.pcep.messages.PCEPError; import tid.pce.pcep.messages.PCEPKeepalive; import tid.pce.pcep.messages.PCEPMessage; import tid.pce.pcep.messages.PCEPMessageTypes; import tid.pce.pcep.messages.PCEPOpen; import tid.pce.pcep.objects.OPEN; import tid.pce.pcep.objects.ObjectParameters; import tid.pce.pcep.objects.PCEPErrorObject; import tid.pce.pcep.objects.tlvs.DomainIDTLV; import tid.pce.pcep.objects.tlvs.LSPDatabaseVersionTLV; import tid.pce.pcep.objects.tlvs.PCE_ID_TLV; import tid.pce.pcep.objects.tlvs.PCE_Redundancy_Group_Identifier_TLV; import tid.pce.pcep.objects.tlvs.SRCapabilityTLV; import tid.pce.pcep.objects.tlvs.StatefulCapabilityTLV; import tid.pce.server.RequestQueue; /** * Generic PCEP Session. * Implements the basics of a PCEP Session * Any particular session must inherit this one * * @author ogondio * */ public abstract class GenericPCEPSession extends Thread implements PCEPSession { /** * PCEP Session Manager */ protected PCEPSessionsInformation pcepSessionManager; /** * Thread to send periodic Keepalives */ protected KeepAliveThread keepAliveT = null; /** * Value of the Keepalive timer set by the Local PCE. Used to send keepalives */ protected int keepAliveLocal; /** * Value of the Keepalive timer of the peer PCC. It is not used in the server!!! */ protected int keepAlivePeer; /** * Thread to check if the connection is still alive. * If in this time the PCE has not received anything, it closes the session * It is set by the PCC (in this case, the remote peer) */ protected DeadTimerThread deadTimerT = null; /** * Value of the deadtimer that the PCE sends, so the PCC uses it * If in this time the PCC has not received anything, it closes the session * It is set by the PCE (in this case, the local peer) */ protected int deadTimerLocal; /** * Value of the deadtimer that the PCC sends. It is used in the PCC in the thread */ protected int deadTimerPeer; /** * Socket of the communication between PCC and PCE */ protected Socket socket = null; /** * DataOutputStream to send messages to the peer PCC */ protected DataOutputStream out=null; /** * DataInputStream to receive messages from PCC */ protected DataInputStream in=null; /** * Queue to send the Computing Path Requests */ protected RequestQueue req; /** * Logger to write the Parent PCE server log */ protected Logger log; /** * Timer to schedule KeepWait and OpenWait Timers */ protected Timer timer; /** * Finite State Machine of the PCEP protocol */ protected int FSMstate; /** * Remote PCE ID Address * null if not sent */ protected Inet4Address remotePCEId=null; /** * Remote Domain ID * null if not sent */ protected Inet4Address remoteDomainId=null; /** * Remote List of OF Codes * If sent by the peer PCE */ protected LinkedList<Integer> remoteOfCodes;//FIME: What do we do with them? /** * RemoteOK: a boolean that is set to 1 if the system has received an acceptable Open message. */ protected boolean remoteOK=false; protected boolean localOK=false; protected int openRetry=0; /** * Byte array to store the last PCEP message read. */ protected byte[] msg = null; /** * Initial number of the session ID (internal use only) */ public static long sessionIdCounter=0; /** * Session ID (internal use only) */ private long sessionId; /** * OPEN object of PCEPOpen message. It is used for stateful operations */ protected OPEN open; private boolean sendErrorStateful = false; protected boolean isSessionStateful = false; protected boolean isSessionSRCapable = false; protected int sessionMSD = 0; private long dbVersion; public GenericPCEPSession(PCEPSessionsInformation pcepSessionManager){ this.pcepSessionManager=pcepSessionManager; this.newSessionId(); this.pcepSessionManager.addSession(this.sessionId, this); } /** * Read PCE message from TCP stream * @param in InputStream */ protected byte[] readMsg(DataInputStream in) throws IOException{ byte[] ret = null; byte[] hdr = new byte[4]; byte[] temp = null; boolean endHdr = false; int r = 0; int length = 0; boolean endMsg = false; int offset = 0; while (!endMsg) { try { if (endHdr) { r = in.read(temp, offset, 1); } else { r = in.read(hdr, offset, 1); } } catch (IOException e){ log.info("Mistake reading data: "+ e.getMessage()); throw e; }catch (Exception e) { log.info("readMsg Oops: " + e.getMessage()); throw new IOException(); } if (r > 0) { if (offset == 2) { length = ((int)hdr[offset]&0xFF) << 8; } if (offset == 3) { length = length | (((int)hdr[offset]&0xFF)); temp = new byte[length]; endHdr = true; System.arraycopy(hdr, 0, temp, 0, 4); } if ((length > 0) && (offset == length - 1)) { endMsg = true; } offset++; } else if (r==-1){ log.info("End of stream has been reached"); //throw new IOException(); } } if (length > 0) { ret = new byte[length]; System.arraycopy(temp, 0, ret, 0, length); } return ret; } /** * Read PCE message from TCP stream * @param in InputStream */ protected byte[] readMsgOptimized(DataInputStream in) throws IOException{ byte[] ret = null; byte[] hdr = new byte[4]; byte[] temp = null; boolean endHdr = false; int r = 0; int length = 0; boolean endMsg = false; int offset = 0; while (!endMsg) { try { if (endHdr) { //log.info("Vamos a leer datos "); r = in.read(temp, offset, length-offset); if (r>0){ if ((offset+r)>=length){ //log.info("Bien "); endMsg=true; }else { offset=offset+r; } } else if (r<0){ log.severe("End of stream has been reached reading data"); throw new IOException(); } } else { //log.info("Vamos a leer la cabecera "); r = in.read(hdr, offset, 4-offset); if (r < 0) { log.severe("End of stream has been reached reading header"); throw new IOException(); }else if (r >0){ if ((offset+r)>=4){ length = ( (hdr[offset+2]&0xFF) << 8) | ((hdr[offset+3]&0xFF)); offset=4; temp = new byte[length]; endHdr = true; System.arraycopy(hdr, 0, temp, 0, 4); if (length==4){ endMsg=true; } }else { offset=offset+r; } } } } catch (IOException e){ log.severe("Error reading data: "+ e.getMessage()); throw e; }catch (Exception e) { log.severe("readMsg Oops: " + e.getMessage()); log.severe("FALLO POR : "+e.getStackTrace()); throw new IOException(); } } if (length > 0) { ret = new byte[length]; System.arraycopy(temp, 0, ret, 0, length); } return ret; } /** * <p>Close the PCE session</p> * <p>List of reasons (RFC 5440):</p> * Value Meaning 1 No explanation provided 2 DeadTimer expired 3 Reception of a malformed PCEP message 4 Reception of an unacceptable number of unknown requests/replies 5 Reception of an unacceptable number of unrecognized PCEP messages * @param reason Reason for closing the PCEP Session * @return PCEP Session closed OK */ public void close(int reason){ log.info("Closing PCEP Session"); PCEPClose p_close=new PCEPClose(); p_close.setReason(reason); sendPCEPMessage(p_close); killSession(); } public DataOutputStream getOut() { return out; } public void setOut(DataOutputStream out) { this.out = out; } /** * Starts the deadTimerThread */ protected void startDeadTimer() { this.deadTimerT.start(); } /** * Resets the DeadTimerThread * To be called every time a message in the session is received */ protected void resetDeadTimer() { if (this.deadTimerT != null) { this.deadTimerT.interrupt(); } } public Socket getSocket() { return socket; } /** * Ends the DeadTimer Thread */ protected void cancelDeadTimer() { log.fine("Cancelling DeadTimer"); if (this.deadTimerT != null) { this.deadTimerT.stopRunning(); this.deadTimerT.interrupt(); this.deadTimerT=null; } } /** * Starts the Keep Alive Thread */ public void startKeepAlive() { this.keepAliveT.start(); } /** * Ends the KeepAlive Thread */ public void cancelKeepAlive() { log.fine("Cancelling KeepAliveTimer"); if (this.keepAliveT != null) { this.keepAliveT.stopRunning(); this.keepAliveT.interrupt(); this.keepAliveT=null; } } /** * Ends current connections */ protected void endConnections(){ try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (this.socket != null) { log.info("Closing socket"); this.socket.close(); } } catch (Exception e) { log.info("Error closing connections: " + e.getMessage()); } } public int getFSMstate() { return FSMstate; } protected void setFSMstate(int fSMstate) { FSMstate = fSMstate; } public void killSession(){ log.info("Killing Session"); timer.cancel(); this.endConnections(); this.cancelDeadTimer(); this.cancelKeepAlive(); this.endSession(); this.pcepSessionManager.deleteSession(this.sessionId); log.info("Interrupting thread!!!!"); this.interrupt(); } /** * DO HERE ANYTHING NEEDED AT CLOSING?? * STATISTICS, ETC */ protected abstract void endSession(); /** * * @param zeroDeadTimerAccepted * @param minimumKeepAliveTimerAccepted * @param maxDeadTimerAccepted * @param isParentPCE * @param requestsParentPCE * @param domainId * @param pceId */ protected void initializePCEPSession(boolean zeroDeadTimerAccepted, int minimumKeepAliveTimerAccepted, int maxDeadTimerAccepted, boolean isParentPCE, boolean requestsParentPCE, Inet4Address domainId, Inet4Address pceId, int databaseVersion){ //private void initializePCEPSession(){ /** * Byte array to store the last PCEP message read. */ byte[] msg = null; //First get the input and output stream try { out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); } catch (IOException e) { log.info("Problem in the sockets, ending PCEPSession"); killSession(); return; } //STARTING PCEP SESSION ESTABLISHMENT PHASE //It begins in Open Wait State this.setFSMstate(PCEPValues.PCEP_STATE_OPEN_WAIT); log.info("Entering PCEP_STATE_OPEN_WAIT"); log.info("Scheduling Open Wait Timer"); //Create the 60 seconds Open Wait Timer to wait for an OPEN message OpenWaitTimerTask owtt= new OpenWaitTimerTask(this); this.timer.schedule(owtt, 60000); //Define (Not use yet), the keepwait timer KeepWaitTimerTask kwtt=new KeepWaitTimerTask(this); log.info("Sending OPEN Message"); PCEPOpen p_open_snd; p_open_snd=new PCEPOpen(); p_open_snd.setKeepalive(this.keepAliveLocal); p_open_snd.setDeadTimer(this.deadTimerLocal); if (isParentPCE){ p_open_snd.getOpen().setParentPCEIndicationBit(true); } if (requestsParentPCE==true){ p_open_snd.getOpen().setParentPCERequestBit(true); DomainIDTLV domain_id_tlv=new DomainIDTLV(); domain_id_tlv.setDomainId(domainId); p_open_snd.getOpen().setDomain_id_tlv(domain_id_tlv); PCE_ID_TLV pce_id_tlv=new PCE_ID_TLV(); pce_id_tlv.setPceId(pceId); p_open_snd.getOpen().setPce_id_tlv(pce_id_tlv); } if (pcepSessionManager.isStateful()) { log.info("Statefull: "+pcepSessionManager.isStateful()+" Active: "+pcepSessionManager.isActive()+ " Trigger sync: "+pcepSessionManager.isStatefulTFlag()+ " Incremental sync: "+pcepSessionManager.isStatefulDFlag()+ " include the LSP-DB-VERSION: "+pcepSessionManager.isStatefulSFlag()); StatefulCapabilityTLV stateful_capability_tlv = new StatefulCapabilityTLV(); /*STATEFUL CAPABILITY TLV*/ //Means this PCE is capable of updating LSPs stateful_capability_tlv.setuFlag(true); stateful_capability_tlv.setsFlag(true); stateful_capability_tlv.setdFlag(pcepSessionManager.isStatefulDFlag()); stateful_capability_tlv.settFlag(pcepSessionManager.isStatefulTFlag()); stateful_capability_tlv.setsFlag(pcepSessionManager.isStatefulSFlag()); p_open_snd.getOpen().setStateful_capability_tlv(stateful_capability_tlv); /*PCE REDUNDANCY GROUP IDENTIFIER TLV*/ PCE_Redundancy_Group_Identifier_TLV pce_redundancy_tlv = new PCE_Redundancy_Group_Identifier_TLV(); pce_redundancy_tlv.setRedundancyId(ObjectParameters.redundancyID); p_open_snd.getOpen().setRedundancy_indetifier_tlv(pce_redundancy_tlv); /*LSP DATABASE VERSION TLV*/ //For the time being, we put a value but it's not used so synchronization //won't be avoided. //Only send database version if S flag is active if (pcepSessionManager.isStatefulSFlag()) { LSPDatabaseVersionTLV lsp_database_version = new LSPDatabaseVersionTLV(); lsp_database_version.setLSPStateDBVersion(databaseVersion); p_open_snd.getOpen().setLsp_database_version_tlv(lsp_database_version); } } if (pcepSessionManager.isSRCapable()) { SRCapabilityTLV SR_capability_tlv = new SRCapabilityTLV(); //TODO: get? SR_capability_tlv.setMSD(pcepSessionManager.getMSD()); p_open_snd.getOpen().setSR_capability_tlv(SR_capability_tlv); log.info("SR: "+pcepSessionManager.isSRCapable()+" MSD: "+pcepSessionManager.getMSD()); } //Send the OPEN message sendPCEPMessage(p_open_snd); //Now, read messages until we are in SESSION UP while (this.FSMstate!=PCEPValues.PCEP_STATE_SESSION_UP){ try { //Read a new message msg = readMsg(in); }catch (IOException e){ log.info("Error reading message, ending session"+e.getMessage()); killSession(); return; } if (msg != null) {//If null, it is not a valid PCEP message switch(PCEPMessage.getMessageType(msg)) { case PCEPMessageTypes.MESSAGE_OPEN: log.info("OPEN Message Received"); if (this.FSMstate==PCEPValues.PCEP_STATE_OPEN_WAIT){ PCEPOpen p_open; try { p_open=new PCEPOpen(msg); log.finest(p_open.toString()); owtt.cancel(); //Check parameters if (openRetry==1){ boolean checkOK=true; boolean stateFulOK = true; boolean SROK = true; boolean updateEffective = false; int MSD = -1; this.deadTimerPeer=p_open.getDeadTimer(); this.keepAlivePeer=p_open.getKeepalive(); if (this.deadTimerPeer>maxDeadTimerAccepted){ checkOK=false; } if (this.deadTimerPeer==0){ if(zeroDeadTimerAccepted==false){ checkOK=false; } } if (this.keepAlivePeer<minimumKeepAliveTimerAccepted){ checkOK=false; } //If PCE is stateless and there are statefull tlv send error if ((!pcepSessionManager.isStateful())&& ((p_open.getOpen().getRedundancy_indetifier_tlv()!=null)|| (p_open.getOpen().getLsp_database_version_tlv()!=null)|| (p_open.getOpen().getStateful_capability_tlv()!=null))) { log.info("I'm not expeting Stateful session"); stateFulOK = false; } else if ((pcepSessionManager.isStateful())&&(p_open.getOpen().getStateful_capability_tlv()==null)) { log.info("I'm expeting Stateful session"); stateFulOK = false; } else if (pcepSessionManager.isStateful() && p_open.getOpen().getStateful_capability_tlv()!=null) { updateEffective = p_open.getOpen().getStateful_capability_tlv().isuFlag(); log.info("Other PCEP speaker is also stateful"); } else { log.info("Both PCEP speakers aren't stateful"); } if (!(pcepSessionManager.isSRCapable()) && (p_open.getOpen().getSR_capability_tlv()!=null)) { log.info("I'm not expecting SR session"); SROK = false; } else if ((pcepSessionManager.isSRCapable()) && (p_open.getOpen().getSR_capability_tlv()==null)) { log.info("I'm expeting SR capable session"); SROK = false; } else if ((pcepSessionManager.isSRCapable()) && (p_open.getOpen().getSR_capability_tlv()!=null)) { MSD = p_open.getOpen().getSR_capability_tlv().getMSD(); this.sessionMSD = MSD; //We will only look at this value in the session of a PCE //TODO: que hago con esto? log.info("Other component is also SR capable with MSD= "+p_open.getOpen().getSR_capability_tlv().getMSD()); } else { log.info("Neither of us are SR capable :("); } //TODO: Hay que cambiar esto if (stateFulOK == false) { //processNotStateful(p_open, kwtt); } if ((pcepSessionManager.isStateful())&&(updateEffective == false)) { // log.info("This PCE operates right now as if the LSPs are delegated"); } if (checkOK==false){ log.info("Dont accept deadTimerPeer "+deadTimerPeer+"keepAlivePeer "+keepAlivePeer); PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT); perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_SECOND_OPEN_MESSAGE_UNACCEPTABLE_SESSION_CHARACTERISTICS); ErrorConstruct error_c=new ErrorConstruct(); error_c.getErrorObjList().add(perrorObject); perror.setError(error_c); log.info("Sending Error and ending PCEPSession"); sendPCEPMessage(perror); } else { /** * If no errors are detected, and the session characteristics are * acceptable to the local system, the system: o Sends a Keepalive message to the PCEP peer, o Starts the Keepalive timer, o Sets the RemoteOK variable to 1. If LocalOK=1, the system clears the OpenWait timer and moves to the UP state. If LocalOK=0, the system clears the OpenWait timer, starts the KeepWait timer, and moves to the KeepWait state. */ log.info("Accept deadTimerPeer "+deadTimerPeer+"keepAlivePeer "+keepAlivePeer); if (p_open.getOpen().getPce_id_tlv()!=null){ this.remotePCEId=p_open.getOpen().getPce_id_tlv().getPceId(); } if (p_open.getOpen().getDomain_id_tlv()!=null){ this.remoteDomainId=p_open.getOpen().getDomain_id_tlv().getDomainId(); } if (p_open.getOpen().getOf_list_tlv()!=null){ this.remoteOfCodes=p_open.getOpen().getOf_list_tlv().getOfCodes(); } log.fine("Sending KA to confirm"); PCEPKeepalive p_ka= new PCEPKeepalive(); log.fine("Sending Keepalive message"); sendPCEPMessage(p_ka); //Creates the Keep Wait Timer to wait for a KA to acknowledge the OPEN sent //FIXME: START KA TIMER! this.deadTimerPeer=p_open.getDeadTimer(); this.keepAlivePeer=p_open.getKeepalive(); this.remoteOK=true; if(this.localOK==true){ log.info("Entering STATE_SESSION_UP"); this.setFSMstate(PCEPValues.PCEP_STATE_SESSION_UP); } else { log.info("Entering STATE_KEEP_WAIT"); log.fine("Scheduling KeepwaitTimer"); timer.schedule(kwtt, 60000); this.setFSMstate(PCEPValues.PCEP_STATE_KEEP_WAIT); } if (pcepSessionManager.isStateful()) { log.info("open object saved: "+p_open.getOpen()); this.open = p_open.getOpen(); isSessionStateful = true; } if (pcepSessionManager.isSRCapable()) { // this.open = p_open.getOpen(); isSessionSRCapable = true; sessionMSD = pcepSessionManager.getMSD(); } } } else {//Open retry is 0 boolean dtOK=true; boolean kaOK=true; boolean stateFulOK = true; boolean SROK = true; boolean updateEffective = false; int MSD = -1; //If PCE is stateless and there are statefull tlv send error if ((!pcepSessionManager.isStateful())&& ((p_open.getOpen().getRedundancy_indetifier_tlv()!=null)|| (p_open.getOpen().getLsp_database_version_tlv()!=null)|| (p_open.getOpen().getStateful_capability_tlv()!=null))) { log.info("I'm not expeting Stateful session"); stateFulOK = false; } else if ((pcepSessionManager.isStateful())&&(p_open.getOpen().getStateful_capability_tlv()==null)) { log.info("I'm expeting Stateful session"); stateFulOK = false; } else if (pcepSessionManager.isStateful() && p_open.getOpen().getStateful_capability_tlv()!=null) { updateEffective = p_open.getOpen().getStateful_capability_tlv().isuFlag(); log.info("Other PCEP speaker is also stateful"); } else { log.info("Both PCEP speakers aren't stateful"); } if (!(pcepSessionManager.isSRCapable()) && (p_open.getOpen().getSR_capability_tlv()!=null)) { log.info("I'm not expecting SR session"); SROK = false; } else if ((pcepSessionManager.isSRCapable()) && (p_open.getOpen().getSR_capability_tlv()==null)) { log.info("I'm expeting SR capable session"); SROK = false; } else if ((pcepSessionManager.isSRCapable()) && (p_open.getOpen().getSR_capability_tlv()!=null)) { MSD = p_open.getOpen().getSR_capability_tlv().getMSD(); this.sessionMSD = MSD; //We will only look at this value in the session of a PCE //TODO: que hago con esto? log.info("Other component is also SR capable with MSD= "+p_open.getOpen().getSR_capability_tlv().getMSD()); } else { log.info("Neither of us are SR capable :("); } //TODO: Hay que cambiar esto if (stateFulOK == false) { //processNotStateful(p_open, kwtt); } if ((pcepSessionManager.isStateful())&&(updateEffective == false)) { // log.info("This PCE operates right now as if the LSPs are delegated"); } if (p_open.getDeadTimer()>maxDeadTimerAccepted){ dtOK=false; } if (p_open.getDeadTimer()==0){ if(zeroDeadTimerAccepted==false){ dtOK=false; } } if (p_open.getKeepalive()<minimumKeepAliveTimerAccepted){ kaOK=false; } if ((kaOK == false) || (dtOK == false)){ ///Parameters are unacceptable but negotiable log.info("PEER PCC Open parameters are unaccpetable, but negotiable"); PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT); perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_UNACCEPTABLE_NEGOTIABLE_SESSION_CHARACTERISTICS); if (dtOK==false){ p_open.setDeadTimer(this.deadTimerLocal); } if (kaOK==false) { p_open.setKeepalive(this.keepAliveLocal); } if (stateFulOK==false) { p_open.setKeepalive(this.keepAliveLocal); } if (SROK == false) { p_open.setKeepalive(this.keepAliveLocal); } LinkedList<PCEPErrorObject> perrobjlist=new LinkedList<PCEPErrorObject>(); perrobjlist.add(perrorObject); perror.setErrorObjList(perrobjlist); perror.setOpen(p_open.getOpen()); log.info("Sending Error with new proposal"); this.sendPCEPMessage(perror); this.openRetry=this.openRetry+1; /** * o If LocalOK=1, the system restarts the OpenWait timer and stays in the OpenWait state. o If LocalOK=0, the system clears the OpenWait timer, starts the KeepWait timer, and moves to the KeepWait state. */ if (localOK==true){ log.info("Local ok esta a true, vamos a open wait"); owtt.cancel(); owtt= new OpenWaitTimerTask(this); this.timer.schedule(owtt, 60000); this.setFSMstate(PCEPValues.PCEP_STATE_OPEN_WAIT); } else { log.info("Local ok esta a false, vamos a keep wait"); owtt.cancel(); this.setFSMstate(PCEPValues.PCEP_STATE_KEEP_WAIT); this.timer.schedule(kwtt, 60000); } } else { /* * If no errors are detected, and the session characteristics are acceptable to the local system, the system: o Sends a Keepalive message to the PCEP peer, o Starts the Keepalive timer, o Sets the RemoteOK variable to 1. If LocalOK=1, the system clears the OpenWait timer and moves to the UP state. If LocalOK=0, the system clears the OpenWait timer, starts the KeepWait timer, and moves to the KeepWait state. */ if (p_open.getOpen().getPce_id_tlv()!=null){ this.remotePCEId=p_open.getOpen().getPce_id_tlv().getPceId(); } if (p_open.getOpen().getDomain_id_tlv()!=null){ this.remoteDomainId=p_open.getOpen().getDomain_id_tlv().getDomainId(); } if (p_open.getOpen().getOf_list_tlv()!=null){ this.remoteOfCodes=p_open.getOpen().getOf_list_tlv().getOfCodes(); } log.fine("Sending KA to confirm"); PCEPKeepalive p_ka= new PCEPKeepalive(); log.fine("Sending Keepalive message"); sendPCEPMessage(p_ka); //Creates the Keep Wait Timer to wait for a KA to acknowledge the OPEN sent //FIXME: START KA TIMER! this.deadTimerPeer=p_open.getDeadTimer(); this.keepAlivePeer=p_open.getKeepalive(); this.remoteOK=true; if(this.localOK==true){ log.info("Entering STATE_SESSION_UP"); this.setFSMstate(PCEPValues.PCEP_STATE_SESSION_UP); } else { log.info("Entering STATE_KEEP_WAIT"); log.fine("Scheduling KeepwaitTimer"); timer.schedule(kwtt, 60000); this.setFSMstate(PCEPValues.PCEP_STATE_KEEP_WAIT); } if (pcepSessionManager.isStateful()) { /* The open object is stored for later proccessing */ log.info("open object saved: "+p_open.getOpen()); this.open = p_open.getOpen(); isSessionStateful = true; } if (pcepSessionManager.isSRCapable()) { /* The open object is stored for later proccessing */ //this.open = p_open.getOpen(); isSessionSRCapable= true; sessionMSD = pcepSessionManager.getMSD(); } } } } catch (PCEPProtocolViolationException e1) { log.info("Malformed OPEN, INFORM ERROR and close"); e1.printStackTrace(); PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT); perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_INVALID_OPEN_MESSAGE); ErrorConstruct error_c=new ErrorConstruct(); error_c.getErrorObjList().add(perrorObject); perror.setError(error_c); log.info("Sending Error and ending PCEPSession"); sendPCEPMessage(perror); killSession(); }//Fin del catch de la exception PCEP } else{ log.info("Ignore OPEN message, already one received!!"); } break; case PCEPMessageTypes.MESSAGE_KEEPALIVE: log.info("KeepAlive Message Received"); this.localOK=true; if(this.FSMstate==PCEPValues.PCEP_STATE_KEEP_WAIT){ // If RemoteOK=1, the system clears the KeepWait timer and moves to // the UP state. // If RemoteOK=0, the system clears the KeepWait timer, starts the // OpenWait timer, and moves to the OpenWait State. if (remoteOK==true){ kwtt.cancel(); log.info("Entering STATE_SESSION_UP"); this.setFSMstate(PCEPValues.PCEP_STATE_SESSION_UP); } else{ kwtt.cancel(); log.info("Entering OPEN WAIT STATE"); owtt=new OpenWaitTimerTask(this); this.timer.schedule(owtt, 60000); this.setFSMstate(PCEPValues.PCEP_STATE_OPEN_WAIT); } } //If not... seguimos igual que estabamos //Mas KA no hacen mal... break; case PCEPMessageTypes.MESSAGE_ERROR: log.info("ERROR Message Received"); try { PCEPError msg_error=new PCEPError(msg); if (this.FSMstate==PCEPValues.PCEP_STATE_KEEP_WAIT){ int errorValue; if (msg_error.getError()!=null){ errorValue=msg_error.getError().getErrorObjList().get(0).getErrorValue(); } else { errorValue=msg_error.getErrorObjList().get(0).getErrorValue(); } if (errorValue==ObjectParameters.ERROR_ESTABLISHMENT_UNACCEPTABLE_NEGOTIABLE_SESSION_CHARACTERISTICS) { log.info("ERROR_ESTABLISHMENT_UNACCEPTABLE_NEGOTIABLE_SESSION_CHARACTERISTICS"); /** * If a PCErr message is received before the expiration of the KeepWait timer: 1. If the proposed values are unacceptable, the PCEP peer sends a PCErr message with Error-Type=1 and Error-value=6, and the system releases the PCEP resources for that PCEP peer, closes the TCP connection, and moves to the Idle state. 2. If the proposed values are acceptable, the system adjusts its PCEP session characteristics according to the proposed values received in the PCErr message, restarts the KeepWait timer, and sends a new Open message. If RemoteOK=1, the system restarts the KeepWait timer and stays in the KeepWait state. If RemoteOK=0, the system clears the KeepWait timer, starts the OpenWait timer, and moves to the OpenWait state. */ boolean checkOK=true; if (msg_error.getOpen().getDeadtimer()>maxDeadTimerAccepted){ checkOK=false; } if (msg_error.getOpen().getDeadtimer()==0){ if(zeroDeadTimerAccepted==false){ checkOK=false; } } if (msg_error.getOpen().getKeepalive()<minimumKeepAliveTimerAccepted){ checkOK=false; } if (checkOK==false){ //SendErrorAndClose PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT); perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_PCERR_UNACCEPTABLE_SESSION_CHARACTERISTICS); ErrorConstruct error_c=new ErrorConstruct(); error_c.getErrorObjList().add(perrorObject); perror.setError(error_c); log.info("Sending Error and ending PCEPSession"); sendPCEPMessage(perror); killSession(); return; } else{ this.deadTimerLocal=msg_error.getOpen().getDeadtimer(); this.keepAliveLocal=msg_error.getOpen().getKeepalive(); PCEPOpen p_open_snd2=new PCEPOpen(); p_open_snd2.setKeepalive(this.keepAliveLocal); p_open_snd2.setDeadTimer(this.deadTimerLocal); sendPCEPMessage(p_open_snd2); /** * If RemoteOK=1, the system restarts the KeepWait timer and stays in the KeepWait state. If RemoteOK=0, the system clears the KeepWait timer, starts the OpenWait timer, and moves to the OpenWait state. */ if (remoteOK==true){ kwtt.cancel(); this.setFSMstate(PCEPValues.PCEP_STATE_KEEP_WAIT); } else { kwtt.cancel(); this.timer.schedule(owtt, 60000); this.setFSMstate(PCEPValues.PCEP_STATE_OPEN_WAIT); } } } } else { log.info("Received PCErr and paramaters cant't be negotiated. PCEP Channel will be closed"); } } catch (PCEPProtocolViolationException e1) { log.info("problem decoding error, finishing PCEPSession "+e1); killSession(); } break; default: log.info("UNEXPECTED Message Received"); if (this.FSMstate!=PCEPValues.PCEP_STATE_OPEN_WAIT){ log.info("Ignore OPEN message, already one received!!"); } else { log.info("Unexpected message RECEIVED, closing"); PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT); perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_INVALID_OPEN_MESSAGE); log.info("Sending Error and ending PCEPSession"); ErrorConstruct error_c=new ErrorConstruct(); error_c.getErrorObjList().add(perrorObject); perror.setError(error_c); sendPCEPMessage(perror); } break; } } else { if (this.FSMstate!=PCEPValues.PCEP_STATE_OPEN_WAIT){ log.info("Ignore message, already one received!!"); } else { log.info("Unexpected message RECEIVED, closing"); PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_ESTABLISHMENT); perrorObject.setErrorValue(ObjectParameters.ERROR_ESTABLISHMENT_INVALID_OPEN_MESSAGE); ErrorConstruct error_c=new ErrorConstruct(); error_c.getErrorObjList().add(perrorObject); perror.setError(error_c); sendPCEPMessage(perror); } }//Fin del else }//Fin del WHILE } public void sendPCEPMessage(PCEPMessage message) { try { message.encode(); } catch (PCEPProtocolViolationException e11) { log.severe("ERROR ENCODING ERROR OBJECT, BUG DETECTED, INFORM!!! "+e11.getMessage()); log.severe("Ending Session"); e11.printStackTrace(); killSession(); } try { out.write(message.getBytes()); out.flush(); } catch (IOException e) { log.severe("Problem writing message, finishing session "+e.getMessage()); killSession(); } } public Inet4Address getRemotePCEId() { return remotePCEId; } public void setRemotePCEId(Inet4Address remotePCEId) { this.remotePCEId = remotePCEId; } public LinkedList<Integer> getRemoteOfCodes() { return remoteOfCodes; } public String shortInfo(){ StringBuffer sb=new StringBuffer(1000); if (this.socket!=null){ sb.append("remAddr: "); sb.append(this.socket.getRemoteSocketAddress()); sb.append(" state: "); if (this.FSMstate==PCEPValues.PCEP_STATE_OPEN_WAIT){ sb.append("OPEN_WAIT"); }else if (this.FSMstate==PCEPValues.PCEP_STATE_IDLE){ sb.append("IDLE"); }else if (this.FSMstate==PCEPValues.PCEP_STATE_KEEP_WAIT){ sb.append("KEEP_WAIT"); }else if (this.FSMstate==PCEPValues.PCEP_STATE_SESSION_UP){ sb.append("SESSION_UP"); }else if (this.FSMstate==PCEPValues.PCEP_STATE_SESSION_UP){ sb.append("TCP_PENDING"); }else { sb.append("UNKNOWN"); } } return sb.toString(); } public String toString(){ StringBuffer sb=new StringBuffer(1000); return sb.toString(); } public void newSessionId(){ this.sessionId=GenericPCEPSession.sessionIdCounter+1; sessionIdCounter=sessionIdCounter+1; } private void processNotStateful(PCEPOpen p_open, KeepWaitTimerTask kwtt) { if (sendErrorStateful) { PCEPError perror=new PCEPError(); PCEPErrorObject perrorObject=new PCEPErrorObject(); perrorObject.setErrorType(ObjectParameters.ERROR_INVALID_OPERATION); perrorObject.setErrorValue(ObjectParameters.ERROR_STATEFUL_CAPABILITY_NOT_SUPPORTED); ErrorConstruct error_c=new ErrorConstruct(); error_c.getErrorObjList().add(perrorObject); perror.setError(error_c); this.sendPCEPMessage(perror); } else { log.fine("Sending KA to confirm"); PCEPKeepalive p_ka= new PCEPKeepalive(); log.fine("Sending Keepalive message"); sendPCEPMessage(p_ka); //Creates the Keep Wait Timer to wait for a KA to acknowledge the OPEN sent //FIXME: START KA TIMER! this.deadTimerPeer=p_open.getDeadTimer(); this.keepAlivePeer=p_open.getKeepalive(); this.remoteOK=true; if(this.localOK==true){ log.info("Entering STATE_SESSION_UP"); this.setFSMstate(PCEPValues.PCEP_STATE_SESSION_UP); } else { log.info("Entering STATE_KEEP_WAIT"); log.fine("Scheduling KeepwaitTimer"); timer.schedule(kwtt, 60000); this.setFSMstate(PCEPValues.PCEP_STATE_KEEP_WAIT); } } isSessionStateful = false; } private boolean checkLSPsync(PCEPOpen p_open) { if (pcepSessionManager.isStatefulSFlag() && p_open.getOpen().getStateful_capability_tlv().issFlag()) { //if (data) } return false; } private void processNotSRCapable(PCEPOpen p_open, KeepWaitTimerTask kwtt) { //TODO: por hacer } }
package tk.wurst_client.features.mods; import java.util.HashSet; import java.util.LinkedList; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.network.play.client.CPacketAnimation; import net.minecraft.network.play.client.CPacketPlayerDigging; import net.minecraft.network.play.client.CPacketPlayerDigging.Action; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import tk.wurst_client.events.LeftClickEvent; import tk.wurst_client.events.listeners.LeftClickListener; import tk.wurst_client.events.listeners.RenderListener; import tk.wurst_client.events.listeners.UpdateListener; import tk.wurst_client.features.Feature; import tk.wurst_client.features.special_features.YesCheatSpf.BypassLevel; import tk.wurst_client.settings.ModeSetting; import tk.wurst_client.settings.SliderSetting; import tk.wurst_client.settings.SliderSetting.ValueDisplay; import tk.wurst_client.utils.BlockUtils; import tk.wurst_client.utils.RenderUtils; @Mod.Info( description = "Destroys blocks around you.\n" + "Use .nuker mode <mode> to change the mode.", name = "Nuker", help = "Mods/Nuker") @Mod.Bypasses public class NukerMod extends Mod implements LeftClickListener, RenderListener, UpdateListener { private float currentDamage; private EnumFacing side = EnumFacing.UP; private int blockHitDelay = 0; public static int id = 0; private BlockPos pos; private boolean shouldRenderESP; private int oldSlot = -1; public final SliderSetting range = new SliderSetting("Range", 6, 1, 6, 0.05, ValueDisplay.DECIMAL); public final ModeSetting mode = new ModeSetting("Mode", new String[]{"Normal", "ID", "Flat", "Smash"}, 0); @Override public String getRenderName() { switch(mode.getSelected()) { case 0: return "Nuker"; case 1: return "IDNuker [" + id + "]"; default: return mode.getSelectedMode() + "Nuker"; } } @Override public void initSettings() { settings.add(range); settings.add(mode); } @Override public Feature[] getSeeAlso() { return new Feature[]{wurst.mods.nukerLegitMod, wurst.mods.speedNukerMod, wurst.mods.tunnellerMod, wurst.mods.fastBreakMod, wurst.mods.autoMineMod, wurst.mods.overlayMod}; } @Override public void onEnable() { // disable other nukers if(wurst.mods.nukerLegitMod.isEnabled()) wurst.mods.nukerLegitMod.setEnabled(false); if(wurst.mods.speedNukerMod.isEnabled()) wurst.mods.speedNukerMod.setEnabled(false); if(wurst.mods.tunnellerMod.isEnabled()) wurst.mods.tunnellerMod.setEnabled(false); // add listeners wurst.events.add(LeftClickListener.class, this); wurst.events.add(UpdateListener.class, this); wurst.events.add(RenderListener.class, this); } @Override public void onDisable() { // remove listeners wurst.events.remove(LeftClickListener.class, this); wurst.events.remove(UpdateListener.class, this); wurst.events.remove(RenderListener.class, this); // reset slot if(oldSlot != -1) { mc.player.inventory.currentItem = oldSlot; oldSlot = -1; } // reset damage currentDamage = 0; // disable rendering shouldRenderESP = false; // reset ID id = 0; } @Override public void onRender() { if(!shouldRenderESP) return; // wait for timer if(blockHitDelay != 0) return; // check if block can be destroyed instantly if(mc.player.capabilities.isCreativeMode || BlockUtils.getState(pos) .getPlayerRelativeBlockHardness(mc.player, mc.world, pos) >= 1) RenderUtils.nukerBox(pos, 1); else RenderUtils.nukerBox(pos, currentDamage); } @Override public void onUpdate() { // disable rendering shouldRenderESP = false; // find position to nuke BlockPos newPos = find(); // check if any block was found if(newPos == null) { // reset slot if(oldSlot != -1) { mc.player.inventory.currentItem = oldSlot; oldSlot = -1; } return; } // reset damage if(!newPos.equals(pos)) currentDamage = 0; // set current pos & block pos = newPos; // wait for timer if(blockHitDelay > 0) { blockHitDelay return; } // face block BlockUtils.faceBlockPacket(pos); if(currentDamage == 0) { // start breaking the block mc.player.connection.sendPacket(new CPacketPlayerDigging( Action.START_DESTROY_BLOCK, pos, side)); // save old slot if(wurst.mods.autoToolMod.isActive() && oldSlot == -1) oldSlot = mc.player.inventory.currentItem; // check if block can be destroyed instantly if(mc.player.capabilities.isCreativeMode || BlockUtils.getState(pos) .getPlayerRelativeBlockHardness(mc.player, mc.world, pos) >= 1) { // reset damage currentDamage = 0; // nuke all if(mc.player.capabilities.isCreativeMode && wurst.special.yesCheatSpf.getBypassLevel() .ordinal() <= BypassLevel.MINEPLEX.ordinal()) nukeAll(); else { // enable rendering shouldRenderESP = true; // swing arm mc.player.swingArm(EnumHand.MAIN_HAND); // destroy block mc.playerController.onPlayerDestroyBlock(pos); } return; } } // AutoTool wurst.mods.autoToolMod.setSlot(pos); // swing arm mc.player.connection .sendPacket(new CPacketAnimation(EnumHand.MAIN_HAND)); // enable rendering shouldRenderESP = true; // update damage currentDamage += BlockUtils.getState(pos) .getPlayerRelativeBlockHardness(mc.player, mc.world, pos) * (wurst.mods.fastBreakMod.isActive() && wurst.mods.fastBreakMod.getMode() == 0 ? wurst.mods.fastBreakMod.speed.getValueF() : 1); // send damage to server mc.world.sendBlockBreakProgress(mc.player.getEntityId(), pos, (int)(currentDamage * 10) - 1); // check if block is ready to be destroyed if(currentDamage >= 1) { // destroy block mc.player.connection.sendPacket( new CPacketPlayerDigging(Action.STOP_DESTROY_BLOCK, pos, side)); mc.playerController.onPlayerDestroyBlock(pos); // reset delay blockHitDelay = 4; // reset damage currentDamage = 0; // FastBreak instant mode }else if(wurst.mods.fastBreakMod.isActive() && wurst.mods.fastBreakMod.getMode() == 1) // try to destroy block mc.player.connection.sendPacket( new CPacketPlayerDigging(Action.STOP_DESTROY_BLOCK, pos, side)); } @Override public void onLeftClick(LeftClickEvent event) { // check hitResult if(mc.objectMouseOver == null || mc.objectMouseOver.getBlockPos() == null) return; // check mode if(mode.getSelected() != 1) return; // check material if(BlockUtils .getMaterial(mc.objectMouseOver.getBlockPos()) == Material.AIR) return; // set id id = Block.getIdFromBlock( BlockUtils.getBlock(mc.objectMouseOver.getBlockPos())); } @Override public void onYesCheatUpdate(BypassLevel bypassLevel) { switch(bypassLevel) { default: case OFF: case MINEPLEX: range.unlock(); break; case ANTICHEAT: case OLDER_NCP: case LATEST_NCP: case GHOST_MODE: range.lockToMax(4.25); break; } } @SuppressWarnings("deprecation") private BlockPos find() { LinkedList<BlockPos> queue = new LinkedList<>(); HashSet<BlockPos> alreadyProcessed = new HashSet<>(); queue.add(new BlockPos(mc.player)); while(!queue.isEmpty()) { BlockPos currentPos = queue.poll(); if(alreadyProcessed.contains(currentPos)) continue; alreadyProcessed.add(currentPos); if(BlockUtils.getPlayerBlockDistance(currentPos) > range .getValueF()) continue; int currentID = Block .getIdFromBlock(mc.world.getBlockState(currentPos).getBlock()); if(currentID != 0) switch(mode.getSelected()) { case 1: if(currentID == id) return currentPos; break; case 2: if(currentPos.getY() >= mc.player.posY) return currentPos; break; case 3: if(mc.world.getBlockState(currentPos).getBlock() .getPlayerRelativeBlockHardness( mc.world.getBlockState(pos), mc.player, mc.world, currentPos) >= 1) return currentPos; break; default: return currentPos; } if(wurst.special.yesCheatSpf.getBypassLevel() .ordinal() <= BypassLevel.MINEPLEX.ordinal() || !mc.world.getBlockState(currentPos).getBlock() .getMaterial(null).blocksMovement()) { queue.add(currentPos.add(0, 0, -1));// north queue.add(currentPos.add(0, 0, 1));// south queue.add(currentPos.add(-1, 0, 0));// west queue.add(currentPos.add(1, 0, 0));// east queue.add(currentPos.add(0, -1, 0));// down queue.add(currentPos.add(0, 1, 0)); } } return null; } @SuppressWarnings("deprecation") private void nukeAll() { for(int y = (int)range.getValueF(); y >= (mode.getSelected() == 2 ? 0 : -range.getValueF()); y for(int x = (int)range.getValueF(); x >= -range.getValueF() - 1; x for(int z = (int)range.getValueF(); z >= -range.getValueF(); z { int posX = (int)(Math.floor(mc.player.posX) + x); int posY = (int)(Math.floor(mc.player.posY) + y); int posZ = (int)(Math.floor(mc.player.posZ) + z); BlockPos blockPos = new BlockPos(posX, posY, posZ); Block block = mc.world.getBlockState(blockPos).getBlock(); float xDiff = (float)(mc.player.posX - posX); float yDiff = (float)(mc.player.posY - posY); float zDiff = (float)(mc.player.posZ - posZ); float currentDistance = BlockUtils.getBlockDistance(xDiff, yDiff, zDiff); if(Block.getIdFromBlock(block) != 0 && posY >= 0 && currentDistance <= range.getValueF()) { if(mode.getSelected() == 1 && Block.getIdFromBlock(block) != id) continue; if(mode.getSelected() == 3 && block.getPlayerRelativeBlockHardness( mc.world.getBlockState(blockPos), mc.player, mc.world, blockPos) < 1) continue; side = mc.objectMouseOver.sideHit; shouldRenderESP = true; BlockUtils.faceBlockPacket(pos); mc.player.connection.sendPacket( new CPacketPlayerDigging(Action.START_DESTROY_BLOCK, blockPos, side)); block.onBlockDestroyedByPlayer(mc.world, blockPos, mc.world.getBlockState(blockPos)); } } } }
package tutorialspoint.networking;
package controller; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.servlet.ServletContext; import application.AppBean; import beans.list.ListInterface; import beans.list.ListItem; import beans.list.Synonym; import database.DBList; import properties.IntlConfiguration; import util.AppBeanPropertyHelper; import util.CRTLogger; import util.StringUtilities; /** * Creates Json files based on lists * Format: {"label": "Calcimycin", "value": "3"}, * Nursing items are either marked with "1" in the nursing column or added as additional item with "U" as type. * (U1.xxx are nursing diagnoses) * * Sep 2022: refactoring by gulpi (=Martin Adler): * <li>made it more generic and configurable by properties to make it more flexible for extension of lists</li> * * @author ingahege */ public class JsonCreator { // following constants are not longer used in db querying, however we keep them here public static final String TYPE_PROBLEM = "C"; public static final String TYPE_TEST = "E"; public static final String TYPE_EPI = "F"; public static final String TYPE_DRUGS = "D"; public static final String TYPE_PERSONS = "M"; public static final String TYPE_MANUALLY_ADDED = "MA"; public static final String TYPE_HEALTHCARE = "N"; public static final String TYPE_CONTEXT = "I"; public static final String TYPE_B = "B"; public static final String TYPE_G = "G"; public static final String TYPE_ANATOMY = "A"; public static final String TYPE_NURSING = "U"; //private boolean createOneList = true; //if false, we create multiple lists for problems, ddx, etc. private static ServletContext context; public synchronized void initJsonExport(ServletContext contextIn){ context = contextIn; String lang = null; //language can be set with a query parameter, e.g. when calling through list admin page try{ lang = AjaxController.getInstance().getRequestParamByKey("lang"); } catch(Exception e){} if(lang!=null){ exportGenericList("standard",new Locale(lang)); exportGenericList("nursing",new Locale(lang)); exportGenericList("context",new Locale(lang)); } else{ // loop thru all types String list_types = AppBean.getProperty("lists.types","standard,context,nursing"); List<String> list_types_list = net.casus.util.StringUtilities.getStringListFromString(list_types, ","); Iterator<String> list_types_list_it = list_types_list.iterator(); while(list_types_list_it.hasNext()) { String loop = list_types_list_it.next(); //Log.info("JsonCreator","list_type:" + loop); // loop thru all languages String languages = AppBean.getProperty("lists.languages." + loop,"en,de,pl,sv,es,pt,fr,uk"); List<String> languages_list = net.casus.util.StringUtilities.getStringListFromString(languages, ","); Iterator<String> languages_list_it = languages_list.iterator(); while(languages_list_it.hasNext()) { exportGenericList(loop,new Locale(languages_list_it.next())); } } } } public void setContext(ServletContext context){ JsonCreator.context = context; } /** * We export the list of the given language from the database into a JSON file for use in the user interface * We also store the list items in the SummaryController for using it for the statement analysis and assessment. * @param loc */ public File getGenericJsonFileByLoc(String type, String lang ){ String file = AppBean.getProperty("lists." + type,"jsonp_#{locale}.json"); List<String> getStringList = AppBeanPropertyHelper.getStringList("lists.languages.", type, null); if (getStringList != null && getStringList.contains(lang)) { file = net.casus.util.StringUtilities.replace(file, "#{locale}", lang != null ? lang : "en"); } else { return null; } if (file != null) { if (context != null) { return new File(context.getRealPath(AppBean.getProperty("lists.base","src/html/") + file)); } else { String name = file; int idx = name.lastIndexOf('/'); name = name.substring(idx+1); return new File(name); } } return null; } /** * We export the list of the given language from the database into a JSON file for use in the user interface * We also store the list items in the SummaryController for using it for the statement analysis and assessment. * @param loc */ @SuppressWarnings({ "rawtypes", "unchecked" }) public List exportGenericList(String type, Locale loc){ // dababase call configurable by lists.dbtypes.<type>=<STring delimioted by , (comma) with categories; lists.professionType.<type>=0 | 1; listvaliant for future extension List<ListItem> items = new DBList().selectListItemsByTypesAndLang(loc, AppBeanPropertyHelper.getArray("lists.dbtypes.", type, null), AppBeanPropertyHelper.getInt("lists.professionType.", type, 0), AppBeanPropertyHelper.getInt("lists.professionVariant.", type, -1)); if(items==null || items.isEmpty()) { CRTLogger.out("JsonCreator.exportGenericList(\"" + type + "\"," + loc + ") => items null | empty: " + items, CRTLogger.LEVEL_ERROR); return null; //then something went really wrong! } //we collect all items here, to sort it alphabetically List itemsAndSyns = new ArrayList(); try{ int lines = 0; int json_lines = 0; // preprocess for standard list onlky (until now -> configure by lists.preprocess.<type>=true | false if (AppBeanPropertyHelper.getBoolean("lists.preprocess.", type, false)) { lines = exportGenericList_preprocess(loc, items, itemsAndSyns, lines); } else { itemsAndSyns = items; } //SummaryStatementController.addListItems(itemsAndSyns, loc.getLanguage()); // should NOT happen!!!! if (itemsAndSyns != null) { Collections.sort(itemsAndSyns); json_lines = itemsAndSyns.size(); } // generate json entries StringBuffer sb = new StringBuffer("["); for(int i=0; i<itemsAndSyns.size();i++){ ListInterface li = (ListInterface) itemsAndSyns.get(i); String tmpName = li.getName(); tmpName = cleanJsonString(tmpName); sb.append("{\"label\": \"" + tmpName + "\", \"value\": \"" + li.getIdForJsonList() + "\"},\n"); } // own entries global and configurable per type lists.allowOwnEntries.<type>=true | false exportGenericList_ownEntries(type, loc, sb); // clean up -> remove last comma!! sb.replace(sb.length()-2, sb.length(), "]"); // write to file finally exportGenericList_write2File(type, loc, json_lines, sb); return itemsAndSyns; } catch( Exception e){ CRTLogger.out(StringUtilities.stackTraceToString(e), CRTLogger.LEVEL_PROD); return null; } } private String cleanJsonString(String tmpName) { tmpName = net.casus.util.StringUtilities.replace(tmpName, "\r\n", " "); tmpName = net.casus.util.StringUtilities.replace(tmpName, "\n\r", " "); tmpName = net.casus.util.StringUtilities.replace(tmpName, "\r", " "); tmpName = net.casus.util.StringUtilities.replace(tmpName, "\n", " "); return tmpName; } private void exportGenericList_write2File(String type, Locale loc, int json_lines, StringBuffer sb) throws IOException { File f = getGenericJsonFileByLoc(type,loc != null ? loc.getLanguage() : "en"); if (f != null) { PrintWriter pw = new PrintWriter(new FileWriter(f)); pw.print(sb.toString()); pw.flush(); pw.close(); CRTLogger.out("lines exported: " + json_lines + " to <" + (f!=null?f.getAbsolutePath():"-") + ">", CRTLogger.LEVEL_PROD); } else { CRTLogger.out("lines not exported: type:" + type + "and loc:" + loc + " ar not enabled!", CRTLogger.LEVEL_PROD); } } private void exportGenericList_ownEntries(String type, Locale loc, StringBuffer sb) { boolean allowOwnEntries = AppBean.getProperty("AllowOwnEntries", false); if (allowOwnEntries) { allowOwnEntries = AppBeanPropertyHelper.getBoolean("lists.allowOwnEntries.", type, false); } if(allowOwnEntries) { sb.append(getOwnEntry(loc)); } } private int exportGenericList_preprocess(Locale loc, List<ListItem> items, @SuppressWarnings("rawtypes") List itemsAndSyns, int lines) { for(int i=0; i<items.size(); i++){ ListItem item = items.get(i); //add items for SummaryStatement Rating if(doAddItem(item)){ lines += addItemAndSynonymaNew(item, itemsAndSyns); SummaryStatementController.addListItem(item, loc.getLanguage()); } else if(item.getFirstCode().startsWith("A")){ SummaryStatementController.addListItemsA(item, loc.getLanguage()); } else if(item.getFirstCode().startsWith("Z")){ //we add countries... SummaryStatementController.addListItem(item, loc.getLanguage()); } } return lines; } private String getOwnEntry(Locale loc){ String ownEntry = IntlConfiguration.getValue("list.ownEntry", loc); return "{\"label\": \""+ownEntry+"\", \"value\": \"-99\"},\n"; } /** * Make some improvements of the list, we do not add a certain item_level depending on the category etc. * maybe do more here.... * @param item * @return */ private boolean doAddItem(ListItem item){ if(item.isIgnored()) return false; if(item.getItemType().equals("D") && item.getLevel()>=10) return false; if(item.getItemType().equals("A")) return false; if(item.getFirstCode()==null) return true; if(item.getFirstCode().startsWith("D20.0") || item.getFirstCode().startsWith("D20.1")) return false; if(item.getFirstCode().startsWith("D20.3") || item.getFirstCode().startsWith("D20.4")) return false; if(item.getFirstCode().startsWith("D20.7") || item.getFirstCode().startsWith("D20.8")) return false; if(item.getFirstCode().startsWith("D20.9")) return false; if(item.getFirstCode().startsWith("D26.2")) return false; if(item.getFirstCode().startsWith("C22")) return false; //Animal diseases if(item.getName().startsWith("1") || item.getName().startsWith("2") || item.getName().startsWith("3")) return false; if(item.getName().startsWith("4-") || item.getName().startsWith("4,")) return false; if(item.getName().startsWith("5") || item.getName().startsWith("6") || item.getName().startsWith("7")) return false; if(item.getName().startsWith("8") || item.getName().startsWith("9")) return false; if(item.getName().contains("[")) return false; return true; } @SuppressWarnings("unchecked") private int addItemAndSynonymaNew(ListItem item, @SuppressWarnings("rawtypes") List itemsAndSyns/*PrintWriter pw, boolean lastEntry*/){ List<ListInterface> toAddItems = new ArrayList<ListInterface>(); if(item.getSynonyma()==null || item.getSynonyma().isEmpty()){ //no synonyma, only one main item: toAddItems.add(item); } //now we compare the synonyma else{ Iterator<Synonym> it = item.getSynonyma().iterator(); toAddItems.add(item); while(it.hasNext()){ Synonym syn = it.next(); if(!syn.isIgnored()){ boolean isSimilar = false; for(int i=0;i<toAddItems.size(); i++){ isSimilar = StringUtilities.similarStrings(toAddItems.get(i).getName(), syn.getName(), item.getLanguage(), false); if(isSimilar){ ListInterface bestItem = bestTerm(toAddItems.get(i),syn); if(!bestItem.equals(toAddItems.get(i))){ toAddItems.remove(i); toAddItems.add(i, bestItem); } break; } } if(!isSimilar && !toAddItems.contains(syn)) toAddItems.add(syn); } } } itemsAndSyns.addAll(toAddItems); return toAddItems.size(); } private ListInterface bestTerm(ListInterface currBestTerm, ListInterface newTerm){ if(!currBestTerm.getName().contains(" ")) return currBestTerm; //current term is one word if(!newTerm.getName().contains(" ")) return newTerm; //new term is one word -> better term if(currBestTerm.getName().contains(",") && !newTerm.getName().contains(",")) return newTerm; return currBestTerm; } /** * called from context bean: * configurable in properties: * this shouldbe used for defining lists in templates: * * <li>#{crtContext.getMyListUrl("<type>",crtContext.patillscript.locale)}</li> * <li>#{adminContext.getMyListUrl("standard",adminContext.patillscript.locale)}</li> * * <type> := (at this moment) standard | context | nursing (as defined for creation in lists.types property) * * lists.<mode>.<type> and overridable by: * lists.<mode>.<type>.<lang> * * * @param mode * @param type * @param lang * @return */ static public String getDisplayListName(String mode, String type, String lang) { String result = AppBean.getProperty("lists." + mode + "." + type,""); result = AppBean.getProperty("lists." + mode + "." + type + (lang!=null&&lang.length()>0 ? "." + lang : ""),result); List<String> getStringList = AppBeanPropertyHelper.getStringList("lists.languages.", type, null); if (getStringList != null && getStringList.contains(lang)) { result = net.casus.util.StringUtilities.replace(result, "#{locale}", lang != null ? lang : "en"); } else { result = ""; } return result; } }
package com.thaiopensource.xml.dtd; import java.util.Vector; class Decl { static final int REFERENCE = 0; // entity static final int REFERENCE_END = 1; static final int ELEMENT = 2; // params static final int ATTLIST = 3; // params static final int ENTITY = 4; // params static final int NOTATION = 5; // params static final int INCLUDE_SECTION = 6; // params + decls static final int IGNORE_SECTION = 7; // params + value static final int COMMENT = 8; // value static final int PROCESSING_INSTRUCTION = 9; // value Decl(int type) { this.type = type; } int type; Vector params; String value; Entity entity; Vector decls; public boolean equals(Object obj) { if (obj == null || !(obj instanceof Decl)) return false; Decl other = (Decl)obj; if (this.type != other.type) return false; if (this.entity != other.entity) return false; if (this.value != null && !this.value.equals(other.value)) return false; if (this.params != null) { int n = this.params.size(); if (other.params.size() != n) return false; for (int i = 0; i < n; i++) if (!this.params.elementAt(i).equals(other.params.elementAt(i))) return false; } return true; } TopLevel createTopLevel(DtdBuilder db) { switch (type) { case COMMENT: return new Comment(value); case PROCESSING_INSTRUCTION: return createProcessingInstruction(); case NOTATION: return createNotationDecl(); case ELEMENT: return createElementDecl(); case ATTLIST: return createAttlistDecl(); case ENTITY: return createEntityDecl(db); case INCLUDE_SECTION: return createIncludedSection(db); case IGNORE_SECTION: return createIgnoredSection(); } return null; } ElementDecl createElementDecl() { ParamStream ps = new ParamStream(params, true); ps.advance(); String name = ps.value; return new ElementDecl(name, Param.paramsToModelGroup(ps)); } AttlistDecl createAttlistDecl() { ParamStream ps = new ParamStream(params, true); ps.advance(); String name = ps.value; return new AttlistDecl(name, Param.paramsToAttributeGroup(ps)); } TopLevel createEntityDecl(DtdBuilder db) { ParamStream ps = new ParamStream(params); ps.advance(); if (ps.type != Param.PERCENT) return createGeneralEntityDecl(db, ps.value); ps.advance(); String name = ps.value; Entity entity = db.lookupParamEntity(name); if (entity.decl == null) entity.decl = this; if (entity.decl != this) return null; switch (entity.semantic) { case Entity.SEMANTIC_MODEL_GROUP: entity.modelGroup = entity.toModelGroup(); return new ModelGroupDef(name, entity.modelGroup); case Entity.SEMANTIC_ATTRIBUTE_GROUP: entity.attributeGroup = Param.paramsToAttributeGroup(entity.parsed); return new AttributeGroupDef(name, entity.attributeGroup); case Entity.SEMANTIC_DATATYPE: entity.datatype = Param.paramsToDatatype(entity.parsed); return new DatatypeDef(name, entity.datatype); case Entity.SEMANTIC_ENUM_GROUP: entity.enumGroup = Particle.particlesToEnumGroup(entity.parsed); return new EnumGroupDef(name, entity.enumGroup); case Entity.SEMANTIC_FLAG: entity.flag = Param.paramsToFlag(entity.parsed); return new FlagDef(name, entity.flag); } return null; } TopLevel createGeneralEntityDecl(DtdBuilder db, String name) { Entity entity = db.lookupGeneralEntity(name); if (entity.decl == null) entity.decl = this; if (entity.decl != this) return null; if (entity.text == null) return null; return new InternalEntityDecl(name, new String(entity.text)); } IncludedSection createIncludedSection(DtdBuilder db) { Flag flag = Param.paramsToFlag(params); Vector contents = declsToTopLevel(db, decls); TopLevel[] tem = new TopLevel[contents.size()]; for (int i = 0; i < tem.length; i++) tem[i] = (TopLevel)contents.elementAt(i); return new IncludedSection(flag, tem); } static Vector declsToTopLevel(DtdBuilder db, Vector decls) { Vector v = new Vector(); int n = decls.size(); for (int i = 0; i < n; i++) { TopLevel t = ((Decl)decls.elementAt(i)).createTopLevel(db); if (t != null) v.addElement(t); } return v; } IgnoredSection createIgnoredSection() { return new IgnoredSection(Param.paramsToFlag(params), value); } ProcessingInstruction createProcessingInstruction() { int len = value.length(); int i; for (i = 0; i < len && !isWS(value.charAt(i)); i++) ; String target = value.substring(0, i); if (i < len) { for (++i; i < len && isWS(value.charAt(i)); i++) ; } return new ProcessingInstruction(target, value.substring(i, len)); } static private boolean isWS(char c) { switch (c) { case '\n': case '\r': case '\t': case ' ': return true; } return false; } NotationDecl createNotationDecl() { return null; } }
package org.requs; import com.rexsl.test.XhtmlMatchers; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.hamcrest.MatcherAssert; import org.junit.Ignore; import org.junit.Test; /** * Test case for {@link Spec}. * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ public final class SpecTest { /** * Spec.Ultimate can parse input text and produce XML. * @throws IOException When necessary */ @Test public void parsesInputAndProducesXml() throws IOException { MatcherAssert.assertThat( new Spec.Ultimate( IOUtils.toString( this.getClass().getResourceAsStream("syntax/all-cases.req") ) ).xml(), XhtmlMatchers.hasXPaths( "/spec/types", "/spec/requs[version and revision and date]", "/spec/build[duration and time]", "/spec/metrics/ambiguity.overall[. > 0]", "//method/attributes" ) ); } /** * Spec.Ultimate can parse all possible errors. * @throws Exception When necessary */ @Test @Ignore @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public void parsesAllPossibleErrors() throws Exception { final String[] specs = { "\"alpha", "User is a", "User needs: a as", "UC1 where", }; for (final String spec : specs) { MatcherAssert.assertThat( new Spec.Ultimate(spec).xml(), XhtmlMatchers.hasXPath("/spec/errors/error") ); } } }
package net.katsuster.ememu.riscv.core; import net.katsuster.ememu.generic.*; import static net.katsuster.ememu.riscv.core.RV64CSRFile.*; /** * RISC-V 64bit * * RISC-V User-Level ISA V2.2 * RISC-V Privileged ISA V1.10 */ public class RV64 extends CPU64 { public static final int PRIV_U = 0; public static final int PRIV_S = 1; public static final int PRIV_RESERVED = 2; public static final int PRIV_M = 3; public static final int PRIV_MASK = 3; public static final int INTR_SOFT_U = 0; public static final int INTR_SOFT_S = 1; public static final int INTR_RESERVED1 = 2; public static final int INTR_SOFT_M = 3; public static final int INTR_TIMER_U = 4; public static final int INTR_TIMER_S = 5; public static final int INTR_RESERVED2 = 6; public static final int INTR_TIMER_M = 7; public static final int INTR_EXTERNAL_U = 8; public static final int INTR_EXTERNAL_S = 9; public static final int INTR_RESERVED3 = 10; public static final int INTR_EXTERNAL_M = 11; public static final int INTR_MAX = 16; public static final int EXCEPT_BASE = INTR_MAX; public static final int EXCEPT_INS_ALIGN = EXCEPT_BASE + 0; public static final int EXCEPT_INS_FAULT = EXCEPT_BASE + 1; public static final int EXCEPT_ILL = EXCEPT_BASE + 2; public static final int EXCEPT_BRK = EXCEPT_BASE + 3; public static final int EXCEPT_LDR_ALIGN = EXCEPT_BASE + 4; public static final int EXCEPT_LDR_FAULT = EXCEPT_BASE + 5; public static final int EXCEPT_STR_ALIGN = EXCEPT_BASE + 6; public static final int EXCEPT_STR_FAULT = EXCEPT_BASE + 7; public static final int EXCEPT_ENV_UMODE = EXCEPT_BASE + 8; public static final int EXCEPT_ENV_SMODE = EXCEPT_BASE + 9; public static final int EXCEPT_RESERVED1 = EXCEPT_BASE + 10; public static final int EXCEPT_ENV_MMODE = EXCEPT_BASE + 11; public static final int EXCEPT_INS_PAGEF = EXCEPT_BASE + 12; public static final int EXCEPT_LDR_PAGEF = EXCEPT_BASE + 13; public static final int EXCEPT_RESERVED2 = EXCEPT_BASE + 14; public static final int EXCEPT_STR_PAGEF = EXCEPT_BASE + 15; public static final int MAX_INTSRCS = 1; public static final int INTSRC_IRQ = 0; private RV64RegFile regfile; private RV64CSRFile csrfile; private NormalINTC intc; private int privMode; private boolean[] exceptions; private String[] exceptionReasons; private InstructionRV16 instRV16; private InstructionRV32 instRV32; private Opcode decinstAll; private DecodeStageRVI rviDec; private DecodeStageRVC rvcDec; private ExecStageRVI rviExe; private ExecStageRVC rvcExe; public RV64() { regfile = new RV64RegFile(); csrfile = new RV64CSRFile(this); intc = new NormalINTC(MAX_INTSRCS); intc.connectINTDestination(this); privMode = PRIV_M; exceptions = new boolean[16]; exceptionReasons = new String[16]; instRV16 = new InstructionRV16(0); instRV32 = new InstructionRV32(0); decinstAll = new Opcode(instRV32, OpType.INS_TYPE_UNKNOWN, OpIndex.INS_UNKNOWN); rviDec = new DecodeStageRVI(this); rvcDec = new DecodeStageRVC(this); rviExe = new ExecStageRVI(this); rvcExe = new ExecStageRVC(this); } @Override public void init() { //doExceptionReset("Init."); setPrivMode(PRIV_M); setPC(0x1004); setJumped(false); } @Override public String regsToString() { return regfile.toString(); } @Override public String getRegName(int n) { return regfile.getReg(n).getName(); } @Override public void connectINTSource(int n, INTSource c) { } @Override public void disconnectINTSource(int n) { } @Override public void nextPC(Inst32 inst) { if (isJumped()) { setJumped(false); return; } setPCRaw(getPCRaw() + inst.getLength()); } @Override public long getPC() { return getReg(RV64RegFile.REG_PC); } @Override public void setPC(long val) { setJumped(true); setReg(RV64RegFile.REG_PC, val); } @Override public long getPCRaw() { return getRegRaw(RV64RegFile.REG_PC); } @Override public void setPCRaw(long val) { setRegRaw(RV64RegFile.REG_PC, val); } @Override public void jumpRel(long val) { setPC(getPC() + val); } @Override public long getReg(int n) { return getRegRaw(n); } @Override public void setReg(int n, long val) { setRegRaw(n, val); } @Override public long getRegRaw(int n) { return regfile.getReg(n).getValue(); } @Override public void setRegRaw(int n, long val) { regfile.getReg(n).setValue(val); } /** * CSR * * @param n * @return */ public long getCSR(int n) { return csrfile.getReg(n).getValue(); } /** * CSR * * @param n * @param val */ public void setCSR(int n, long val) { csrfile.getReg(n).setValue(val); } /** * CSR * * @param n * @return */ public String getCSRName(int n) { return csrfile.getReg(n).getName(); } /** * RISC-V * * @return RV32 32RV64 64 */ public int getRVBits() { return 64; } /** * * * @return */ int getPrivMode() { return privMode; } /** * * * @param priv */ void setPrivMode(int priv) { privMode = priv; } private int[] xstatusRegs = { CSR_USTATUS, CSR_SSTATUS, -1, CSR_MSTATUS, }; /** * mstatus/sstatus/ustatus xIE * * @param priv * @return xIE */ public boolean getXIE(int priv) { int r = xstatusRegs[priv]; return BitOp.getBit64(getCSR(r), XSTATUS_XIE + priv); } /** * mstatus/sstatus/ustatus xIE * * @param priv * @param val xIE */ public void setXIE(int priv, boolean val) { int r = xstatusRegs[priv]; long v = BitOp.setBit64(getCSR(r), XSTATUS_XIE + priv, val); setCSR(r, v); } private int[] xtvecRegs = { CSR_UTVEC, CSR_STVEC, -1, CSR_MTVEC, }; /** * mtvec/stvec/utvec MODE * * @param priv * @return */ public int getXTVEC_MODE(int priv) { int r = xtvecRegs[priv]; return (int)(getCSR(r) & XTVEC_MODE_MASK); } private int[] xieRegs = { CSR_UIE, CSR_SIE, -1, CSR_MIE, }; /** * mie/sie/uie xSIE * * @param priv * @return xSIE */ public boolean getXIE_XSIE(int priv) { int r = xieRegs[priv]; return BitOp.getBit64(getCSR(r), XIE_XSIE + priv); } /** * mie/sie/uie xSIE * * @param priv * @param val xSIE */ public void setXIE_XSIE(int priv, boolean val) { int r = xieRegs[priv]; long v = BitOp.setBit64(getCSR(r), XIE_XSIE + priv, val); setCSR(r, v); } /** * mie/sie/uie xTIE * * @param priv * @return xTIE */ public boolean getXIE_XTIE(int priv) { int r = xieRegs[priv]; return BitOp.getBit64(getCSR(r), XIE_XTIE + priv); } /** * mie/sie/uie xTIE * * @param priv * @param val xTIE */ public void setXIE_XTIE(int priv, boolean val) { int r = xieRegs[priv]; long v = BitOp.setBit64(getCSR(r), XIE_XTIE + priv, val); setCSR(r, v); } /** * mie/sie/uie xEIE * * @param priv * @return xEIE */ public boolean getXIE_XEIE(int priv) { int r = xieRegs[priv]; return BitOp.getBit64(getCSR(r), XIE_XEIE + priv); } /** * mie/sie/uie xEIE * * @param priv * @param val xEIE */ public void setXIE_XEIE(int priv, boolean val) { int r = xieRegs[priv]; long v = BitOp.setBit64(getCSR(r), XIE_XEIE + priv, val); setCSR(r, v); } private int[] xipRegs = { CSR_UIP, CSR_SIP, -1, CSR_MIP, }; /** * mip/sip/uip xSIP * * @param priv * @return xSIP */ public boolean getXIP_XSIP(int priv) { int r = xipRegs[priv]; return BitOp.getBit64(getCSR(r), XIP_XSIP + priv); } /** * mip/sip/uip xSIP * * @param priv * @param val xSIP */ public void setXIP_XSIP(int priv, boolean val) { int r = xipRegs[priv]; long v = BitOp.setBit64(getCSR(r), XIP_XSIP + priv, val); setCSR(r, v); } /** * mip/sip/uip xTIP * * @param priv * @return xTIP */ public boolean getXIP_XTIP(int priv) { int r = xipRegs[priv]; return BitOp.getBit64(getCSR(r), XIP_XTIP + priv); } /** * mip/sip/uip xTIP * * @param priv * @param val xTIP */ public void setXIP_XTIP(int priv, boolean val) { int r = xipRegs[priv]; long v = BitOp.setBit64(getCSR(r), XIP_XTIP + priv, val); setCSR(r, v); } /** * mip/sip/uip xEIP * * @param priv * @return xEIP */ public boolean getXIP_XEIP(int priv) { int r = xipRegs[priv]; return BitOp.getBit64(getCSR(r), XIP_XEIP + priv); } /** * mip/sip/uip xEIP * * @param priv * @param val xEIP */ public void setXIP_XEIP(int priv, boolean val) { int r = xipRegs[priv]; long v = BitOp.setBit64(getCSR(r), XIP_XEIP + priv, val); setCSR(r, v); } public boolean isRaisedInternalInterrupt() { int ie = xieRegs[getPrivMode()]; int ip = xipRegs[getPrivMode()]; return (getCSR(ie) & getCSR(ip)) != 0; } private int[] xcauseRegs = { CSR_UCAUSE, CSR_SCAUSE, -1, CSR_MCAUSE, }; /** * mcause/scause/ucause Exception Code * * @param priv * @return */ public long getXCAUSE_CODE(int priv) { int r = xcauseRegs[priv]; int l = getRVBits() - 1; return BitOp.getField64(getCSR(r), XCAUSE_CODE, l); } /** * mcause/scause/ucause Exception Code * * @param priv * @param val */ public void setXCAUSE_CODE(int priv, long val) { int r = xcauseRegs[priv]; int l = getRVBits() - 1; long v = BitOp.setField64(getCSR(r), XCAUSE_CODE, l, val); setCSR(r, v); } /** * mcause/scause/ucause Interrupt * * @param priv * @return Interrupt */ public boolean getXCAUSE_INTR(int priv) { int r = xcauseRegs[priv]; return BitOp.getBit64(getCSR(r), XCAUSE_INTERRUPT); } /** * mcause/scause/ucause Interrupt * * @param priv * @param val Interrupt */ public void setXCAUSE_INTR(int priv, boolean val) { int r = xcauseRegs[priv]; long v = BitOp.setBit64(getCSR(r), XCAUSE_INTERRUPT, val); setCSR(r, v); } /** * * * @return */ public Inst32 fetch() { long vaddr, paddr; short v16; int v32; vaddr = getPCRaw(); paddr = vaddr; if (!tryRead(paddr, 2)) { //raiseException(EXCEPT_ABT_INST, // String.format("exec [%08x]", paddr)); return null; } v16 = read16(paddr); int aa = BitOp.getField32(v16, 0, 2); if (aa != 3) { //16bit instRV16.reuse(v16, 2); return instRV16; } int bbb = BitOp.getField32(v16, 2, 3); if (bbb != 7) { //32bit v32 = read_ua32(paddr); instRV32.reuse(v32, 4); return instRV32; } //TODO: Over 32bit is not support throw new IllegalArgumentException("Not support over 32bit length instructions"); } /** * * * @param instgen * @return */ public Opcode decode(Inst32 instgen) { OpType optype; OpIndex opind; if (instgen.getLength() == 4) { //RVI InstructionRV32 inst = (InstructionRV32) instgen; opind = rviDec.decode(inst); //TODO: opind optype = OpType.INS_TYPE_RVI; } else if (instgen.getLength() == 2) { //RVC InstructionRV16 inst = (InstructionRV16) instgen; opind = rvcDec.decode(inst); //TODO: opind optype = OpType.INS_TYPE_RVC; } else { throw new IllegalArgumentException(String.format( "Unknown instruction length %d.", instgen.getLength())); } decinstAll.reuse(instgen, optype, opind); return decinstAll; } /** * * * @param decinst */ public void disasm(Opcode decinst) { executeInst(decinst, false); } /** * * * @param decinst */ public void execute(Opcode decinst) { executeInst(decinst, true); } /** * * * @param decinst * @param exec true * false */ public void executeInst(Opcode decinst, boolean exec) { switch (decinst.getType()) { case INS_TYPE_RVI: rviExe.execute(decinst, exec); break; case INS_TYPE_RVC: rvcExe.execute(decinst, exec); break; default: throw new IllegalArgumentException("Unknown instruction type " + decinst.getType()); } } /** * * * @param num INTR_xxxx, EXCEPT_xxxx * @param dbgmsg */ public void raiseException(int num, String dbgmsg) { if (num < 0 || exceptions.length <= num) { throw new IllegalArgumentException("Illegal exception number " + num); } if (isRaisedException()) { throw new IllegalStateException("Exception status is not cleared."); } exceptions[num] = true; exceptionReasons[num] = dbgmsg; setRaisedException(true); } @Override public void step() { Inst32 inst; Opcode decinst; //doImportantException(); if (isRaisedInterrupt()) { //FIQ //acceptFIQ(); //if (isRaisedException()) { // setRaisedException(false); // return; //IRQ //acceptIRQ(); //if (isRaisedException()) { // setRaisedException(false); // return; //if (!intc.getINTSource(INTSRC_IRQ).isAssert() && // !intc.getINTSource(INTSRC_FIQ).isAssert()) { // setRaisedInterrupt(false); } inst = fetch(); if (isRaisedException()) { setRaisedException(false); return; } decinst = decode(inst); if (isEnabledDisasm()) { disasm(decinst); } //FIXME: for debug //if (getCPSR().getTBit()) { // setPrintInstruction(true); // disasm(decinst); execute(decinst); if (isRaisedException()) { setRaisedException(false); return; } nextPC(inst); } }
package org.olap4j; import org.olap4j.mdx.SelectNode; import org.olap4j.metadata.*; import org.olap4j.query.*; import org.olap4j.query.QueryDimension.HierarchizeMode; import org.olap4j.query.Selection.Operator; import org.olap4j.test.TestContext; import java.sql.Connection; import java.sql.DriverManager; import junit.framework.TestCase; /** * Unit test illustrating sequence of calls to olap4j API from a graphical * client. * * @since May 22, 2007 * @author James Dixon * @version $Id$ */ public class OlapTest extends TestCase { final TestContext.Tester tester = TestContext.instance().getTester(); private Connection connection; public OlapTest() { super(); } protected void tearDown() throws Exception { // Simple strategy to prevent connection leaks if (connection != null && !connection.isClosed()) { connection.close(); connection = null; } } public Cube getFoodmartCube(String cubeName) { try { connection = tester.createConnection(); OlapConnection olapConnection = tester.getWrapper().unwrap(connection, OlapConnection.class); final String catalogName; switch (tester.getFlavor()) { case MONDRIAN: catalogName = "LOCALDB"; break; case XMLA: default: catalogName = "FoodMart"; break; } Catalog catalog = olapConnection.getCatalogs().get(catalogName); NamedList<Schema> schemas = catalog.getSchemas(); if (schemas.size() == 0) { return null; } // Use the first schema Schema schema = schemas.get(0); // Get a list of cube objects and dump their names NamedList<Cube> cubes = schema.getCubes(); if (cubes.size() == 0) { // no cubes where present return null; } // take the first cube return cubes.get(cubeName); } catch (Exception e) { e.printStackTrace(); } return null; } public void testModel() { try { if (false) { // define the connection information String schemaUri = "file:/open/mondrian/demo/FoodMart.xml"; String schemaName = "FoodMart"; String userName = "foodmartuser"; String password = "foodmartpassword"; String jdbc = "jdbc:mysql://localhost/foodmart?user=foodmartuser" + "&password=foodmartpassword"; // Create a connection object to the specific implementation of an // olap4j source. This is the only provider-specific code. Class.forName("mondrian.olap4j.MondrianOlap4jDriver"); connection = DriverManager.getConnection( "jdbc:mondrian:Jdbc=" + jdbc + ";User=" + userName + ";Password=" + password + ";Catalog=" + schemaUri); } else { connection = tester.createConnection(); } OlapConnection olapConnection = tester.getWrapper().unwrap(connection, OlapConnection.class); // REVIEW: jhyde: Why do you want to name connections? We could add // a connect string property 'description', if that helps // connection.setName("First Connection"); // The code from here on is generic olap4j stuff // Get a list of the schemas available from this connection and dump // their names. final String catalogName; switch (tester.getFlavor()) { case MONDRIAN: catalogName = "LOCALDB"; break; case XMLA: default: catalogName = "FoodMart"; break; } Catalog catalog = olapConnection.getCatalogs().get(catalogName); NamedList<Schema> schemas = catalog.getSchemas(); if (schemas.size() == 0) { // No schemas were present return; } // Use the first schema Schema schema = schemas.get(0); // Get a list of cube objects and dump their names NamedList<Cube> cubes = schema.getCubes(); if (cubes.size() == 0) { // no cubes where present return; } // take the "Sales" cube Cube cube = cubes.get("Sales"); // The code from this point on is for the Foodmart schema // Create a new query Query query = new Query("my query", cube); QueryDimension productQuery = query.getDimension("Product"); QueryDimension storeQuery = query.getDimension("Store"); QueryDimension timeQuery = query.getDimension("Time"); //$NON-NLS-1$ Member productMember = cube.lookupMember("Product", "Drink"); // create some selections for Store storeQuery.include( Selection.Operator.CHILDREN, "Store", "USA"); // create some selections for Product productQuery.clearInclusions(); productQuery.include( Selection.Operator.CHILDREN, productMember); productQuery.include( Selection.Operator.CHILDREN, "Product", "Food"); // create some selections for Time timeQuery.include(Selection.Operator.CHILDREN, "Time", "1997"); // place our dimensions on the axes query.getAxis(Axis.COLUMNS).addDimension(productQuery); assert productQuery.getAxis() == query.getAxis(Axis.COLUMNS); query.getAxis(Axis.ROWS).addDimension(storeQuery); query.getAxis(Axis.ROWS).addDimension(timeQuery); try { query.getAxis(Axis.ROWS).addDimension(storeQuery); fail("expected exception"); } catch (Exception e) { assertTrue( e.getMessage().contains("dimension already on this axis")); } query.validate(); query.execute(); // for shits and giggles we'll swap the axes over query.swapAxes(); query.validate(); query.execute(); } catch (Throwable t) { t.printStackTrace(); fail(); } } public void testSelectionModes() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // TEST CHILDREN SELECTION QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.validate(); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{[Product].[All Products].[Drink].Children} ON ROWS\n" + "FROM [Sales]", mdxString); // TEST ANCESTORS SELECTION productDimension.clearInclusions(); productDimension.include( Selection.Operator.ANCESTORS, "Product", "Drink"); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{Ascendants([Product].[All Products].[Drink])} ON ROWS\n" + "FROM [Sales]", mdxString); // TEST DESCENDANTS SELECTION productDimension.clearInclusions(); productDimension.include( Selection.Operator.DESCENDANTS, "Product", "Drink"); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{Descendants([Product].[All Products].[Drink])} ON ROWS\n" + "FROM [Sales]", mdxString); // TEST INCLUDE_CHILDREN SELECTION productDimension.clearInclusions(); productDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Product", "Drink"); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{{[Product].[All Products].[Drink], [Product].[All Products].[Drink].Children}} ON ROWS\n" + "FROM [Sales]", mdxString); // TEST SIBLINGS SELECTION productDimension.clearInclusions(); productDimension.include( Selection.Operator.SIBLINGS, "Product", "Drink"); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{[Product].[All Products].[Drink].Siblings} ON ROWS\n" + "FROM [Sales]", mdxString); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testMultipleDimensionSelections() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink"); QueryDimension storeDimension = query.getDimension("Store"); storeDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Store", "USA"); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include(Selection.Operator.CHILDREN, "Time", "1997"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.ROWS).addDimension(storeDimension); query.getAxis(Axis.ROWS).addDimension(timeDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.validate(); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "CrossJoin({[Product].[All Products].[Drink].Children}, " + "CrossJoin({{[Store].[All Stores].[USA], " + "[Store].[All Stores].[USA].Children}}, " + "{[Time].[1997].Children})) ON ROWS\n" + "FROM [Sales]", mdxString); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSwapAxes() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.validate(); assertEquals( Axis.ROWS, productDimension.getAxis().getLocation()); assertEquals( Axis.COLUMNS, measuresDimension.getAxis().getLocation()); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{[Product].[All Products].[Drink].Children} ON ROWS\n" + "FROM [Sales]", mdxString); query.swapAxes(); assertEquals( Axis.COLUMNS, productDimension.getAxis().getLocation()); assertEquals( Axis.ROWS, measuresDimension.getAxis().getLocation()); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Product].[All Products].[Drink].Children} ON COLUMNS,\n" + "{[Measures].[Store Sales]} ON ROWS\n" + "FROM [Sales]", mdxString); query.swapAxes(); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSortDimension() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Product", "Drink"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include("Time", "Year", "1997", "Q3", "7"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.getAxis(Axis.FILTER).addDimension(timeDimension); query.validate(); assertEquals( Axis.ROWS, productDimension.getAxis().getLocation()); assertEquals( Axis.COLUMNS, measuresDimension.getAxis().getLocation()); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{{[Product].[All Products].[Drink], [Product].[All Products].[Drink].Children}} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q3].[7])", mdxString); // Sort the products in ascending order. query.getDimension("Product").sort(SortOrder.DESC); SelectNode sortedMdx = query.getSelect(); String sortedMdxString = sortedMdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{Order({{[Product].[All Products].[Drink], [Product].[All Products].[Drink].Children}}, [Product].CurrentMember.Name, DESC)} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q3].[7])", sortedMdxString); CellSet results = query.execute(); String s = TestContext.toString(results); TestContext.assertEqualsVerbose( "Axis + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997].[Q3].[7], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "Row #0: 4,409.58\n" + "Row #1: 629.69\n" + "Row #2: 2,477.02\n" + "Row #3: 1,302.87\n", s); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testSortAxis() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Product", "Drink"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include("Time", "Year", "1997", "Q3", "7"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.getAxis(Axis.FILTER).addDimension(timeDimension); query.validate(); assertEquals( Axis.ROWS, productDimension.getAxis().getLocation()); assertEquals( Axis.COLUMNS, measuresDimension.getAxis().getLocation()); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{{[Product].[All Products].[Drink], [Product].[All Products].[Drink].Children}} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q3].[7])", mdxString); // Sort the rows in ascending order. query.getAxis(Axis.ROWS).sort( SortOrder.BASC, "Measures", "Store Sales"); SelectNode sortedMdx = query.getSelect(); String sortedMdxString = sortedMdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "Order({{[Product].[All Products].[Drink], [Product].[All Products].[Drink].Children}}, [Measures].[Store Sales], BASC) ON ROWS\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q3].[7])", sortedMdxString); CellSet results = query.execute(); String s = TestContext.toString(results); TestContext.assertEqualsVerbose( "Axis + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997].[Q3].[7], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink]}\n" + "Row #0: 629.69\n" + "Row #1: 1,302.87\n" + "Row #2: 2,477.02\n" + "Row #3: 4,409.58\n", s); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testDimensionsOrder() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink"); QueryDimension storeDimension = query.getDimension("Store"); storeDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Store", "USA"); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include(Selection.Operator.CHILDREN, "Time", "1997"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.ROWS).addDimension(storeDimension); query.getAxis(Axis.ROWS).addDimension(timeDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.validate(); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "CrossJoin({[Product].[All Products].[Drink].Children}, " + "CrossJoin({{[Store].[All Stores].[USA], " + "[Store].[All Stores].[USA].Children}}, " + "{[Time].[1997].Children})) ON ROWS\n" + "FROM [Sales]", mdxString); // Push down the Products dimension. query.getAxis(Axis.ROWS).pushDown(0); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "CrossJoin({{[Store].[All Stores].[USA], " + "[Store].[All Stores].[USA].Children}}, " + "CrossJoin({[Product].[All Products].[Drink].Children}, " + "{[Time].[1997].Children})) ON ROWS\n" + "FROM [Sales]", mdxString); // Pull Up the Time dimension. query.getAxis(Axis.ROWS).pullUp(2); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "CrossJoin({{[Store].[All Stores].[USA], " + "[Store].[All Stores].[USA].Children}}, " + "CrossJoin({[Time].[1997].Children}, " + "{[Product].[All Products].[Drink].Children})) ON ROWS\n" + "FROM [Sales]", mdxString); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testDimensionsHierarchize() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink"); QueryDimension storeDimension = query.getDimension("Store"); storeDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Store", "USA"); storeDimension.setHierarchizeMode(HierarchizeMode.POST); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include(Selection.Operator.CHILDREN, "Time", "1997"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.ROWS).addDimension(storeDimension); query.getAxis(Axis.ROWS).addDimension(timeDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.validate(); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "CrossJoin({[Product].[All Products].[Drink].Children}, " + "CrossJoin({Hierarchize({{[Store].[All Stores].[USA], " + "[Store].[All Stores].[USA].Children}}, POST)}, " + "{[Time].[1997].Children})) ON ROWS\n" + "FROM [Sales]", mdxString); storeDimension.setHierarchizeMode(HierarchizeMode.PRE); query.validate(); mdx = query.getSelect(); mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "CrossJoin({[Product].[All Products].[Drink].Children}, " + "CrossJoin({Hierarchize({{[Store].[All Stores].[USA], " + "[Store].[All Stores].[USA].Children}})}, " + "{[Time].[1997].Children})) ON ROWS\n" + "FROM [Sales]", mdxString); } catch (Exception e) { e.printStackTrace(); fail(); } } /** * This test makes sure that the generated MDX model is not affected * by subsequent operations performed on the source query model. */ public void testQueryVersusParseTreeIndependence() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } // Setup a base query. Query query = new Query("my query", cube); QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Product", "Drink"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.validate(); assertEquals( Axis.ROWS, productDimension.getAxis().getLocation()); assertEquals( Axis.COLUMNS, measuresDimension.getAxis().getLocation()); // These variables are important. We will evaluate those // to decide if there are links between the MDX and the Query SelectNode originalMdx = query.getSelect(); String originalMdxString = originalMdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS,\n" + "{{[Product].[All Products].[Drink], [Product].[All Products].[Drink].Children}} ON ROWS\n" + "FROM [Sales]", originalMdxString); // change selections measuresDimension.include( Selection.Operator.SIBLINGS, "Measures", "Customer Count"); productDimension.include( Selection.Operator.SIBLINGS, "Product", "All Products", "Drink", "Alcoholic Beverages"); // Add something to crossjoin with query.getAxis(Axis.ROWS).addDimension( query.getDimension("Gender")); query.getDimension("Gender").include( Operator.CHILDREN, "Gender", "All Gender"); query.getAxis(Axis.UNUSED).addDimension( query.getDimension("Product")); query.validate(); // Check if the MDX object tree is still the same assertEquals(originalMdxString, originalMdx.toString()); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testExclusionModes() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } // Setup a base query. Query query = new Query("my query", cube); QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink", "Beverages"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Food", "Frozen Foods"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Sales Count"); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include("Time", "Year", "1997", "Q3", "7"); query.getAxis(Axis.ROWS).addDimension(productDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); query.getAxis(Axis.FILTER).addDimension(timeDimension); query.validate(); // Validate the generated MDX String mdxString = query.getSelect().toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Sales Count]} ON COLUMNS,\n" + "{[Product].[All Products].[Drink].[Beverages].Children, [Product].[All Products].[Food].[Frozen Foods].Children} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q3].[7])", mdxString); // Validate the returned results CellSet results = query.execute(); String resultsString = TestContext.toString(results); TestContext.assertEqualsVerbose( "Axis + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997].[Q3].[7], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "Axis + "{[Measures].[Sales Count]}\n" + "Axis + "{[Product].[All Products].[Drink].[Beverages].[Carbonated Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Hot Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Pure Juice Beverages]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Frozen Desserts]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Frozen Entrees]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Meat]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Pizza]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Vegetables]}\n" + "Row #0: 103\n" + "Row #1: 65\n" + "Row #2: 125\n" + "Row #3: 100\n" + "Row #4: 143\n" + "Row #5: 185\n" + "Row #6: 68\n" + "Row #7: 81\n" + "Row #8: 105\n" + "Row #9: 212\n", resultsString); // Exclude the Carbonated Beverages because they are not good // for your health. query.getDimension("Product").exclude( "Product", "Drink", "Beverages", "Carbonated Beverages"); // Validate the generated MDX query.validate(); mdxString = query.getSelect().toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Sales Count]} ON COLUMNS,\n" + "{Except({[Product].[All Products].[Drink].[Beverages].Children, [Product].[All Products].[Food].[Frozen Foods].Children}, {[Product].[All Products].[Drink].[Beverages].[Carbonated Beverages]})} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ([Time].[1997].[Q3].[7])", mdxString); // Validate the returned results results = query.execute(); resultsString = TestContext.toString(results); TestContext.assertEqualsVerbose( "Axis + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997].[Q3].[7], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "Axis + "{[Measures].[Sales Count]}\n" + "Axis + "{[Product].[All Products].[Drink].[Beverages].[Drinks]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Hot Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Pure Juice Beverages]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Frozen Desserts]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Frozen Entrees]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Meat]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Pizza]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Vegetables]}\n" + "Row #0: 65\n" + "Row #1: 125\n" + "Row #2: 100\n" + "Row #3: 143\n" + "Row #4: 185\n" + "Row #5: 68\n" + "Row #6: 81\n" + "Row #7: 105\n" + "Row #8: 212\n", resultsString); } catch (Exception e) { e.printStackTrace(); fail(); } } public void testNonMandatoryQueryAxis() { try { Cube cube = getFoodmartCube("Sales"); if (cube == null) { fail("Could not find Sales cube"); } Query query = new Query("my query", cube); // create selections QueryDimension productDimension = query.getDimension("Product"); productDimension.include( Selection.Operator.CHILDREN, "Product", "Drink"); QueryDimension storeDimension = query.getDimension("Store"); storeDimension.include( Selection.Operator.INCLUDE_CHILDREN, "Store", "USA"); storeDimension.setHierarchizeMode(HierarchizeMode.POST); QueryDimension timeDimension = query.getDimension("Time"); timeDimension.include(Selection.Operator.CHILDREN, "Time", "1997"); QueryDimension measuresDimension = query.getDimension("Measures"); measuresDimension.include("Measures", "Store Sales"); //query.getAxis(Axis.ROWS).addDimension(productDimension); //query.getAxis(Axis.ROWS).addDimension(storeDimension); //query.getAxis(Axis.ROWS).addDimension(timeDimension); query.getAxis(Axis.COLUMNS).addDimension(measuresDimension); //query.validate(); SelectNode mdx = query.getSelect(); String mdxString = mdx.toString(); TestContext.assertEqualsVerbose( "SELECT\n" + "{[Measures].[Store Sales]} ON COLUMNS\n" + "FROM [Sales]", mdxString); try { query.validate(); fail(); } catch (OlapException e) { assertEquals(0, e.getCause().getMessage().indexOf( "A valid Query requires at least one " + "dimension on the rows axis.")); } } catch (Exception e) { e.printStackTrace(); fail(); } } public static void main(String args[]) { OlapTest olapTest = new OlapTest(); olapTest.testModel(); } } // End OlapTest.java
package view; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.FloatBuffer; import javax.imageio.ImageIO; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLEventListener; import com.jogamp.opengl.GLException; import com.jogamp.opengl.glu.GLU; import com.jogamp.opengl.math.VectorUtil; import com.jogamp.opengl.util.awt.AWTGLReadBufferUtil; import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.TextureCoords; import com.jogamp.opengl.util.texture.TextureIO; import hochberger.utilities.application.ResourceLoader; import hochberger.utilities.threading.ThreadRunner; import hochberger.utilities.timing.Sleeper; import hochberger.utilities.timing.ToMilis; import model.HeightMap; import model.Position; public class OpticalSensorTerrainVisualization implements GLEventListener { private static final int WAIT_CYCLES = 5; private final GLU glu; private HeightMap points; private boolean takeScreenshotWithNextRender; private String screenshotFilePath; private int width; private int height; private Position position; private Position viewTargetPosition; private String nextScreenshotFilePath; private int waitCycles; private Texture texture; private int screenshotCounter; private float[][][] vertexNormals; public OpticalSensorTerrainVisualization(final int width, final int height) { super(); this.width = width; this.height = height; this.glu = new GLU(); this.points = new HeightMap(0); this.takeScreenshotWithNextRender = false; this.position = new Position(250, 1000, 250); this.viewTargetPosition = new Position(0, 0, 0); this.screenshotFilePath = System.getProperty("user.home"); this.waitCycles = WAIT_CYCLES; this.screenshotCounter = 0; this.vertexNormals = new float[0][0][0]; } @Override public void init(final GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glShadeModel(GL2.GL_SMOOTH); gl.glClearColor(0f, 0f, 0f, 0f); gl.glClearDepth(1.0f); gl.glEnable(GL2.GL_DEPTH_TEST); gl.glDepthFunc(GL2.GL_LEQUAL); gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST); gl.glEnable(GL2.GL_NORMALIZE); gl.glEnable(GL2.GL_CULL_FACE); final float h = (float) this.width / (float) this.height; gl.glViewport(0, 0, this.width, this.height); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); this.glu.gluPerspective(60.0, h, 0.1, 10000.0); gl.glMatrixMode(GL2.GL_MODELVIEW); try { this.texture = TextureIO.newTexture(ResourceLoader.loadStream("snow_2_512.jpg"), true, "jpg"); } catch (GLException | IOException e) { e.printStackTrace(); } this.texture.enable(gl); this.texture.bind(gl); } @Override public void dispose(final GLAutoDrawable drawable) { // TODO Auto-generated method stub } @Override public void display(final GLAutoDrawable drawable) { update(); render(drawable); } private void update() { // TODO Auto-generated method stub } private void render(final GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glClearDepth(1d); gl.glClearColor(0f, 0f, 0f, 0f); gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); gl.glPushMatrix(); lighting(gl); this.glu.gluLookAt(this.position.getX(), this.position.getY(), this.position.getZ(), this.viewTargetPosition.getX(), this.viewTargetPosition.getY(), this.viewTargetPosition.getZ(), 0, 0, -1); drawTerrain(gl); takeScreenShot(drawable); gl.glFlush(); gl.glPopMatrix(); } private void takeScreenShot(final GLAutoDrawable drawable) { if (!this.takeScreenshotWithNextRender) { return; } if (0 < --this.waitCycles) { return; } this.waitCycles = WAIT_CYCLES; this.takeScreenshotWithNextRender = false; final AWTGLReadBufferUtil util = new AWTGLReadBufferUtil(drawable.getGLProfile(), false); final BufferedImage image = util.readPixelsToBufferedImage(drawable.getGL(), true); final File outputfile = new File(this.nextScreenshotFilePath); ThreadRunner.startThread(new Runnable() { @Override public void run() { try { ImageIO.write(image, "png", outputfile); } catch (final IOException e) { e.printStackTrace(); } } }); } private void drawTerrain(final GL2 gl) { gl.glPushMatrix(); final float[] matShininess = { 50.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SHININESS, FloatBuffer.wrap(matShininess)); final float[] matAmbient = { 0.1f, 0.1f, 0.1f, 0.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT, FloatBuffer.wrap(matAmbient)); final float[] matDiffuse = { 0.7f, 0.7f, 0.7f, 1.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_DIFFUSE, FloatBuffer.wrap(matDiffuse)); final float[] matSpecular = { 1.0f, 1.0f, 1.0f, 1.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, FloatBuffer.wrap(matSpecular)); drawSurface(gl); gl.glPopMatrix(); } protected void drawSurface(final GL2 gl) { gl.glBegin(GL2.GL_QUADS); final TextureCoords coords = this.texture.getImageTexCoords(); for (int z = 0; z < this.points.getZDimension() - 1; z++) { for (int x = 0; x < this.points.getXDimension() - 1; x++) { gl.glNormal3f(this.vertexNormals[x][z][0], this.vertexNormals[x][z][1], this.vertexNormals[x][z][2]); gl.glVertex3d(x, this.points.get(x, z), z); gl.glTexCoord2d(coords.bottom(), coords.left()); gl.glNormal3f(this.vertexNormals[x][z + 1][0], this.vertexNormals[x][z + 1][1], this.vertexNormals[x][z + 1][2]); gl.glVertex3d(x, this.points.get(x, z + 1), (z + 1)); gl.glTexCoord2d(coords.top(), coords.left()); gl.glNormal3f(this.vertexNormals[x + 1][z + 1][0], this.vertexNormals[x + 1][z + 1][1], this.vertexNormals[x + 1][z + 1][2]); gl.glVertex3d((x + 1), this.points.get(x + 1, z + 1), (z + 1)); gl.glTexCoord2d(coords.top(), coords.right()); gl.glNormal3f(this.vertexNormals[x + 1][z][0], this.vertexNormals[x + 1][z][1], this.vertexNormals[x + 1][z][2]); gl.glVertex3d((x + 1), this.points.get(x + 1, z), z); gl.glTexCoord2d(coords.bottom(), coords.right()); } } gl.glEnd(); } @Override public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, int height) { this.width = width; this.height = height; final GL2 gl = drawable.getGL().getGL2(); if (height <= 0) { height = 1; } final float h = (float) width / (float) height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); this.glu.gluPerspective(45.0f, h, 1.0, 10000.0); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); } private void lighting(final GL2 gl) { gl.glShadeModel(GL2.GL_SMOOTH); final float[] ambientLight = { 0.4f, 0.4f, 0.4f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, ambientLight, 0); final float[] diffuseLight = { 0.7f, 0.7f, 0.7f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, diffuseLight, 0); final float[] specularLight = { 0.3f, 0.3f, 0.3f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPECULAR, specularLight, 0); final float[] lightPosition = { 10000.0f, 10000.0f, 10000.0f, 0f }; gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, FloatBuffer.wrap(lightPosition)); gl.glEnable(GL2.GL_LIGHTING); gl.glEnable(GL2.GL_LIGHT0); } private void calculateNormals(final HeightMap points) { final float[][][] areaNormals = new float[points.getXDimension()][points.getZDimension()][3]; for (int z = 0; z < points.getZDimension(); z++) { for (int x = 0; x < points.getXDimension(); x++) { final float[] one = { 0, (float) (points.get(x, z + 1) - points.get(x, z)), 1 }; final float[] two = { 1, (float) (points.get(x + 1, z) - points.get(x, z)), 0 }; areaNormals[x][z] = VectorUtil.crossVec3(areaNormals[x][z], one, two); } } this.vertexNormals = new float[points.getXDimension()][points.getZDimension()][3]; for (int z = 1; z < points.getZDimension(); z++) { for (int x = 1; x < points.getXDimension(); x++) { for (int i = 0; i < 3; i++) { this.vertexNormals[x][z][i] = (areaNormals[x][z][i] + areaNormals[x - 1][z][i] + areaNormals[x][z - 1][i] + areaNormals[x - 1][z - 1][i]) / 4f; } this.vertexNormals[x][z] = VectorUtil.normalizeVec3(this.vertexNormals[x][z]); } } } public void setPoints(final HeightMap points) { this.points = new HeightMap(0); calculateNormals(points); Sleeper.sleep(ToMilis.seconds(0.5)); this.points = points; this.position = new Position(points.getXDimension() / 2d, 1.5 * points.getXDimension(), points.getZDimension() / 2d); this.viewTargetPosition = new Position(points.getXDimension() / 2d, 0, points.getZDimension() / 2d); } public String prepareScreenshot() { this.takeScreenshotWithNextRender = true; this.nextScreenshotFilePath = this.screenshotFilePath + "/terrain_" + System.currentTimeMillis() + "_" + (++this.screenshotCounter) + ".png"; return this.nextScreenshotFilePath; } public void setScreenshotStorageFolder(final String filepath) { this.screenshotFilePath = filepath; } public void setOpticalSensor(final Position position, final Position viewTargetPosition) { this.position = position; this.viewTargetPosition = viewTargetPosition; } }
package etomica.integrator; import java.io.Serializable; import etomica.EtomicaInfo; import etomica.atom.AtomLeafAgentManager; import etomica.atom.AtomSet; import etomica.atom.AtomTypeLeaf; import etomica.atom.IAtom; import etomica.atom.IAtomKinetic; import etomica.atom.AtomAgentManager.AgentSource; import etomica.atom.iterator.IteratorDirective; import etomica.exception.ConfigurationOverlapException; import etomica.phase.Phase; import etomica.potential.PotentialCalculationForcePressureSum; import etomica.potential.PotentialCalculationForceSum; import etomica.potential.PotentialMaster; import etomica.simulation.Simulation; import etomica.space.IVector; import etomica.space.Space; import etomica.space.Tensor; import etomica.util.IRandom; public class IntegratorVelocityVerlet extends IntegratorMD implements AgentSource { private static final long serialVersionUID = 2L; protected PotentialCalculationForceSum forceSum; private final IteratorDirective allAtoms; protected final Tensor pressureTensor; protected final Tensor workTensor; protected AtomLeafAgentManager agentManager; public IntegratorVelocityVerlet(Simulation sim, PotentialMaster potentialMaster) { this(potentialMaster, sim.getRandom(), sim.getDefaults().timeStep, sim.getDefaults().temperature); } public IntegratorVelocityVerlet(PotentialMaster potentialMaster, IRandom random, double timeStep, double temperature) { super(potentialMaster,random,timeStep,temperature); // if you're motivated to throw away information earlier, you can use // PotentialCalculationForceSum instead. forceSum = new PotentialCalculationForcePressureSum(potentialMaster.getSpace()); allAtoms = new IteratorDirective(); // allAtoms is used only for the force calculation, which has no LRC // but we're also calculating the pressure tensor, which does have LRC. // things deal with this OK. allAtoms.setIncludeLrc(true); pressureTensor = potentialMaster.getSpace().makeTensor(); workTensor = potentialMaster.getSpace().makeTensor(); } public static EtomicaInfo getEtomicaInfo() { EtomicaInfo info = new EtomicaInfo("Molecular dynamics using velocity Verlet integration algorithm"); return info; } public void setPhase(Phase p) { if (phase != null) { // allow agentManager to de-register itself as a PhaseListener agentManager.dispose(); } super.setPhase(p); agentManager = new AtomLeafAgentManager(this,p); forceSum.setAgentManager(agentManager); } // steps all particles across time interval tStep // assumes one phase public void doStepInternal() { super.doStepInternal(); AtomSet leafList = phase.getSpeciesMaster().getLeafList(); int nLeaf = leafList.getAtomCount(); for (int iLeaf=0; iLeaf<nLeaf; iLeaf++) { IAtomKinetic a = (IAtomKinetic)leafList.getAtom(iLeaf); MyAgent agent = (MyAgent)agentManager.getAgent(a); IVector r = a.getPosition(); IVector v = a.getVelocity(); v.PEa1Tv1(0.5*timeStep*((AtomTypeLeaf)a.getType()).rm(),agent.force); // p += f(old)*dt/2 r.PEa1Tv1(timeStep,v); // r += p*dt/m } forceSum.reset(); //Compute forces on each atom potential.calculate(phase, allAtoms, forceSum); if(forceSum instanceof PotentialCalculationForcePressureSum){ pressureTensor.E(((PotentialCalculationForcePressureSum)forceSum).getPressureTensor()); } //Finish integration step for (int iLeaf=0; iLeaf<nLeaf; iLeaf++) { IAtomKinetic a = (IAtomKinetic)leafList.getAtom(iLeaf); // System.out.println("force: "+((MyAgent)a.ia).force.toString()); IVector velocity = a.getVelocity(); workTensor.Ev1v2(velocity,velocity); workTensor.TE(((AtomTypeLeaf)a.getType()).getMass()); pressureTensor.PE(workTensor); velocity.PEa1Tv1(0.5*timeStep*((AtomTypeLeaf)a.getType()).rm(),((MyAgent)agentManager.getAgent(a)).force); //p += f(new)*dt/2 } pressureTensor.TE(1/phase.getBoundary().volume()); if(isothermal) { doThermostat(); } return; } /** * Returns the pressure tensor based on the forces calculated during the * last time step. */ public Tensor getPressureTensor() { return pressureTensor; } public void reset() throws ConfigurationOverlapException{ if(!initialized) return; super.reset(); forceSum.reset(); potential.calculate(phase, allAtoms, forceSum); } public Class getAgentClass() { return MyAgent.class; } public final Object makeAgent(IAtom a) { return new MyAgent(potential.getSpace()); } public void releaseAgent(Object agent, IAtom atom) {} public final static class MyAgent implements IntegratorPhase.Forcible, Serializable { //need public so to use with instanceof private static final long serialVersionUID = 1L; public IVector force; public MyAgent(Space space) { force = space.makeVector(); } public IVector force() {return force;} } }
package net.md_5.bungee; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.gson.GsonBuilder; import net.md_5.bungee.api.Favicon; import net.md_5.bungee.api.ServerPing; import net.md_5.bungee.module.ModuleManager; import com.google.common.io.ByteStreams; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.log.BungeeLogger; import net.md_5.bungee.scheduler.BungeeScheduler; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.gson.Gson; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.EventLoopGroup; import io.netty.util.ResourceLeakDetector; import net.md_5.bungee.conf.Configuration; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.InetSocketAddress; import java.text.MessageFormat; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import jline.UnsupportedTerminal; import jline.console.ConsoleReader; import jline.internal.Log; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ReconnectHandler; import net.md_5.bungee.api.config.ConfigurationAdapter; import net.md_5.bungee.api.config.ListenerInfo; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import net.md_5.bungee.api.tab.CustomTabList; import net.md_5.bungee.command.*; import net.md_5.bungee.conf.YamlConfig; import net.md_5.bungee.log.LoggingOutputStream; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.Protocol; import net.md_5.bungee.protocol.ProtocolConstants; import net.md_5.bungee.protocol.packet.Chat; import net.md_5.bungee.protocol.packet.PluginMessage; import net.md_5.bungee.query.RemoteQuery; import net.md_5.bungee.tab.Custom; import net.md_5.bungee.util.CaseInsensitiveMap; import org.fusesource.jansi.AnsiConsole; /** * Main BungeeCord proxy class. */ public class BungeeCord extends ProxyServer { /** * Current operation state. */ public volatile boolean isRunning; /** * Configuration. */ @Getter public final Configuration config = new Configuration(); /** * Localization bundle. */ public ResourceBundle bundle; public EventLoopGroup eventLoops; /** * locations.yml save thread. */ private final Timer saveThread = new Timer( "Reconnect Saver" ); private final Timer metricsThread = new Timer( "Metrics Thread" ); /** * Server socket listener. */ private Collection<Channel> listeners = new HashSet<>(); /** * Fully qualified connections. */ private final Map<String, UserConnection> connections = new CaseInsensitiveMap<>(); private final ReadWriteLock connectionLock = new ReentrantReadWriteLock(); /** * Plugin manager. */ @Getter public final PluginManager pluginManager = new PluginManager( this ); @Getter @Setter private ReconnectHandler reconnectHandler; @Getter @Setter private ConfigurationAdapter configurationAdapter = new YamlConfig(); private final Collection<String> pluginChannels = new HashSet<>(); @Getter private final File pluginsFolder = new File( "plugins" ); @Getter private final BungeeScheduler scheduler = new BungeeScheduler(); @Getter private ConsoleReader consoleReader; @Getter private final Logger logger; public final Gson gson = new GsonBuilder() .registerTypeAdapter( ServerPing.PlayerInfo.class, new PlayerInfoSerializer( ProtocolConstants.MINECRAFT_1_7_6 ) ) .registerTypeAdapter( Favicon.class, Favicon.getFaviconTypeAdapter() ).create(); public final Gson gsonLegacy = new GsonBuilder() .registerTypeAdapter( ServerPing.PlayerInfo.class, new PlayerInfoSerializer( ProtocolConstants.MINECRAFT_1_7_2 ) ) .registerTypeAdapter( Favicon.class, Favicon.getFaviconTypeAdapter() ).create(); @Getter private ConnectionThrottle connectionThrottle; private final ModuleManager moduleManager = new ModuleManager(); { // TODO: Proper fallback when we interface the manager getPluginManager().registerCommand( null, new CommandReload() ); getPluginManager().registerCommand( null, new CommandEnd() ); getPluginManager().registerCommand( null, new CommandIP() ); getPluginManager().registerCommand( null, new CommandBungee() ); getPluginManager().registerCommand( null, new CommandPerms() ); registerChannel( "BungeeCord" ); } public static BungeeCord getInstance() { return (BungeeCord) ProxyServer.getInstance(); } public BungeeCord() throws IOException { try { bundle = ResourceBundle.getBundle( "messages" ); } catch ( MissingResourceException ex ) { bundle = ResourceBundle.getBundle( "messages", Locale.ENGLISH ); } Log.setOutput( new PrintStream( ByteStreams.nullOutputStream() ) ); // TODO: Bug JLine AnsiConsole.systemInstall(); consoleReader = new ConsoleReader(); consoleReader.setExpandEvents( false ); logger = new BungeeLogger( this ); System.setErr( new PrintStream( new LoggingOutputStream( logger, Level.SEVERE ), true ) ); System.setOut( new PrintStream( new LoggingOutputStream( logger, Level.INFO ), true ) ); if ( consoleReader.getTerminal() instanceof UnsupportedTerminal ) { logger.info( "Unable to initialize fancy terminal. To fix this on Windows, install the correct Microsoft Visual C++ 2008 Runtime" ); logger.info( "NOTE: This error is non crucial, and BungeeCord will still function correctly! Do not bug the author about it unless you are still unable to get it working" ); } if ( NativeCipher.load() ) { logger.info( "Using OpenSSL based native cipher." ); } else { logger.info( "Using standard Java JCE cipher. To enable the OpenSSL based native cipher, please make sure you are using 64 bit Ubuntu or Debian with libssl installed." ); } } /** * Start this proxy instance by loading the configuration, plugins and * starting the connect thread. * * @throws Exception */ @Override public void start() throws Exception { System.setProperty( "java.net.preferIPv4Stack", "true" ); // Minecraft does not support IPv6 System.setProperty( "io.netty.selectorAutoRebuildThreshold", "0" ); // Seems to cause Bungee to stop accepting connections ResourceLeakDetector.setEnabled( false ); // Eats performance eventLoops = PipelineUtils.newEventLoopGroup( 0, new ThreadFactoryBuilder().setNameFormat( "Netty IO Thread #%1$d" ).build() ); File moduleDirectory = new File( "modules" ); moduleManager.load( this, moduleDirectory ); pluginManager.detectPlugins( moduleDirectory ); pluginsFolder.mkdir(); pluginManager.detectPlugins( pluginsFolder ); pluginManager.loadPlugins(); config.load(); isRunning = true; pluginManager.enablePlugins(); connectionThrottle = new ConnectionThrottle( config.getThrottle() ); startListeners(); saveThread.scheduleAtFixedRate( new TimerTask() { @Override public void run() { if ( getReconnectHandler() != null ) { getReconnectHandler().save(); } } }, 0, TimeUnit.MINUTES.toMillis( 5 ) ); metricsThread.scheduleAtFixedRate( new Metrics(), 0, TimeUnit.MINUTES.toMillis( Metrics.PING_INTERVAL ) ); } public void startListeners() { for ( final ListenerInfo info : config.getListeners() ) { ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().info( "Listening on " + info.getHost() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new ServerBootstrap() .channel( PipelineUtils.getServerChannel() ) .childAttr( PipelineUtils.LISTENER, info ) .childHandler( PipelineUtils.SERVER_CHILD ) .group( eventLoops ) .localAddress( info.getHost() ) .bind().addListener( listener ); if ( info.isQueryEnabled() ) { ChannelFutureListener bindListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().info( "Started query on " + future.channel().localAddress() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new RemoteQuery( this, info ).start( PipelineUtils.getDatagramChannel(), new InetSocketAddress( info.getHost().getAddress(), info.getQueryPort() ), eventLoops, bindListener ); } } } public void stopListeners() { for ( Channel listener : listeners ) { getLogger().log( Level.INFO, "Closing listener {0}", listener ); try { listener.close().syncUninterruptibly(); } catch ( ChannelException ex ) { getLogger().severe( "Could not close listen thread" ); } } listeners.clear(); } @Override public void stop() { new Thread( "Shutdown Thread" ) { @Override public void run() { BungeeCord.this.isRunning = false; stopListeners(); getLogger().info( "Closing pending connections" ); connectionLock.readLock().lock(); try { getLogger().info( "Disconnecting " + connections.size() + " connections" ); for ( UserConnection user : connections.values() ) { user.disconnect( getTranslation( "restart" ) ); } } finally { connectionLock.readLock().unlock(); } getLogger().info( "Closing IO threads" ); eventLoops.shutdownGracefully(); try { eventLoops.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); } catch ( InterruptedException ex ) { } if ( reconnectHandler != null ) { getLogger().info( "Saving reconnect locations" ); reconnectHandler.save(); reconnectHandler.close(); } saveThread.cancel(); metricsThread.cancel(); // TODO: Fix this shit getLogger().info( "Disabling plugins" ); for ( Plugin plugin : pluginManager.getPlugins() ) { try { plugin.onDisable(); for ( Handler handler : plugin.getLogger().getHandlers() ) { handler.close(); } } catch ( Throwable t ) { getLogger().severe( "Exception disabling plugin " + plugin.getDescription().getName() ); t.printStackTrace(); } getScheduler().cancel( plugin ); } scheduler.shutdown(); getLogger().info( "Thank you and goodbye" ); // Need to close loggers after last message! for ( Handler handler : getLogger().getHandlers() ) { handler.close(); } System.exit( 0 ); } }.start(); } /** * Broadcasts a packet to all clients that is connected to this instance. * * @param packet the packet to send */ public void broadcast(DefinedPacket packet) { connectionLock.readLock().lock(); try { for ( UserConnection con : connections.values() ) { con.unsafe().sendPacket( packet ); } } finally { connectionLock.readLock().unlock(); } } @Override public String getName() { return "BungeeCord"; } @Override public String getVersion() { return ( BungeeCord.class.getPackage().getImplementationVersion() == null ) ? "unknown" : BungeeCord.class.getPackage().getImplementationVersion(); } @Override public String getTranslation(String name, Object... args) { String translation = "<translation '" + name + "' missing>"; try { translation = MessageFormat.format( bundle.getString( name ), args ); } catch ( MissingResourceException ex ) { } return translation; } @Override @SuppressWarnings("unchecked") public Collection<ProxiedPlayer> getPlayers() { connectionLock.readLock().lock(); try { return Collections.unmodifiableCollection( new HashSet( connections.values() ) ); } finally { connectionLock.readLock().unlock(); } } @Override public int getOnlineCount() { return connections.size(); } @Override public ProxiedPlayer getPlayer(String name) { connectionLock.readLock().lock(); try { return connections.get( name ); } finally { connectionLock.readLock().unlock(); } } public ProxiedPlayer getPlayer(UUID uuid) { connectionLock.readLock().lock(); try { for ( ProxiedPlayer proxiedPlayer : connections.values() ) { if ( proxiedPlayer.getUniqueId().equals( uuid ) ) { return proxiedPlayer; } } return null; } finally { connectionLock.readLock().unlock(); } } @Override public Map<String, ServerInfo> getServers() { return config.getServers(); } @Override public ServerInfo getServerInfo(String name) { return getServers().get( name ); } @Override @Synchronized("pluginChannels") public void registerChannel(String channel) { pluginChannels.add( channel ); } @Override @Synchronized("pluginChannels") public void unregisterChannel(String channel) { pluginChannels.remove( channel ); } @Override @Synchronized("pluginChannels") public Collection<String> getChannels() { return Collections.unmodifiableCollection( pluginChannels ); } public PluginMessage registerChannels() { return new PluginMessage( "REGISTER", Util.format( pluginChannels, "\00" ).getBytes() ); } @Override public int getProtocolVersion() { return Protocol.supportedVersions.get( Protocol.supportedVersions.size() - 1 ); } @Override public String getGameVersion() { return "1.7.9"; } @Override public ServerInfo constructServerInfo(String name, InetSocketAddress address, String motd, boolean restricted) { return new BungeeServerInfo( name, address, motd, restricted ); } @Override public CommandSender getConsole() { return ConsoleCommandSender.getInstance(); } @Override public void broadcast(String message) { broadcast( TextComponent.fromLegacyText( message ) ); } @Override public void broadcast(BaseComponent... message) { getConsole().sendMessage( BaseComponent.toLegacyText( message ) ); broadcast( new Chat( ComponentSerializer.toString( message ) ) ); } @Override public void broadcast(BaseComponent message) { getConsole().sendMessage( message.toLegacyText() ); broadcast( new Chat( ComponentSerializer.toString( message ) ) ); } public void addConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.put( con.getName(), con ); } finally { connectionLock.writeLock().unlock(); } } public void removeConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.remove( con.getName() ); } finally { connectionLock.writeLock().unlock(); } } @Override public CustomTabList customTabList(ProxiedPlayer player) { return new Custom( player ); } @Override public Collection<String> getDisabledCommands() { return config.getDisabledCommands(); } @Override public Collection<ProxiedPlayer> matchPlayer(final String partialName) { Preconditions.checkNotNull( partialName, "partialName" ); ProxiedPlayer exactMatch = getPlayer( partialName ); if ( exactMatch != null ) { return Collections.singleton( exactMatch ); } return Sets.newHashSet( Iterables.find( getPlayers(), new Predicate<ProxiedPlayer>() { @Override public boolean apply(ProxiedPlayer input) { return input.getName().toLowerCase().contains( partialName.toLowerCase() ); } } ) ); } }
package net.md_5.bungee; import com.google.common.io.ByteStreams; import net.md_5.bungee.log.BungeeLogger; import net.md_5.bungee.reconnect.YamlReconnectHandler; import net.md_5.bungee.scheduler.BungeeScheduler; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.gson.Gson; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.MultithreadEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.ResourceLeakDetector; import net.md_5.bungee.config.Configuration; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import jline.UnsupportedTerminal; import jline.console.ConsoleReader; import jline.internal.Log; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ReconnectHandler; import net.md_5.bungee.api.config.ConfigurationAdapter; import net.md_5.bungee.api.config.ListenerInfo; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import net.md_5.bungee.api.tab.CustomTabList; import net.md_5.bungee.command.*; import net.md_5.bungee.config.YamlConfig; import net.md_5.bungee.log.LoggingOutputStream; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.packet.DefinedPacket; import net.md_5.bungee.protocol.packet.Packet3Chat; import net.md_5.bungee.protocol.packet.PacketFAPluginMessage; import net.md_5.bungee.protocol.Vanilla; import net.md_5.bungee.tab.Custom; import net.md_5.bungee.util.CaseInsensitiveMap; import org.fusesource.jansi.AnsiConsole; /** * Main BungeeCord proxy class. */ public class BungeeCord extends ProxyServer { /** * Current operation state. */ public volatile boolean isRunning; /** * Configuration. */ public final Configuration config = new Configuration(); /** * Localization bundle. */ public final ResourceBundle bundle = ResourceBundle.getBundle( "messages_en" ); public final MultithreadEventLoopGroup eventLoops = new NioEventLoopGroup( 0, new ThreadFactoryBuilder().setNameFormat( "Netty IO Thread #%1$d" ).build() ); /** * locations.yml save thread. */ private final Timer saveThread = new Timer( "Reconnect Saver" ); private final Timer metricsThread = new Timer( "Metrics Thread" ); /** * Server socket listener. */ private Collection<Channel> listeners = new HashSet<>(); /** * Fully qualified connections. */ private final Map<String, UserConnection> connections = new CaseInsensitiveMap<>(); private final ReadWriteLock connectionLock = new ReentrantReadWriteLock(); /** * Plugin manager. */ @Getter public final PluginManager pluginManager = new PluginManager( this ); @Getter @Setter private ReconnectHandler reconnectHandler; @Getter @Setter private ConfigurationAdapter configurationAdapter = new YamlConfig(); private final Collection<String> pluginChannels = new HashSet<>(); @Getter private final File pluginsFolder = new File( "plugins" ); @Getter private final BungeeScheduler scheduler = new BungeeScheduler(); @Getter private ConsoleReader consoleReader; @Getter private final Logger logger; public final Gson gson = new Gson(); { // TODO: Proper fallback when we interface the manager getPluginManager().registerCommand( null, new CommandReload() ); getPluginManager().registerCommand( null, new CommandEnd() ); getPluginManager().registerCommand( null, new CommandList() ); getPluginManager().registerCommand( null, new CommandServer() ); getPluginManager().registerCommand( null, new CommandIP() ); getPluginManager().registerCommand( null, new CommandAlert() ); getPluginManager().registerCommand( null, new CommandBungee() ); getPluginManager().registerCommand( null, new CommandPerms() ); getPluginManager().registerCommand( null, new CommandSend() ); getPluginManager().registerCommand( null, new CommandFind() ); registerChannel( "BungeeCord" ); } public static BungeeCord getInstance() { return (BungeeCord) ProxyServer.getInstance(); } public BungeeCord() throws IOException { Log.setOutput( new PrintStream( ByteStreams.nullOutputStream() ) ); // TODO: Bug JLine AnsiConsole.systemInstall(); consoleReader = new ConsoleReader(); logger = new BungeeLogger( this ); System.setErr( new PrintStream( new LoggingOutputStream( logger, Level.SEVERE ), true ) ); System.setOut( new PrintStream( new LoggingOutputStream( logger, Level.INFO ), true ) ); if ( consoleReader.getTerminal() instanceof UnsupportedTerminal ) { logger.info( "Unable to initialize fancy terminal. To fix this on Windows, install the correct Microsoft Visual C++ 2008 Runtime" ); logger.info( "NOTE: This error is non crucial, and BungeeCord will still function correctly! Do not bug the author about it unless you are still unable to get it working" ); } } /** * Starts a new instance of BungeeCord. * * @param args command line arguments, currently none are used * @throws Exception when the server cannot be started */ public static void main(String[] args) throws Exception { Calendar deadline = Calendar.getInstance(); deadline.set( 2013, 8, 9 ); // year, month, date if ( Calendar.getInstance().after( deadline ) ) { System.err.println( "*** Warning, this build is outdated ***" ); System.err.println( "*** Please download a new build from http: System.err.println( "*** You will get NO support regarding this build ***" ); System.err.println( "*** Server will start in 30 seconds ***" ); Thread.sleep( TimeUnit.SECONDS.toMillis( 30 ) ); } BungeeCord bungee = new BungeeCord(); ProxyServer.setInstance( bungee ); bungee.getLogger().info( "Enabled BungeeCord version " + bungee.getVersion() ); bungee.start(); while ( bungee.isRunning ) { String line = bungee.getConsoleReader().readLine( ">" ); if ( line != null ) { if ( !bungee.getPluginManager().dispatchCommand( ConsoleCommandSender.getInstance(), line ) ) { bungee.getConsole().sendMessage( ChatColor.RED + "Command not found" ); } } } } private final Map<InetAddress, Long> throttle = new HashMap<>(); public void unThrottle(InetAddress address) { if ( address != null ) { synchronized ( throttle ) { throttle.remove( address ); } } } public boolean throttle(InetAddress address) { long currentTime = System.currentTimeMillis(); synchronized ( throttle ) { Long value = throttle.get( address ); if ( value != null && currentTime - value < config.getThrottle() ) { throttle.put( address, currentTime ); return true; } throttle.put( address, currentTime ); } return false; } /** * Start this proxy instance by loading the configuration, plugins and * starting the connect thread. * * @throws Exception */ @Override public void start() throws Exception { ResourceLeakDetector.setEnabled( false ); // Eats performance pluginsFolder.mkdir(); pluginManager.detectPlugins( pluginsFolder ); config.load(); for ( ListenerInfo info : config.getListeners() ) { if ( !info.isForceDefault() && reconnectHandler == null ) { reconnectHandler = new YamlReconnectHandler(); break; } } isRunning = true; pluginManager.loadAndEnablePlugins(); startListeners(); saveThread.scheduleAtFixedRate( new TimerTask() { @Override public void run() { getReconnectHandler().save(); } }, 0, TimeUnit.MINUTES.toMillis( 5 ) ); metricsThread.scheduleAtFixedRate( new Metrics(), 0, TimeUnit.MINUTES.toMillis( Metrics.PING_INTERVAL ) ); } public void startListeners() { for ( final ListenerInfo info : config.getListeners() ) { ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().info( "Listening on " + info.getHost() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new ServerBootstrap() .channel( NioServerSocketChannel.class ) .childAttr( PipelineUtils.LISTENER, info ) .childHandler( PipelineUtils.SERVER_CHILD ) .group( eventLoops ) .localAddress( info.getHost() ) .bind().addListener( listener ); } } public void stopListeners() { for ( Channel listener : listeners ) { getLogger().log( Level.INFO, "Closing listener {0}", listener ); try { listener.close().syncUninterruptibly(); } catch ( ChannelException ex ) { getLogger().severe( "Could not close listen thread" ); } } listeners.clear(); } @Override public void stop() { new Thread( "Shutdown Thread" ) { @Override public void run() { BungeeCord.this.isRunning = false; stopListeners(); getLogger().info( "Closing pending connections" ); connectionLock.readLock().lock(); try { getLogger().info( "Disconnecting " + connections.size() + " connections" ); for ( UserConnection user : connections.values() ) { user.disconnect( getTranslation( "restart" ) ); } } finally { connectionLock.readLock().unlock(); } getLogger().info( "Closing IO threads" ); eventLoops.shutdownGracefully(); try { eventLoops.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); } catch ( InterruptedException ex ) { } if ( reconnectHandler != null ) { getLogger().info( "Saving reconnect locations" ); reconnectHandler.save(); reconnectHandler.close(); } saveThread.cancel(); metricsThread.cancel(); // TODO: Fix this shit getLogger().info( "Disabling plugins" ); for ( Plugin plugin : pluginManager.getPlugins() ) { plugin.onDisable(); getScheduler().cancel( plugin ); } scheduler.shutdown(); getLogger().info( "Thankyou and goodbye" ); System.exit( 0 ); } }.start(); } /** * Broadcasts a packet to all clients that is connected to this instance. * * @param packet the packet to send */ public void broadcast(DefinedPacket packet) { connectionLock.readLock().lock(); try { for ( UserConnection con : connections.values() ) { con.unsafe().sendPacket( packet ); } } finally { connectionLock.readLock().unlock(); } } @Override public String getName() { return "BungeeCord"; } @Override public String getVersion() { return ( BungeeCord.class.getPackage().getImplementationVersion() == null ) ? "unknown" : BungeeCord.class.getPackage().getImplementationVersion(); } @Override public String getTranslation(String name) { String translation = "<translation '" + name + "' missing>"; try { translation = bundle.getString( name ); } catch ( MissingResourceException ex ) { } return translation; } @Override @SuppressWarnings("unchecked") public Collection<ProxiedPlayer> getPlayers() { connectionLock.readLock().lock(); try { return (Collection) new HashSet<>( connections.values() ); } finally { connectionLock.readLock().unlock(); } } @Override public int getOnlineCount() { return connections.size(); } @Override public ProxiedPlayer getPlayer(String name) { connectionLock.readLock().lock(); try { return connections.get( name ); } finally { connectionLock.readLock().unlock(); } } @Override public Map<String, ServerInfo> getServers() { return config.getServers(); } @Override public ServerInfo getServerInfo(String name) { return getServers().get( name ); } @Override @Synchronized("pluginChannels") public void registerChannel(String channel) { pluginChannels.add( channel ); } @Override @Synchronized("pluginChannels") public void unregisterChannel(String channel) { pluginChannels.remove( channel ); } @Override @Synchronized("pluginChannels") public Collection<String> getChannels() { return Collections.unmodifiableCollection( pluginChannels ); } public PacketFAPluginMessage registerChannels() { return new PacketFAPluginMessage( "REGISTER", Util.format( pluginChannels, "\00" ).getBytes() ); } @Override public byte getProtocolVersion() { return Vanilla.PROTOCOL_VERSION; } @Override public String getGameVersion() { return Vanilla.GAME_VERSION; } @Override public ServerInfo constructServerInfo(String name, InetSocketAddress address, String motd, boolean restricted) { return new BungeeServerInfo( name, address, motd, restricted ); } @Override public CommandSender getConsole() { return ConsoleCommandSender.getInstance(); } @Override public void broadcast(String message) { getConsole().sendMessage( message ); // TODO: Here too String encoded = BungeeCord.getInstance().gson.toJson( message ); broadcast( new Packet3Chat( "{\"text\":" + encoded + "}" ) ); } public void addConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.put( con.getName(), con ); } finally { connectionLock.writeLock().unlock(); } } public void removeConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.remove( con.getName() ); } finally { connectionLock.writeLock().unlock(); } } @Override public CustomTabList customTabList(ProxiedPlayer player) { return new Custom( player ); } public Collection<String> getDisabledCommands() { return config.getDisabledCommands(); } }
package git4idea.commands; import com.intellij.execution.process.AnsiEscapeDecoder; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import git4idea.DialogManager; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.commands.GitCommand.LockingPolicy; import git4idea.config.*; import git4idea.i18n.GitBundle; import git4idea.rebase.GitHandlerRebaseEditorManager; import git4idea.rebase.GitSimpleEditorHandler; import git4idea.rebase.GitUnstructuredEditor; import git4idea.util.GitVcsConsoleWriter; import one.util.streamex.StreamEx; import org.jetbrains.annotations.CalledInBackground; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.regex.Pattern; import static com.intellij.openapi.util.text.StringUtil.splitByLinesKeepSeparators; import static com.intellij.openapi.util.text.StringUtil.trimLeading; import static git4idea.commands.GitCommand.LockingPolicy.READ; /** * Basic functionality for git handler execution. */ public abstract class GitImplBase implements Git { private static final Logger LOG = Logger.getInstance(GitImplBase.class); @NotNull @Override public GitCommandResult runCommand(@NotNull GitLineHandler handler) { return run(handler, getCollectingCollector()); } @Override @NotNull public GitCommandResult runCommand(@NotNull Computable<? extends GitLineHandler> handlerConstructor) { return run(handlerConstructor, GitImplBase::getCollectingCollector); } @NotNull private static OutputCollector getCollectingCollector() { return new OutputCollector() { @Override public void outputLineReceived(@NotNull String line) { addOutputLine(line); } @Override public void errorLineReceived(@NotNull String line) { if (Registry.is("git.allow.stderr.to.stdout.mixing") && !looksLikeError(line)) { addOutputLine(line); } else { addErrorLine(line); } } }; } @Override @NotNull public GitCommandResult runCommandWithoutCollectingOutput(@NotNull GitLineHandler handler) { return run(handler, new OutputCollector() { @Override protected void outputLineReceived(@NotNull String line) {} @Override protected void errorLineReceived(@NotNull String line) { addErrorLine(line); } }); } /** * Run handler with retry on authentication failure */ @NotNull private static GitCommandResult run(@NotNull Computable<? extends GitLineHandler> handlerConstructor, @NotNull Computable<? extends OutputCollector> outputCollectorConstructor) { @NotNull GitCommandResult result; int authAttempt = 0; do { GitLineHandler handler = handlerConstructor.compute(); OutputCollector outputCollector = outputCollectorConstructor.compute(); boolean isCredHelperUsed = GitVcsApplicationSettings.getInstance().isUseCredentialHelper(); result = run(handler, outputCollector); if (isCredHelperUsed != GitVcsApplicationSettings.getInstance().isUseCredentialHelper()) { // do not spend attempt if the credential helper has been enabled continue; } authAttempt++; } while (result.isAuthenticationFailed() && authAttempt < 2); return result; } /** * Run handler with per-project locking, logging and authentication */ @NotNull private static GitCommandResult run(@NotNull GitLineHandler handler, @NotNull OutputCollector outputCollector) { GitVersion version = GitVersion.NULL; if (handler.isPreValidateExecutable()) { GitExecutable executable = handler.getExecutable(); try { version = GitExecutableManager.getInstance().identifyVersion(executable); if (version.getType() == GitVersion.Type.WSL1 && !Registry.is("git.allow.wsl1.executables")) { throw new GitNotInstalledException(GitBundle.message("executable.error.git.not.installed"), null); } } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { return handlePreValidationException(handler.project(), e); } } Project project = handler.project(); if (project != null && project.isDisposed()) { LOG.warn("Project has already been disposed"); throw new ProcessCanceledException(); } if (project != null) { try (GitHandlerAuthenticationManager authenticationManager = GitHandlerAuthenticationManager.prepare(project, handler, version)) { try (GitHandlerRebaseEditorManager ignored = prepareGeneralPurposeEditor(project, handler)) { GitCommandResult result = doRun(handler, version, outputCollector); return GitCommandResult.withAuthentication(result, authenticationManager.isHttpAuthFailed()); } } catch (IOException e) { return GitCommandResult.startError(GitBundle.message("git.executable.unknown.error.message", e.getLocalizedMessage())); } } else { return doRun(handler, version, outputCollector); } } @NotNull private static GitHandlerRebaseEditorManager prepareGeneralPurposeEditor(@NotNull Project project, @NotNull GitLineHandler handler) { return GitHandlerRebaseEditorManager.prepareEditor(handler, new GitSimpleEditorHandler(project)); } /** * Run handler with per-project locking, logging */ @NotNull private static GitCommandResult doRun(@NotNull GitLineHandler handler, @NotNull GitVersion version, @NotNull OutputCollector outputCollector) { getGitTraceEnvironmentVariables(version).forEach(handler::addCustomEnvironmentVariable); boolean canSuppressOptionalLocks = Registry.is("git.use.no.optional.locks") && GitVersionSpecialty.ENV_GIT_OPTIONAL_LOCKS_ALLOWED.existsIn(version); if (canSuppressOptionalLocks) { handler.addCustomEnvironmentVariable("GIT_OPTIONAL_LOCKS", "0"); } GitCommandResultListener resultListener = new GitCommandResultListener(outputCollector); handler.addLineListener(resultListener); try (AccessToken ignored = lock(handler)) { writeOutputToConsole(handler); handler.runInCurrentThread(); } catch (IOException e) { return GitCommandResult.error(GitBundle.message("git.error.cant.process.output", e.getLocalizedMessage())); } return new GitCommandResult(resultListener.myStartFailed, resultListener.myExitCode, outputCollector.myErrorOutput, outputCollector.myOutput); } /** * Only public because of {@link GitExecutableValidator#isExecutableValid()} */ @NotNull public static Map<String, String> getGitTraceEnvironmentVariables(@NotNull GitVersion version) { Map<@NonNls String, @NonNls String> environment = new HashMap<>(5); int logLevel = Registry.intValue("git.execution.trace"); if (logLevel == 0) { environment.put("GIT_TRACE", "0"); if (GitVersionSpecialty.ENV_GIT_TRACE_PACK_ACCESS_ALLOWED.existsIn(version)) environment.put("GIT_TRACE_PACK_ACCESS", ""); environment.put("GIT_TRACE_PACKET", ""); environment.put("GIT_TRACE_PERFORMANCE", "0"); environment.put("GIT_TRACE_SETUP", "0"); } else { String logFile = PathManager.getLogPath() + "/gittrace.log"; if ((logLevel & 1) == 1) environment.put("GIT_TRACE", logFile); if ((logLevel & 2) == 2) environment.put("GIT_TRACE_PACK_ACCESS", logFile); if ((logLevel & 4) == 4) environment.put("GIT_TRACE_PACKET", logFile); if ((logLevel & 8) == 8) environment.put("GIT_TRACE_PERFORMANCE", logFile); if ((logLevel & 16) == 16) environment.put("GIT_TRACE_SETUP", logFile); } return environment; } @CalledInBackground public static boolean loadFileAndShowInSimpleEditor(@NotNull Project project, @Nullable VirtualFile root, @NotNull File file, @NotNull @NlsContexts.DialogTitle String dialogTitle, @NotNull @NlsContexts.Button String okButtonText) throws IOException { String encoding = root == null ? CharsetToolkit.UTF8 : GitConfigUtil.getCommitEncoding(project, root); String initialText = trimLeading(ignoreComments(FileUtil.loadFile(file, encoding))); String newText = showUnstructuredEditorAndWait(project, root, initialText, dialogTitle, okButtonText); if (newText == null) { return false; } else { FileUtil.writeToFile(file, newText.getBytes(encoding)); return true; } } @Nullable private static String showUnstructuredEditorAndWait(@NotNull Project project, @Nullable VirtualFile root, @NotNull @NlsSafe String initialText, @NotNull @NlsContexts.DialogTitle String dialogTitle, @NotNull @NlsContexts.Button String okButtonText) { Ref<String> newText = Ref.create(); ApplicationManager.getApplication().invokeAndWait(() -> { GitUnstructuredEditor editor = new GitUnstructuredEditor(project, root, initialText, dialogTitle, okButtonText); DialogManager.show(editor); if (editor.isOK()) { newText.set(editor.getText()); } }); return newText.get(); } @NotNull private static String ignoreComments(@NotNull String text) { String[] lines = splitByLinesKeepSeparators(text); return StreamEx.of(lines) .filter(line -> !line.startsWith(GitUtil.COMMENT_CHAR)) .joining(); } private static class GitCommandResultListener implements GitLineHandlerListener { private final OutputCollector myOutputCollector; private int myExitCode = 0; private boolean myStartFailed = false; GitCommandResultListener(OutputCollector outputCollector) { myOutputCollector = outputCollector; } @Override public void onLineAvailable(String line, Key outputType) { if (outputType == ProcessOutputTypes.STDOUT) { myOutputCollector.outputLineReceived(line); } else if (outputType == ProcessOutputTypes.STDERR && !looksLikeProgress(line)) { myOutputCollector.errorLineReceived(line); } } @Override public void processTerminated(int code) { myExitCode = code; } @Override public void startFailed(@NotNull Throwable t) { myStartFailed = true; myOutputCollector.errorLineReceived(GitBundle.message("git.executable.unknown.error.message", t.getLocalizedMessage())); } } private static abstract class OutputCollector { final List<String> myOutput = new ArrayList<>(); final List<String> myErrorOutput = new ArrayList<>(); final void addOutputLine(@NotNull String line) { synchronized (myOutput) { myOutput.add(line); } } final void addErrorLine(@NotNull String line) { synchronized (myErrorOutput) { myErrorOutput.add(line); } } abstract void outputLineReceived(@NotNull String line); abstract void errorLineReceived(@NotNull String line); } @NotNull private static GitCommandResult handlePreValidationException(@Nullable Project project, @NotNull Exception e) { // Show notification if it's a project non-modal task and cancel the task ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (project != null && progressIndicator != null && !progressIndicator.getModalityState().dominates(ModalityState.NON_MODAL)) { GitExecutableProblemsNotifier.getInstance(project).notifyExecutionError(e); throw new ProcessCanceledException(e); } else { return GitCommandResult.startError( GitBundle.getString("git.executable.validation.error.start.title") + ": \n" + GitExecutableProblemsNotifier.getPrettyErrorMessage(e) ); } } private static void writeOutputToConsole(@NotNull GitLineHandler handler) { if (handler.isSilent()) return; Project project = handler.project(); if (project != null && !project.isDefault()) { GitVcsConsoleWriter vcsConsoleWriter = GitVcsConsoleWriter.getInstance(project); String workingDir = stringifyWorkingDir(project.getBasePath(), handler.getWorkingDirectory()); vcsConsoleWriter.showCommandLine(String.format("[%s] %s", workingDir, handler.printableCommandLine())); handler.addLineListener(new GitLineHandlerListener() { private final AnsiEscapeDecoder myAnsiEscapeDecoder = new AnsiEscapeDecoder(); @Override public void onLineAvailable(String line, Key outputType) { if (StringUtil.isEmptyOrSpaces(line)) return; if (outputType == ProcessOutputTypes.SYSTEM) return; if (outputType == ProcessOutputTypes.STDOUT && handler.isStdoutSuppressed()) return; if (outputType == ProcessOutputTypes.STDERR && handler.isStderrSuppressed()) return; List<Pair<String, Key>> lineChunks = new ArrayList<>(); myAnsiEscapeDecoder.escapeText(line, outputType, (text, key) -> lineChunks.add(Pair.create(text, key))); vcsConsoleWriter.showMessage(lineChunks); } }); } } @NotNull private static AccessToken lock(@NotNull GitLineHandler handler) { Project project = handler.project(); LockingPolicy lockingPolicy = handler.getCommand().lockingPolicy(); if (project == null || project.isDefault() || lockingPolicy == READ) { return AccessToken.EMPTY_ACCESS_TOKEN; } ReadWriteLock executionLock = GitVcs.getInstance(project).getCommandLock(); executionLock.writeLock().lock(); return new AccessToken() { @Override public void finish() { executionLock.writeLock().unlock(); } }; } public static boolean looksLikeProgress(@NotNull String line) { if (PROGRESS_PATTERN.matcher(line).matches()) return true; return ContainerUtil.exists(SUPPRESSED_PROGRESS_INDICATORS, prefix -> { if (StringUtil.startsWith(line, prefix)) return true; if (StringUtil.startsWith(line, REMOTE_PROGRESS_PREFIX)) { return StringUtil.startsWith(line, REMOTE_PROGRESS_PREFIX.length(), prefix); } return false; }); } /** * Pattern that matches most git progress messages. * <p> * 'remote: Finding sources: 1% (575/57489) ' * 'Receiving objects: 100% (57489/57489), 50.03 MiB | 2.83 MiB/s, done.' */ private static final Pattern PROGRESS_PATTERN = Pattern.compile(".*:\\s*\\d{1,3}% \\(\\d+/\\d+\\).*"); private static final @NonNls String REMOTE_PROGRESS_PREFIX = "remote: "; /** * 'remote: Counting objects: 198285, done' * 'Expanding reachable commits in commit graph: 95907' */ private static final @NonNls String[] SUPPRESSED_PROGRESS_INDICATORS = { "Counting objects: ", "Enumerating objects: ", "Compressing objects: ", "Writing objects: ", "Receiving objects: ", "Resolving deltas: ", "Finding sources: ", "Updating files: ", "Checking out files: ", "Expanding reachable commits in commit graph: ", "Delta compression using up to " }; private static boolean looksLikeError(@NotNull @NonNls String text) { return ContainerUtil.exists(ERROR_INDICATORS, indicator -> StringUtil.startsWithIgnoreCase(text.trim(), indicator)); } // could be upper-cased, so should check case-insensitively public static final @NonNls String[] ERROR_INDICATORS = { "warning:", "error:", "fatal:", "remote: error", "Cannot", "Could not", "Interactive rebase already started", "refusing to pull", "cannot rebase:", "conflict", "unable", "The file will have its original", "runnerw:" }; @NotNull static String stringifyWorkingDir(@Nullable String basePath, @NotNull File workingDir) { if (basePath != null) { String relPath = FileUtil.getRelativePath(basePath, FileUtil.toSystemIndependentName(workingDir.getPath()), '/'); if (".".equals(relPath)) { return workingDir.getName(); } else if (relPath != null) { return FileUtil.toSystemDependentName(relPath); } } return workingDir.getPath(); } }
package tlc2.tool; import tla2sany.modanalyzer.SpecObj; import tla2sany.semantic.APSubstInNode; import tla2sany.semantic.ExprNode; import tla2sany.semantic.ExprOrOpArgNode; import tla2sany.semantic.FormalParamNode; import tla2sany.semantic.LabelNode; import tla2sany.semantic.LetInNode; import tla2sany.semantic.LevelConstants; import tla2sany.semantic.LevelNode; import tla2sany.semantic.ModuleNode; import tla2sany.semantic.OpApplNode; import tla2sany.semantic.OpArgNode; import tla2sany.semantic.OpDeclNode; import tla2sany.semantic.OpDefNode; import tla2sany.semantic.SemanticNode; import tla2sany.semantic.Subst; import tla2sany.semantic.SubstInNode; import tla2sany.semantic.SymbolNode; import tla2sany.semantic.ThmOrAssumpDefNode; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.util.Context; import tlc2.util.IdThread; import tlc2.util.Vect; import tlc2.value.Applicable; import tlc2.value.BoolValue; import tlc2.value.Enumerable; import tlc2.value.FcnLambdaValue; import tlc2.value.FcnParams; import tlc2.value.FcnRcdValue; import tlc2.value.LazyValue; import tlc2.value.MVPerm; import tlc2.value.MethodValue; import tlc2.value.OpLambdaValue; import tlc2.value.OpValue; import tlc2.value.RecordValue; import tlc2.value.Reducible; import tlc2.value.SetCapValue; import tlc2.value.SetCupValue; import tlc2.value.SetDiffValue; import tlc2.value.SetEnumValue; import tlc2.value.SetOfFcnsValue; import tlc2.value.SetOfRcdsValue; import tlc2.value.SetOfTuplesValue; import tlc2.value.SetPredValue; import tlc2.value.StringValue; import tlc2.value.SubsetValue; import tlc2.value.TupleValue; import tlc2.value.UnionValue; import tlc2.value.Value; import tlc2.value.ValueConstants; import tlc2.value.ValueEnumeration; import tlc2.value.ValueExcept; import tlc2.value.ValueVec; import util.Assert; import util.Assert.TLCRuntimeException; import util.FilenameToStream; import util.UniqueString; /** * This class provides useful methods for tools like model checker * and simulator. * * It's instance serves as a spec handle * This is one of two places in TLC, where not all messages are retrieved from the message printer, * but constructed just here in the code. */ public class Tool extends Spec implements ValueConstants, ToolGlobals, TraceApp { protected Action[] actions; // the list of TLA actions. private CallStack callStack; // the call stack. private Vect actionVec = new Vect(10); /** * Creates a new tool handle * @param specDir * @param specFile * @param configFile */ public Tool(String specDir, String specFile, String configFile, FilenameToStream resolver) { super(specDir, specFile, configFile, resolver); this.actions = null; this.callStack = null; } /** * Initialization. Any Tool object must call it before doing anything. * @param spec - <code>null</code> or a filled spec object from previous SANY run */ public final SpecObj init(boolean preprocess, SpecObj spec) { // Parse and process this spec. // It takes care of all overrides. // SZ Feb 20, 2009: added spec reference, // if not null it is just used instead of re-parsing SpecObj processSpec = super.processSpec(spec); // Initialize state. if (TLCGlobals.isCoverageEnabled()) { TLCStateMutSource.init(this); } else { TLCStateMut.init(this); } // Pre-evaluate all the definitions in the spec that are constants. if (preprocess) { this.processConstantDefns(); } // Finally, process the config file. super.processConfig(); return processSpec; } public final void setCallStack() { this.callStack = new CallStack(); } public final CallStack getCallStack() { return this.callStack; } /** * This method returns the set of all possible actions of the * spec, and sets the actions field of this object. In fact, we * could simply treat the next predicate as one "giant" action. * But for efficiency, we preprocess the next state predicate by * splitting it into a set of actions for the maximum prefix * of disjunction and existential quantification. */ public final Action[] getActions() { if (this.actions == null) { Action next = this.getNextStateSpec(); if (next == null) { this.actions = new Action[0]; } else { this.getActions(next.pred, next.con); int sz = this.actionVec.size(); this.actions = new Action[sz]; for (int i = 0; i < sz; i++) { this.actions[i] = (Action)this.actionVec.elementAt(i); } } } return this.actions; } private final void getActions(SemanticNode next, Context con) { this.getActions(next, con, Action.UNNAMED_ACTION); } private final void getActions(SemanticNode next, Context con, final UniqueString actionName) { switch (next.getKind()) { case OpApplKind: { OpApplNode next1 = (OpApplNode)next; this.getActionsAppl(next1, con, actionName); return; } case LetInKind: { LetInNode next1 = (LetInNode)next; this.getActions(next1.getBody(), con, actionName); return; } case SubstInKind: { SubstInNode next1 = (SubstInNode)next; Subst[] substs = next1.getSubsts(); if (substs.length == 0) { this.getActions(next1.getBody(), con, actionName); } else { Action action = new Action(next1, con, actionName); this.actionVec.addElement(action); } return; } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode next1 = (APSubstInNode)next; Subst[] substs = next1.getSubsts(); if (substs.length == 0) { this.getActions(next1.getBody(), con, actionName); } else { Action action = new Action(next1, con, actionName); this.actionVec.addElement(action); } return; } case LabelKind: { LabelNode next1 = (LabelNode)next; this.getActions(next1.getBody(), con, actionName); return; } default: { Assert.fail("The next state relation is not a boolean expression.\n" + next); } } } private final void getActionsAppl(OpApplNode next, Context con, final UniqueString actionName) { ExprOrOpArgNode[] args = next.getArgs(); SymbolNode opNode = next.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { Object val = this.lookup(opNode, con, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { try { FormalParamNode[] formals = opDef.getParams(); int alen = args.length; int argLevel = 0; for (int i = 0; i < alen; i++) { argLevel = args[i].getLevel(); if (argLevel != 0) break; } if (argLevel == 0) { Context con1 = con; for (int i = 0; i < alen; i++) { Value aval = this.eval(args[i], con, TLCState.Empty); con1 = con1.cons(formals[i], aval); } this.getActions(opDef.getBody(), con1, opDef.getName()); return; } } catch (Throwable e) { /*SKIP*/ } } } if (opcode == 0) { Action action = new Action(next, con, opNode.getName()); this.actionVec.addElement(action); return; } } switch (opcode) { case OPCODE_be: // BoundedExists { int cnt = this.actionVec.size(); try { ContextEnumerator Enum = this.contexts(next, con, TLCState.Empty, TLCState.Empty, EvalControl.Clear); Context econ; while ((econ = Enum.nextElement()) != null) { this.getActions(args[0], econ, actionName); } } catch (Throwable e) { Action action = new Action(next, con, actionName); this.actionVec.removeAll(cnt); this.actionVec.addElement(action); } return; } case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < args.length; i++) { this.getActions(args[i], con, actionName); } return; } default: { // We handle all the other builtin operators here. Action action = new Action(next, con, actionName); this.actionVec.addElement(action); return; } } } /* * This method returns the set of possible initial states that * satisfies the initial state predicate. Initial state predicate * can be under-specified. Too many possible initial states will * probably make tools like TLC useless. */ public final StateVec getInitStates() { final StateVec initStates = new StateVec(0); getInitStates(initStates); return initStates; } public final void getInitStates(IStateFunctor functor) { Vect init = this.getInitStateSpec(); ActionItemList acts = ActionItemList.Empty; // MAK 09/11/2018: Tail to head iteration order cause the first elem added with // acts.cons to be acts tail. This fixes the bug/funny behavior that the init // predicate Init == A /\ B /\ C /\ D was evaluated in the order A, D, C, B (A // doesn't get added to acts at all). for (int i = (init.size() - 1); i > 0; i Action elem = (Action)init.elementAt(i); acts = acts.cons(elem.pred, elem.con, ActionItemList.PRED); } if (init.size() != 0) { Action elem = (Action)init.elementAt(0); TLCState ps = TLCState.Empty.createEmpty(); this.getInitStates(elem.pred, acts, elem.con, ps, functor); } } /* Create the state specified by pred. */ public final TLCState makeState(SemanticNode pred) { ActionItemList acts = ActionItemList.Empty; TLCState ps = TLCState.Empty.createEmpty(); StateVec states = new StateVec(0); this.getInitStates(pred, acts, Context.Empty, ps, states); if (states.size() != 1) { Assert.fail("The predicate does not specify a unique state." + pred); } TLCState state = states.elementAt(0); if (!this.isGoodState(state)) { Assert.fail("The state specified by the predicate is not complete." + pred); } return state; } private final void getInitStates(SemanticNode init, ActionItemList acts, Context c, TLCState ps, IStateFunctor states) { if (this.callStack != null) this.callStack.push(init); try { switch (init.getKind()) { case OpApplKind: { OpApplNode init1 = (OpApplNode)init; this.getInitStatesAppl(init1, acts, c, ps, states); return; } case LetInKind: { LetInNode init1 = (LetInNode)init; this.getInitStates(init1.getBody(), acts, c, ps, states); return; } case SubstInKind: { SubstInNode init1 = (SubstInNode)init; Subst[] subs = init1.getSubsts(); Context c1 = c; for (int i = 0; i < subs.length; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false)); } this.getInitStates(init1.getBody(), acts, c1, ps, states); return; } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode init1 = (APSubstInNode)init; Subst[] subs = init1.getSubsts(); Context c1 = c; for (int i = 0; i < subs.length; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false)); } this.getInitStates(init1.getBody(), acts, c1, ps, states); return; } // LabelKind class added by LL on 13 Jun 2007 case LabelKind: { LabelNode init1 = (LabelNode)init; this.getInitStates(init1.getBody(), acts, c, ps, states); return; } default: { Assert.fail("The init state relation is not a boolean expression.\n" + init); } } } catch (TLCRuntimeException | EvalException e) { if (this.callStack != null) { // Freeze the callStack to ignore subsequent pop operations. This is // necessary to ignore the callStack#pop calls in the finally blocks when the // Java call stack gets unwounded. this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } private final void getInitStates(ActionItemList acts, TLCState ps, IStateFunctor states) { if (acts.isEmpty()) { states.addElement(ps.copy()); return; } else if (ps.allAssigned()) { // MAK 05/25/2018: If all values of the initial state have already been // assigned, there is no point in further trying to assign values. Instead, all // remaining statements (ActionItemList) can just be evaluated for their boolean // value. // This optimization is especially useful to check inductive invariants which // require TLC to generate a very large set of initial states. while (!acts.isEmpty()) { final Value bval = this.eval(acts.carPred(), acts.carContext(), ps, TLCState.Empty, EvalControl.Init); if (!(bval instanceof BoolValue)) { //TODO Choose more fitting error message. Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "initial states", "boolean", bval.toString(), acts.pred.toString() }); } if (!((BoolValue) bval).val) { return; } // Move on to the next action in the ActionItemList. acts = acts.cdr(); } states.addElement(ps.copy()); return; } // Assert.check(act.kind > 0 || act.kind == -1); ActionItemList acts1 = acts.cdr(); this.getInitStates(acts.carPred(), acts1, acts.carContext(), ps, states); } private final void getInitStatesAppl(OpApplNode init, ActionItemList acts, Context c, TLCState ps, IStateFunctor states) { if (this.callStack != null) this.callStack.push(init); try { ExprOrOpArgNode[] args = init.getArgs(); int alen = args.length; SymbolNode opNode = init.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, ps, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { // Context c1 = this.getOpContext(opDef, args, c, false); Context c1 = this.getOpContext(opDef, args, c, true); this.getInitStates(opDef.getBody(), acts, c1, ps, states); return; } } // Added 13 Nov 2009 by LL to fix Yuan's fix. if (val instanceof ThmOrAssumpDefNode) { ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); Context c1 = this.getOpContext(opDef, args, c, true); this.getInitStates(opDef.getBody(), acts, c1, ps, states); return; } if (val instanceof LazyValue) { LazyValue lv = (LazyValue)val; if (lv.getValue() == null || lv.isUncachable()) { this.getInitStates(lv.expr, acts, lv.con, ps, states); return; } val = lv.getValue(); } Object bval = val; if (alen == 0) { if (val instanceof MethodValue) { bval = ((MethodValue)val).apply(EmptyArgs, EvalControl.Init); } } else { if (val instanceof OpValue) { Applicable opVal = (Applicable)val; Value[] argVals = new Value[alen]; // evaluate the actuals: for (int i = 0; i < alen; i++) { argVals[i] = this.eval(args[i], c, ps, TLCState.Empty, EvalControl.Init); } // apply the operator: bval = opVal.apply(argVals, EvalControl.Init); } } if (opcode == 0) { if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "initial states", "boolean", bval.toString(), init.toString() }); } if (((BoolValue) bval).val) { this.getInitStates(acts, ps, states); } return; } } switch (opcode) { case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < alen; i++) { this.getInitStates(args[i], acts, c, ps, states); } return; } case OPCODE_cl: // ConjList case OPCODE_land: { for (int i = alen-1; i > 0; i acts = acts.cons(args[i], c, i); } this.getInitStates(args[0], acts, c, ps, states); return; } case OPCODE_be: // BoundedExists { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(init, c, ps, TLCState.Empty, EvalControl.Init); Context c1; while ((c1 = Enum.nextElement()) != null) { this.getInitStates(body, acts, c1, ps, states); } return; } case OPCODE_bf: // BoundedForall { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(init, c, ps, TLCState.Empty, EvalControl.Init); Context c1 = Enum.nextElement(); if (c1 == null) { this.getInitStates(acts, ps, states); } else { ActionItemList acts1 = acts; Context c2; while ((c2 = Enum.nextElement()) != null) { acts1 = acts1.cons(body, c2, ActionItemList.PRED); } this.getInitStates(body, acts1, c1, ps, states); } return; } case OPCODE_ite: // IfThenElse { Value guard = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init); if (!(guard instanceof BoolValue)) { Assert.fail("In computing initial states, a non-boolean expression (" + guard.getKindString() + ") was used as the condition " + "of an IF.\n" + init); } int idx = (((BoolValue)guard).val) ? 1 : 2; this.getInitStates(args[idx], acts, c, ps, states); return; } case OPCODE_case: // Case { SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pair = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pair.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, ps, TLCState.Empty, EvalControl.Init); if (!(bval instanceof BoolValue)) { Assert.fail("In computing initial states, a non-boolean expression (" + bval.getKindString() + ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1]); } if (((BoolValue)bval).val) { this.getInitStates(pairArgs[1], acts, c, ps, states); return; } } } if (other == null) { Assert.fail("In computing initial states, TLC encountered a CASE with no" + " conditions true.\n" + init); } this.getInitStates(other, acts, c, ps, states); return; } case OPCODE_fa: // FcnApply { Value fval = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init); if (fval instanceof FcnLambdaValue) { FcnLambdaValue fcn = (FcnLambdaValue)fval; if (fcn.fcnRcd == null) { Context c1 = this.getFcnContext(fcn, args, c, ps, TLCState.Empty, EvalControl.Init); this.getInitStates(fcn.body, acts, c1, ps, states); return; } fval = fcn.fcnRcd; } else if (!(fval instanceof Applicable)) { Assert.fail("In computing initial states, a non-function (" + fval.getKindString() + ") was applied as a function.\n" + init); } Applicable fcn = (Applicable) fval; Value argVal = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init); Value bval = fcn.apply(argVal, EvalControl.Init); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "initial states", "boolean", init.toString() }); } if (((BoolValue)bval).val) { this.getInitStates(acts, ps, states); } return; } case OPCODE_eq: { SymbolNode var = this.getVar(args[0], c, false); if (var == null || var.getName().getVarLoc() < 0) { Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init); if (!((BoolValue)bval).val) { return; } } else { UniqueString varName = var.getName(); Value lval = ps.lookup(varName); Value rval = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init); if (lval == null) { ps = ps.bind(varName, rval, init); this.getInitStates(acts, ps, states); ps.unbind(varName); return; } else { if (!lval.equals(rval)) { return; } } } this.getInitStates(acts, ps, states); return; } case OPCODE_in: { SymbolNode var = this.getVar(args[0], c, false); if (var == null || var.getName().getVarLoc() < 0) { Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init); if (!((BoolValue)bval).val) { return; } } else { UniqueString varName = var.getName(); Value lval = ps.lookup(varName); Value rval = this.eval(args[1], c, ps, TLCState.Empty, EvalControl.Init); if (lval == null) { if (!(rval instanceof Enumerable)) { Assert.fail("In computing initial states, the right side of \\IN" + " is not enumerable.\n" + init); } ValueEnumeration Enum = ((Enumerable)rval).elements(); Value elem; while ((elem = Enum.nextElement()) != null) { ps.bind(varName, elem, init); this.getInitStates(acts, ps, states); ps.unbind(varName); } return; } else { if (!rval.member(lval)) { return; } } } this.getInitStates(acts, ps, states); return; } case OPCODE_implies: { Value lval = this.eval(args[0], c, ps, TLCState.Empty, EvalControl.Init); if (!(lval instanceof BoolValue)) { Assert.fail("In computing initial states of a predicate of form" + " P => Q, P was " + lval.getKindString() + "\n." + init); } if (((BoolValue)lval).val) { this.getInitStates(args[1], acts, c, ps, states); } else { this.getInitStates(acts, ps, states); } return; } // The following case added by LL on 13 Nov 2009 to handle subexpression names. case OPCODE_nop: { this.getInitStates(args[0], acts, c, ps, states); return; } default: { // For all the other builtin operators, simply evaluate: Value bval = this.eval(init, c, ps, TLCState.Empty, EvalControl.Init); if (!(bval instanceof BoolValue)) { Assert.fail("In computing initial states, TLC expected a boolean expression," + "\nbut instead found " + bval + ".\n" + init); } if (((BoolValue)bval).val) { this.getInitStates(acts, ps, states); } return; } } } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } /** * This method returns the set of next states when taking the action * in the given state. */ public final StateVec getNextStates(Action action, TLCState state) { ActionItemList acts = ActionItemList.Empty; TLCState s1 = TLCState.Empty.createEmpty(); StateVec nss = new StateVec(0); this.getNextStates(action.pred, acts, action.con, state, s1, nss); return nss; } private final TLCState getNextStates(SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { if (this.callStack != null) { return getNextStatesWithCallStack(pred, acts, c, s0, s1, nss); } else { return getNextStatesImpl(pred, acts, c, s0, s1, nss); } } private final TLCState getNextStatesWithCallStack(SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { this.callStack.push(pred); try { return getNextStatesImpl(pred, acts, c, s0, s1, nss); } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) this.callStack.freeze(); throw e; } finally { this.callStack.pop(); } } private final TLCState getNextStatesImpl(SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { switch (pred.getKind()) { case OpApplKind: { OpApplNode pred1 = (OpApplNode)pred; return this.getNextStatesAppl(pred1, acts, c, s0, s1, nss); } case LetInKind: { LetInNode pred1 = (LetInNode)pred; return this.getNextStates(pred1.getBody(), acts, c, s0, s1, nss); } case SubstInKind: { return getNextStatesImplSubstInKind((SubstInNode) pred, acts, c, s0, s1, nss); } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { return getNextStatesImplApSubstInKind((APSubstInNode) pred, acts, c, s0, s1, nss); } // LabelKind class added by LL on 13 Jun 2007 case LabelKind: { LabelNode pred1 = (LabelNode)pred; return this.getNextStates(pred1.getBody(), acts, c, s0, s1, nss); } default: { Assert.fail("The next state relation is not a boolean expression.\n" + pred); } } return s1; } private final TLCState getNextStatesImplSubstInKind(SubstInNode pred1, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false)); } return this.getNextStates(pred1.getBody(), acts, c1, s0, s1, nss); } private final TLCState getNextStatesImplApSubstInKind(APSubstInNode pred1, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false)); } return this.getNextStates(pred1.getBody(), acts, c1, s0, s1, nss); } private final TLCState getNextStates(ActionItemList acts, final TLCState s0, final TLCState s1, final StateVec nss) { int kind = acts.carKind(); if (acts.isEmpty()) { nss.addElement(s1); return s1.copy(); } else if (s1.allAssigned()) { SemanticNode pred = acts.carPred(); Context c = acts.carContext(); while (!acts.isEmpty()) { if (kind > 0 || kind == -1) { final Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear); if (!(bval instanceof BoolValue)) { // TODO Choose more fitting error message. Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean", bval.toString(), acts.pred.toString() }); } if (!((BoolValue) bval).val) { return s1; } } else if (kind == -2) { // Identical to default handling below (line 876). Ignored during this optimization. return this.processUnchanged(pred, acts.cdr(), c, s0, s1, nss); } else { final Value v1 = this.eval(pred, c, s0); final Value v2 = this.eval(pred, c, s1); if (v1.equals(v2)) { return s1; } } // Move on to the next action in the ActionItemList. acts = acts.cdr(); pred = acts.carPred(); c = acts.carContext(); kind = acts.carKind(); } nss.addElement(s1); return s1.copy(); } SemanticNode pred = acts.carPred(); Context c = acts.carContext(); ActionItemList acts1 = acts.cdr(); if (kind > 0) { return this.getNextStates(pred, acts1, c, s0, s1, nss); } else if (kind == -1) { return this.getNextStates(pred, acts1, c, s0, s1, nss); } else if (kind == -2) { return this.processUnchanged(pred, acts1, c, s0, s1, nss); } else { Value v1 = this.eval(pred, c, s0); Value v2 = this.eval(pred, c, s1); if (!v1.equals(v2)) { return this.getNextStates(acts1, s0, s1, nss); } } return s1; } private final TLCState getNextStatesAppl(OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { if (this.callStack != null) this.callStack.push(pred); try { ExprOrOpArgNode[] args = pred.getArgs(); int alen = args.length; SymbolNode opNode = pred.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, s0, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { // Context c1 = this.getOpContext(opDef, args, c, false); Context c1 = this.getOpContext(opDef, args, c, true); return this.getNextStates(opDef.getBody(), acts, c1, s0, s1, nss); } } // Added by LL 13 Nov 2009 to fix Yuan's fix if (val instanceof ThmOrAssumpDefNode) { ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode)val; Context c1 = this.getOpContext(opDef, args, c, true); return this.getNextStates(opDef.getBody(), acts, c1, s0, s1, nss); } if (val instanceof LazyValue) { LazyValue lv = (LazyValue)val; if (lv.getValue() == null || lv.isUncachable()) { return this.getNextStates(lv.expr, acts, lv.con, s0, s1, nss); } val = lv.getValue(); } Object bval = val; if (alen == 0) { if (val instanceof MethodValue) { bval = ((MethodValue)val).apply(EmptyArgs, EvalControl.Clear); } } else { if (val instanceof OpValue) { Applicable opVal = (Applicable)val; Value[] argVals = new Value[alen]; // evaluate the actuals: for (int i = 0; i < alen; i++) { argVals[i] = this.eval(args[i], c, s0, s1, EvalControl.Clear); } // apply the operator: bval = opVal.apply(argVals, EvalControl.Clear); } } if (opcode == 0) { if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean", bval.toString(), pred.toString() }); } if (((BoolValue) bval).val) { return this.getNextStates(acts, s0, s1, nss); } return s1; } } TLCState resState = s1; switch (opcode) { case OPCODE_cl: // ConjList case OPCODE_land: { ActionItemList acts1 = acts; for (int i = alen - 1; i > 0; i acts1 = acts1.cons(args[i], c, i); } return this.getNextStates(args[0], acts1, c, s0, s1, nss); } case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < alen; i++) { resState = this.getNextStates(args[i], acts, c, s0, resState, nss); } return resState; } case OPCODE_be: // BoundedExists { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Clear); Context c1; while ((c1 = Enum.nextElement()) != null) { resState = this.getNextStates(body, acts, c1, s0, resState, nss); } return resState; } case OPCODE_bf: // BoundedForall { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Clear); Context c1 = Enum.nextElement(); if (c1 == null) { resState = this.getNextStates(acts, s0, s1, nss); } else { ActionItemList acts1 = acts; Context c2; while ((c2 = Enum.nextElement()) != null) { acts1 = acts1.cons(body, c2, ActionItemList.PRED); } resState = this.getNextStates(body, acts1, c1, s0, s1, nss); } return resState; } case OPCODE_fa: // FcnApply { Value fval = this.eval(args[0], c, s0, s1, EvalControl.KeepLazy); if (fval instanceof FcnLambdaValue) { FcnLambdaValue fcn = (FcnLambdaValue)fval; if (fcn.fcnRcd == null) { Context c1 = this.getFcnContext(fcn, args, c, s0, s1, EvalControl.Clear); return this.getNextStates(fcn.body, acts, c1, s0, s1, nss); } fval = fcn.fcnRcd; } if (!(fval instanceof Applicable)) { Assert.fail("In computing next states, a non-function (" + fval.getKindString() + ") was applied as a function.\n" + pred); } Applicable fcn = (Applicable)fval; Value argVal = this.eval(args[1], c, s0, s1, EvalControl.Clear); Value bval = fcn.apply(argVal, EvalControl.Clear); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "next states", "boolean", pred.toString() }); } if (((BoolValue)bval).val) { return this.getNextStates(acts, s0, s1, nss); } return resState; } case OPCODE_aa: // AngleAct <A>_e { ActionItemList acts1 = acts.cons(args[1], c, ActionItemList.CHANGED); return this.getNextStates(args[0], acts1, c, s0, s1, nss); } case OPCODE_sa: { /* The following two lines of code did not work, and were changed by * YuanYu to mimic the way \/ works. Change made * 11 Mar 2009, with LL sitting next to him. */ // this.getNextStates(args[0], acts, c, s0, s1, nss); // return this.processUnchanged(args[1], acts, c, s0, s1, nss); resState = this.getNextStates(args[0], acts, c, s0, resState, nss); return this.processUnchanged(args[1], acts, c, s0, resState, nss); } case OPCODE_ite: // IfThenElse { Value guard = this.eval(args[0], c, s0, s1, EvalControl.Clear); if (!(guard instanceof BoolValue)) { Assert.fail("In computing next states, a non-boolean expression (" + guard.getKindString() + ") was used as the condition of" + " an IF." + pred); } if (((BoolValue)guard).val) { return this.getNextStates(args[1], acts, c, s0, s1, nss); } else { return this.getNextStates(args[2], acts, c, s0, s1, nss); } } case OPCODE_case: // Case { SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pair = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pair.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, s0, s1, EvalControl.Clear); if (!(bval instanceof BoolValue)) { Assert.fail("In computing next states, a non-boolean expression (" + bval.getKindString() + ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1]); } if (((BoolValue)bval).val) { return this.getNextStates(pairArgs[1], acts, c, s0, s1, nss); } } } if (other == null) { Assert.fail("In computing next states, TLC encountered a CASE with no" + " conditions true.\n" + pred); } return this.getNextStates(other, acts, c, s0, s1, nss); } case OPCODE_eq: { SymbolNode var = this.getPrimedVar(args[0], c, false); // Assert.check(var.getName().getVarLoc() >= 0); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear); if (!((BoolValue)bval).val) { return resState; } } else { UniqueString varName = var.getName(); Value lval = s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Clear); if (lval == null) { resState.bind(varName, rval, pred); resState = this.getNextStates(acts, s0, resState, nss); resState.unbind(varName); return resState; } else if (!lval.equals(rval)) { return resState; } } return this.getNextStates(acts, s0, s1, nss); } case OPCODE_in: { SymbolNode var = this.getPrimedVar(args[0], c, false); // Assert.check(var.getName().getVarLoc() >= 0); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear); if (!((BoolValue)bval).val) { return resState; } } else { UniqueString varName = var.getName(); Value lval = s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Clear); if (lval == null) { if (!(rval instanceof Enumerable)) { Assert.fail("In computing next states, the right side of \\IN" + " is not enumerable.\n" + pred); } ValueEnumeration Enum = ((Enumerable)rval).elements(); Value elem; while ((elem = Enum.nextElement()) != null) { resState.bind(varName, elem, pred); resState = this.getNextStates(acts, s0, resState, nss); resState.unbind(varName); } return resState; } else if (!rval.member(lval)) { return resState; } } return this.getNextStates(acts, s0, s1, nss); } case OPCODE_implies: { Value bval = this.eval(args[0], c, s0, s1, EvalControl.Clear); if (!(bval instanceof BoolValue)) { Assert.fail("In computing next states of a predicate of the form" + " P => Q, P was\n" + bval.getKindString() + ".\n" + pred); } if (((BoolValue)bval).val) { return this.getNextStates(args[1], acts, c, s0, s1, nss); } else { return this.getNextStates(acts, s0, s1, nss); } } case OPCODE_unchanged: { return this.processUnchanged(args[0], acts, c, s0, s1, nss); } case OPCODE_cdot: { Assert.fail("The current version of TLC does not support action composition."); return s1; } // The following case added by LL on 13 Nov 2009 to handle subexpression names. case OPCODE_nop: { return this.getNextStates(args[0], acts, c, s0, s1, nss); } default: { // We handle all the other builtin operators here. Value bval = this.eval(pred, c, s0, s1, EvalControl.Clear); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "next states", "boolean", bval.toString(), pred.toString() }); } if (((BoolValue)bval).val) { resState = this.getNextStates(acts, s0, s1, nss); } return resState; } } } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } private final TLCState processUnchanged(SemanticNode expr, ActionItemList acts, Context c, TLCState s0, TLCState s1, StateVec nss) { if (this.callStack != null) this.callStack.push(expr); try { SymbolNode var = this.getVar(expr, c, false); TLCState resState = s1; if (var != null) { // expr is a state variable: UniqueString varName = var.getName(); Value val0 = s0.lookup(varName); Value val1 = s1.lookup(varName); if (val1 == null) { resState.bind(varName, val0, expr); resState = this.getNextStates(acts, s0, resState, nss); resState.unbind(varName); } else if (val0.equals(val1)) { resState = this.getNextStates(acts, s0, s1, nss); } else { MP.printWarning(EC.TLC_UNCHANGED_VARIABLE_CHANGED, new String[]{varName.toString(), expr.toString()}); } return resState; } if (expr instanceof OpApplNode) { OpApplNode expr1 = (OpApplNode)expr; ExprOrOpArgNode[] args = expr1.getArgs(); int alen = args.length; SymbolNode opNode = expr1.getOperator(); UniqueString opName = opNode.getName(); int opcode = BuiltInOPs.getOpCode(opName); if (opcode == OPCODE_tup) { // a tuple: if (alen != 0) { ActionItemList acts1 = acts; for (int i = alen-1; i > 0; i acts1 = acts1.cons(args[i], c, ActionItemList.UNCHANGED); } return this.processUnchanged(args[0], acts1, c, s0, s1, nss); } return this.getNextStates(acts, s0, s1, nss); } if (opcode == 0 && alen == 0) { // a 0-arity operator: Object val = this.lookup(opNode, c, false); if (val instanceof OpDefNode) { return this.processUnchanged(((OpDefNode)val).getBody(), acts, c, s0, s1, nss); } else if (val instanceof LazyValue) { LazyValue lv = (LazyValue)val; return this.processUnchanged(lv.expr, acts, lv.con, s0, s1, nss); } else { Assert.fail("In computing next states, TLC found the identifier\n" + opName + " undefined in an UNCHANGED expression at\n" + expr); } return this.getNextStates(acts, s0, s1, nss); } } Value v0 = this.eval(expr, c, s0); Value v1 = this.eval(expr, c, s1, null, EvalControl.Clear); if (v0.equals(v1)) { resState = this.getNextStates(acts, s0, s1, nss); } return resState; } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } /* Special version of eval for state expressions. */ public final Value eval(SemanticNode expr, Context c, TLCState s0) { return this.eval(expr, c, s0, TLCState.Empty, EvalControl.Clear); } /* * This method evaluates the expression expr in the given context, * current state, and partial next state. */ public final Value eval(SemanticNode expr, Context c, TLCState s0, TLCState s1, final int control) { if (this.callStack != null) this.callStack.push(expr); try { switch (expr.getKind()) { case LabelKind: { LabelNode expr1 = (LabelNode) expr; return this.eval(expr1.getBody(), c, s0, s1, control); } case OpApplKind: { OpApplNode expr1 = (OpApplNode)expr; return this.evalAppl(expr1, c, s0, s1, control); } case LetInKind: { LetInNode expr1 = (LetInNode)expr; OpDefNode[] letDefs = expr1.getLets(); int letLen = letDefs.length; Context c1 = c; for (int i = 0; i < letLen; i++) { OpDefNode opDef = letDefs[i]; if (opDef.getArity() == 0) { Value rhs = new LazyValue(opDef.getBody(), c1); c1 = c1.cons(opDef, rhs); } } return this.eval(expr1.getBody(), c1, s0, s1, control); } case SubstInKind: { SubstInNode expr1 = (SubstInNode)expr; Subst[] subs = expr1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, true)); } return this.eval(expr1.getBody(), c1, s0, s1, control); } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode expr1 = (APSubstInNode)expr; Subst[] subs = expr1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, true)); } return this.eval(expr1.getBody(), c1, s0, s1, control); } case NumeralKind: case DecimalKind: case StringKind: { return Value.getValue(expr); } case AtNodeKind: { return (Value)c.lookup(EXCEPT_AT); } case OpArgKind: { OpArgNode expr1 = (OpArgNode)expr; SymbolNode opNode = expr1.getOp(); Object val = this.lookup(opNode, c, false); if (val instanceof OpDefNode) { return setSource(expr, new OpLambdaValue((OpDefNode)val, this, c, s0, s1)); } return (Value)val; } default: { Assert.fail("Attempted to evaluate an expression that cannot be evaluated.\n" + expr); return null; // make compiler happy } } } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } private final Value evalAppl(final OpApplNode expr, Context c, TLCState s0, TLCState s1, final int control) { if (this.callStack != null) { return evalApplWithCallStack(expr, c, s0, s1, control); } else { return evalApplImpl(expr, c, s0, s1, control); } } private final Value evalApplWithCallStack(final OpApplNode expr, Context c, TLCState s0, TLCState s1, final int control) { this.callStack.push(expr); try { return evalApplImpl(expr, c, s0, s1, control); } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) this.callStack.freeze(); throw e; } finally { this.callStack.pop(); } } private final Value evalApplImpl(final OpApplNode expr, Context c, TLCState s0, TLCState s1, final int control) { ExprOrOpArgNode[] args = expr.getArgs(); SymbolNode opNode = expr.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, s0, EvalControl.isPrimed(control)); // First, unlazy if it is a lazy value. We cannot use the cached // value when s1 == null or isEnabled(control). if (val instanceof LazyValue) { final LazyValue lv = (LazyValue) val; if (s1 == null) { val = this.eval(lv.expr, lv.con, s0, null, control); } else if (lv.isUncachable() || EvalControl.isEnabled(control)) { // Never use cached LazyValues in an ENABLED expression. This is why all // this.enabled* methods pass EvalControl.Enabled (the only exclusion being the // call on line line 2799 which passes EvalControl.Primed). This is why we can // be sure that ENALBED expressions are not affected by the caching bug tracked // in Github issue 113 (see below). val = this.eval(lv.expr, lv.con, s0, s1, control); } else { val = lv.getValue(); if (val == null) { final Value res = this.eval(lv.expr, lv.con, s0, s1, control); // This check has been suggested by Yuan Yu on 01/15/2018: // If init-states are being generated, level has to be <= ConstantLevel for // caching/LazyValue to be allowed. If next-states are being generated, level // has to be <= VariableLevel. The level indicates if the expression to be // evaluated contains only constants, constants & variables, constants & // variables and primed variables (thus action) or is a temporal formula. // This restriction is in place to fix Github issue 113 // TLC can generate invalid sets of init or next-states caused by broken // LazyValue evaluation. The related tests are AssignmentInit* and // AssignmentNext*. Without this fix TLC essentially reuses a stale lv.val when // it needs to re-evaluate res because the actual operands to eval changed. // Below is Leslie's formal description of the bug: // The possible initial values of some variable var are specified by a subformula // F(..., var, ...) // in the initial predicate, for some operator F such that expanding the // definition of F results in a formula containing more than one occurrence of // var , not all occurring in separate disjuncts of that formula. // The possible next values of some variable var are specified by a subformula // F(..., var', ...) // in the next-state relation, for some operator F such that expanding the // definition of F results in a formula containing more than one occurrence of // var' , not all occurring in separate disjuncts of that formula. // An example of the first case is an initial predicate Init defined as follows: // VARIABLES x, ... // F(var) == \/ var \in 0..99 /\ var % 2 = 0 // \/ var = -1 // Init == /\ F(x) // The error would not appear if F were defined by: // F(var) == \/ var \in {i \in 0..99 : i % 2 = 0} // \/ var = -1 // or if the definition of F(x) were expanded in Init : // Init == /\ \/ x \in 0..99 /\ x % 2 = 0 // \/ x = -1 // A similar example holds for case 2 with the same operator F and the // next-state formula // Next == /\ F(x') // The workaround is to rewrite the initial predicate or next-state relation so // it is not in the form that can cause the bug. The simplest way to do that is // to expand (in-line) the definition of F in the definition of the initial // predicate or next-state relation. // Note that EvalControl.Init is only set in the scope of this.getInitStates*, // but not in the scope of methods such as this.isInModel, this.isGoodState... // which are invoked by DFIDChecker and ModelChecker#doInit and doNext. These // invocation however don't pose a problem with regards to issue 113 because // they don't generate the set of initial or next states but get passed fully // generated/final states. // !EvalControl.isInit(control) means Tool is either processing the spec in // this.process* as part of initialization or that next-states are being // generated. The latter case has to restrict usage of cached LazyValue as // discussed above. final int level = ((LevelNode) lv.expr).getLevel(); // cast to LevelNode is safe because LV only subclass of SN. if ((EvalControl.isInit(control) && level <= LevelConstants.ConstantLevel) || (!EvalControl.isInit(control) && level <= LevelConstants.VariableLevel)) { // The performance benefits of caching values is generally debatable. The time // it takes TLC to check a reasonable sized model of the PaxosCommit [1] spec is // ~2h with, with limited caching due to the fix for issue 113 or without // caching. There is no measurable performance difference even though the change // for issue 113 reduces the cache hits from ~13 billion to ~4 billion. This was // measured with an instrumented version of TLC. // [1] general/performance/PaxosCommit/ lv.setValue(res); } val = res; } } } Value res = null; if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode)val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { Context c1 = this.getOpContext(opDef, args, c, true); res = this.eval(opDef.getBody(), c1, s0, s1, control); } } else if (val instanceof Value) { res = (Value)val; int alen = args.length; if (alen == 0) { if (val instanceof MethodValue) { res = ((MethodValue)val).apply(EmptyArgs, EvalControl.Clear); } } else { if (val instanceof OpValue) { Applicable opVal = (Applicable)val; Value[] argVals = new Value[alen]; // evaluate the actuals: for (int i = 0; i < alen; i++) { argVals[i] = this.eval(args[i], c, s0, s1, control); } // apply the operator: res = opVal.apply(argVals, control); } } } else if (val instanceof ThmOrAssumpDefNode) { // Assert.fail("Trying to evaluate the theorem or assumption name `" // + opNode.getName() + "'. \nUse `" + opNode.getName() // + "!:' instead.\n" +expr); ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode) val ; Context c1 = this.getOpContext(opDef, args, c, true); return this.eval(opDef.getBody(), c1, s0, s1, control); } else { Assert.fail(EC.TLC_CONFIG_UNDEFINED_OR_NO_OPERATOR, new String[] { opNode.getName().toString(), expr.toString() }); } if (opcode == 0) { return res; } } switch (opcode) { case OPCODE_bc: // BoundedChoose { SemanticNode pred = args[0]; SemanticNode inExpr = expr.getBdedQuantBounds()[0]; Value inVal = this.eval(inExpr, c, s0, s1, control); if (!(inVal instanceof Enumerable)) { Assert.fail("Attempted to compute the value of an expression of\n" + "form CHOOSE x \\in S: P, but S was not enumerable.\n" + expr); } // To fix Bugzilla Bug 279 : TLC bug caused by TLC's not preserving the semantics of CHOOSE // (@see tlc2.tool.BugzillaBug279Test), // the statement // inVal.normalize(); // was replaced by the following by LL on 7 Mar 2012. This fix has not yet received // the blessing of Yuan Yu, so it should be considered to be provisional. // Value convertedVal = inVal.ToSetEnum(); // if (convertedVal != null) { // inVal = convertedVal; // } else { // inVal.normalize(); // end of fix. // MAK 09/22/2018: // The old fix above has the undesired side effect of enumerating inVal. In // other words, e.g. a SUBSET 1..8 would be enumerated and normalized into a // SetEnumValue. This is expensive and especially overkill, if the CHOOSE // predicate holds for most if not all elements of inVal. In this case, we // don't want to fully enumerate inVal but instead return the first element // obtained from Enumerable#elements for which the predicate holds. Thus, // Enumerable#elements(Ordering) has been added by which we make the requirement // for elements to be normalized explicit. Implementor of Enumerable, such as // SubsetValue are then free to implement elements that returns elements in // normalized order without converting SubsetValue into SetEnumValue first. inVal.normalize(); ValueEnumeration enumSet = ((Enumerable)inVal).elements(Enumerable.Ordering.NORMALIZED); FormalParamNode[] bvars = expr.getBdedQuantSymbolLists()[0]; boolean isTuple = expr.isBdedQuantATuple()[0]; if (isTuple) { // Identifier tuple case: int cnt = bvars.length; Value val; while ((val = enumSet.nextElement()) != null) { TupleValue tv = val.toTuple(); if (tv == null || tv.size() != cnt) { Assert.fail("Attempted to compute the value of an expression of form\n" + "CHOOSE <<x1, ... , xN>> \\in S: P, but S was not a set\n" + "of N-tuples.\n" + expr); } Context c1 = c; for (int i = 0; i < cnt; i++) { c1 = c1.cons(bvars[i], tv.elems[i]); } Value bval = this.eval(pred, c1, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}); } if (((BoolValue)bval).val) { return val; } } } else { // Simple identifier case: SymbolNode name = bvars[0]; Value val; while ((val = enumSet.nextElement()) != null) { Context c1 = c.cons(name, val); Value bval = this.eval(pred, c1, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}); } if (((BoolValue)bval).val) { return val; } } } Assert.fail("Attempted to compute the value of an expression of form\n" + "CHOOSE x \\in S: P, but no element of S satisfied P.\n" + expr); return null; // make compiler happy } case OPCODE_be: // BoundedExists { ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control); SemanticNode body = args[0]; Context c1; while ((c1 = Enum.nextElement()) != null) { Value bval = this.eval(body, c1, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}); } if (((BoolValue)bval).val) { return ValTrue; } } return ValFalse; } case OPCODE_bf: // BoundedForall { ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control); SemanticNode body = args[0]; Context c1; while ((c1 = Enum.nextElement()) != null) { Value bval = this.eval(body, c1, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}); } if (!((BoolValue)bval).val) { return ValFalse; } } return ValTrue; } case OPCODE_case: // Case { int alen = args.length; SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pairNode.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as a condition of a CASE. " + pairArgs[0]); } if (((BoolValue)bval).val) { return this.eval(pairArgs[1], c, s0, s1, control); } } } if (other == null) { Assert.fail("Attempted to evaluate a CASE with no conditions true.\n" + expr); } return this.eval(other, c, s0, s1, control); } case OPCODE_cp: // CartesianProd { int alen = args.length; Value[] sets = new Value[alen]; for (int i = 0; i < alen; i++) { sets[i] = this.eval(args[i], c, s0, s1, control); } return setSource(expr, new SetOfTuplesValue(sets)); } case OPCODE_cl: // ConjList { int alen = args.length; for (int i = 0; i < alen; i++) { Value bval = this.eval(args[i], c, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as a formula in a conjunction.\n" + args[i]); } if (!((BoolValue)bval).val) { return ValFalse; } } return ValTrue; } case OPCODE_dl: // DisjList { int alen = args.length; for (int i = 0; i < alen; i++) { Value bval = this.eval(args[i], c, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as a formula in a disjunction.\n" + args[i]); } if (((BoolValue)bval).val) { return ValTrue; } } return ValFalse; } case OPCODE_exc: // Except { int alen = args.length; Value result = this.eval(args[0], c, s0, s1, control); // SZ: variable not used ValueExcept[] expts = new ValueExcept[alen-1]; for (int i = 1; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pairArgs = pairNode.getArgs(); SemanticNode[] cmpts = ((OpApplNode)pairArgs[0]).getArgs(); Value[] lhs = new Value[cmpts.length]; for (int j = 0; j < lhs.length; j++) { lhs[j] = this.eval(cmpts[j], c, s0, s1, control); } Value atVal = result.select(lhs); if (atVal == null) { // Do nothing but warn: MP.printWarning(EC.TLC_EXCEPT_APPLIED_TO_UNKNOWN_FIELD, new String[]{args[0].toString()}); } else { Context c1 = c.cons(EXCEPT_AT, atVal); Value rhs = this.eval(pairArgs[1], c1, s0, s1, control); ValueExcept vex = new ValueExcept(lhs, rhs); result = result.takeExcept(vex); } } return result; } case OPCODE_fa: // FcnApply { Value result = null; Value fval = this.eval(args[0], c, s0, s1, EvalControl.setKeepLazy(control)); if ((fval instanceof FcnRcdValue) || (fval instanceof FcnLambdaValue)) { Applicable fcn = (Applicable)fval; Value argVal = this.eval(args[1], c, s0, s1, control); result = fcn.apply(argVal, control); } else if ((fval instanceof TupleValue) || (fval instanceof RecordValue)) { Applicable fcn = (Applicable)fval; if (args.length != 2) { Assert.fail("Attempted to evaluate an expression of form f[e1, ... , eN]" + "\nwith f a tuple or record and N > 1.\n" + expr); } Value aval = this.eval(args[1], c, s0, s1, control); result = fcn.apply(aval, control); } else { Assert.fail("A non-function (" + fval.getKindString() + ") was applied" + " as a function.\n" + expr); } return result; } case OPCODE_fc: // FcnConstructor case OPCODE_nrfs: // NonRecursiveFcnSpec case OPCODE_rfs: // RecursiveFcnSpec { FormalParamNode[][] formals = expr.getBdedQuantSymbolLists(); boolean[] isTuples = expr.isBdedQuantATuple(); ExprNode[] domains = expr.getBdedQuantBounds(); Value[] dvals = new Value[domains.length]; boolean isFcnRcd = true; for (int i = 0; i < dvals.length; i++) { dvals[i] = this.eval(domains[i], c, s0, s1, control); isFcnRcd = isFcnRcd && (dvals[i] instanceof Reducible); } FcnParams params = new FcnParams(formals, isTuples, dvals); SemanticNode fbody = args[0]; FcnLambdaValue fval = (FcnLambdaValue) setSource(expr, new FcnLambdaValue(params, fbody, this, c, s0, s1, control)); if (opcode == OPCODE_rfs) { SymbolNode fname = expr.getUnbdedQuantSymbols()[0]; fval.makeRecursive(fname); isFcnRcd = false; } if (isFcnRcd && !EvalControl.isKeepLazy(control)) { return fval.toFcnRcd(); } return fval; } case OPCODE_ite: // IfThenElse { Value bval = this.eval(args[0], c, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail("A non-boolean expression (" + bval.getKindString() + ") was used as the condition of an IF.\n" + expr); } if (((BoolValue)bval).val) { return this.eval(args[1], c, s0, s1, control); } return this.eval(args[2], c, s0, s1, control); } case OPCODE_rc: // RcdConstructor { int alen = args.length; UniqueString[] names = new UniqueString[alen]; Value[] vals = new Value[alen]; for (int i = 0; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pair = pairNode.getArgs(); names[i] = ((StringValue)Value.getValue(pair[0])).getVal(); vals[i] = this.eval(pair[1], c, s0, s1, control); } return setSource(expr, new RecordValue(names, vals, false)); } case OPCODE_rs: // RcdSelect { Value rval = this.eval(args[0], c, s0, s1, control); Value sval = Value.getValue(args[1]); if (rval instanceof RecordValue) { Value result = ((RecordValue)rval).select(sval); if (result == null) { Assert.fail("Attempted to select nonexistent field " + sval + " from the" + " record\n" + Value.ppr(rval.toString()) + "\n" + expr); } return result; } else { FcnRcdValue fcn = rval.toFcnRcd(); if (fcn == null) { Assert.fail("Attempted to select field " + sval + " from a non-record" + " value " + Value.ppr(rval.toString()) + "\n" + expr); } return fcn.apply(sval, control); } } case OPCODE_se: // SetEnumerate { int alen = args.length; ValueVec vals = new ValueVec(alen); for (int i = 0; i < alen; i++) { vals.addElement(this.eval(args[i], c, s0, s1, control)); } return setSource(expr, new SetEnumValue(vals, false)); } case OPCODE_soa: // SetOfAll: {e(x) : x \in S} { ValueVec vals = new ValueVec(); ContextEnumerator Enum = this.contexts(expr, c, s0, s1, control); SemanticNode body = args[0]; Context c1; while ((c1 = Enum.nextElement()) != null) { Value val = this.eval(body, c1, s0, s1, control); vals.addElement(val); // vals.addElement1(val); } return setSource(expr, new SetEnumValue(vals, false)); } case OPCODE_sor: // SetOfRcds { int alen = args.length; UniqueString names[] = new UniqueString[alen]; Value vals[] = new Value[alen]; for (int i = 0; i < alen; i++) { OpApplNode pairNode = (OpApplNode)args[i]; ExprOrOpArgNode[] pair = pairNode.getArgs(); names[i] = ((StringValue)Value.getValue(pair[0])).getVal(); vals[i] = this.eval(pair[1], c, s0, s1, control); } return setSource(expr, new SetOfRcdsValue(names, vals, false)); } case OPCODE_sof: // SetOfFcns { Value lhs = this.eval(args[0], c, s0, s1, control); Value rhs = this.eval(args[1], c, s0, s1, control); return setSource(expr, new SetOfFcnsValue(lhs, rhs)); } case OPCODE_sso: // SubsetOf { SemanticNode pred = args[0]; SemanticNode inExpr = expr.getBdedQuantBounds()[0]; Value inVal = this.eval(inExpr, c, s0, s1, control); boolean isTuple = expr.isBdedQuantATuple()[0]; FormalParamNode[] bvars = expr.getBdedQuantSymbolLists()[0]; if (inVal instanceof Reducible) { ValueVec vals = new ValueVec(); ValueEnumeration enumSet = ((Enumerable)inVal).elements(); Value elem; if (isTuple) { while ((elem = enumSet.nextElement()) != null) { Context c1 = c; Value[] tuple = ((TupleValue)elem).elems; for (int i = 0; i < bvars.length; i++) { c1 = c1.cons(bvars[i], tuple[i]); } Value bval = this.eval(pred, c1, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form {x \\in S : P(x)}" + " when P was " + bval.getKindString() + ".\n" + pred); } if (((BoolValue)bval).val) { vals.addElement(elem); } } } else { SymbolNode idName = bvars[0]; while ((elem = enumSet.nextElement()) != null) { Context c1 = c.cons(idName, elem); Value bval = this.eval(pred, c1, s0, s1, control); if (!(bval instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form {x \\in S : P(x)}" + " when P was " + bval.getKindString() + ".\n" + pred); } if (((BoolValue)bval).val) { vals.addElement(elem); } } } return setSource(expr, new SetEnumValue(vals, inVal.isNormalized())); } else if (isTuple) { return setSource(expr, new SetPredValue(bvars, inVal, pred, this, c, s0, s1, control)); } else { return setSource(expr, new SetPredValue(bvars[0], inVal, pred, this, c, s0, s1, control)); } } case OPCODE_tup: // Tuple { int alen = args.length; Value[] vals = new Value[alen]; for (int i = 0; i < alen; i++) { vals[i] = this.eval(args[i], c, s0, s1, control); } return setSource(expr, new TupleValue(vals)); } case OPCODE_uc: // UnboundedChoose { Assert.fail("TLC attempted to evaluate an unbounded CHOOSE.\n" + "Make sure that the expression is of form CHOOSE x \\in S: P(x).\n" + expr); return null; // make compiler happy } case OPCODE_ue: // UnboundedExists { Assert.fail("TLC attempted to evaluate an unbounded \\E.\n" + "Make sure that the expression is of form \\E x \\in S: P(x).\n" + expr); return null; // make compiler happy } case OPCODE_uf: // UnboundedForall { Assert.fail("TLC attempted to evaluate an unbounded \\A.\n" + "Make sure that the expression is of form \\A x \\in S: P(x).\n" + expr); return null; // make compiler happy } case OPCODE_lnot: { Value arg = this.eval(args[0], c, s0, s1, control); if (!(arg instanceof BoolValue)) { Assert.fail("Attempted to apply the operator ~ to a non-boolean\n(" + arg.getKindString() + ")\n" + expr); } return (((BoolValue)arg).val) ? ValFalse : ValTrue; } case OPCODE_subset: { Value arg = this.eval(args[0], c, s0, s1, control); return setSource(expr, new SubsetValue(arg)); } case OPCODE_union: { Value arg = this.eval(args[0], c, s0, s1, control); return setSource(expr, UnionValue.union(arg)); } case OPCODE_domain: { Value arg = this.eval(args[0], c, s0, s1, control); if (!(arg instanceof Applicable)) { Assert.fail("Attempted to apply the operator DOMAIN to a non-function\n(" + arg.getKindString() + ")\n" + expr); } return setSource(expr, ((Applicable)arg).getDomain()); } case OPCODE_enabled: { TLCState sfun = TLCStateFun.Empty; Context c1 = Context.branch(c); sfun = this.enabled(args[0], ActionItemList.Empty, c1, s0, sfun); return (sfun != null) ? ValTrue : ValFalse; } case OPCODE_eq: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); return (arg1.equals(arg2)) ? ValTrue : ValFalse; } case OPCODE_land: { Value arg1 = this.eval(args[0], c, s0, s1, control); if (!(arg1 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P /\\ Q" + " when P was\n" + arg1.getKindString() + ".\n" + expr); } if (((BoolValue)arg1).val) { Value arg2 = this.eval(args[1], c, s0, s1, control); if (!(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P /\\ Q" + " when Q was\n" + arg2.getKindString() + ".\n" + expr); } return arg2; } return ValFalse; } case OPCODE_lor: { Value arg1 = this.eval(args[0], c, s0, s1, control); if (!(arg1 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P \\/ Q" + " when P was\n" + arg1.getKindString() + ".\n" + expr); } if (((BoolValue)arg1).val) { return ValTrue; } Value arg2 = this.eval(args[1], c, s0, s1, control); if (!(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P \\/ Q" + " when Q was\n" + arg2.getKindString() + ".\n" + expr); } return arg2; } case OPCODE_implies: { Value arg1 = this.eval(args[0], c, s0, s1, control); if (!(arg1 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P => Q" + " when P was\n" + arg1.getKindString() + ".\n" + expr); } if (((BoolValue)arg1).val) { Value arg2 = this.eval(args[1], c, s0, s1, control); if (!(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P => Q" + " when Q was\n" + arg2.getKindString() + ".\n" + expr); } return arg2; } return ValTrue; } case OPCODE_equiv: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); if (!(arg1 instanceof BoolValue) || !(arg2 instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form P <=> Q" + " when P or Q was not a boolean.\n" + expr); } BoolValue bval1 = (BoolValue)arg1; BoolValue bval2 = (BoolValue)arg2; return (bval1.val == bval2.val) ? ValTrue : ValFalse; } case OPCODE_noteq: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); return arg1.equals(arg2) ? ValFalse : ValTrue; } case OPCODE_subseteq: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); if (!(arg1 instanceof Enumerable)) { Assert.fail("Attempted to evaluate an expression of form S \\subseteq T," + " but S was not enumerable.\n" + expr); } return ((Enumerable) arg1).isSubsetEq(arg2); } case OPCODE_in: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); return (arg2.member(arg1)) ? ValTrue : ValFalse; } case OPCODE_notin: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); return (arg2.member(arg1)) ? ValFalse : ValTrue; } case OPCODE_setdiff: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); if (arg1 instanceof Reducible) { return setSource(expr, ((Reducible)arg1).diff(arg2)); } return setSource(expr, new SetDiffValue(arg1, arg2)); } case OPCODE_cap: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); if (arg1 instanceof Reducible) { return setSource(expr, ((Reducible)arg1).cap(arg2)); } else if (arg2 instanceof Reducible) { return setSource(expr, ((Reducible)arg2).cap(arg1)); } return setSource(expr, new SetCapValue(arg1, arg2)); } case OPCODE_nop: // Added by LL on 2 Aug 2007 { return eval(args[0], c, s0, s1, control); } case OPCODE_cup: { Value arg1 = this.eval(args[0], c, s0, s1, control); Value arg2 = this.eval(args[1], c, s0, s1, control); if (arg1 instanceof Reducible) { return setSource(expr, ((Reducible)arg1).cup(arg2)); } else if (arg2 instanceof Reducible) { return setSource(expr, ((Reducible)arg2).cup(arg1)); } return setSource(expr, new SetCupValue(arg1, arg2)); } case OPCODE_prime: { return this.eval(args[0], c, s1, null, EvalControl.setPrimedIfEnabled(control)); } case OPCODE_unchanged: { Value v0 = this.eval(args[0], c, s0, TLCState.Empty, control); Value v1 = this.eval(args[0], c, s1, null, EvalControl.setPrimedIfEnabled(control)); return (v0.equals(v1)) ? ValTrue : ValFalse; } case OPCODE_aa: { Value res = this.eval(args[0], c, s0, s1, control); if (!(res instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form <A>_e," + " but A was not a boolean.\n" + expr); } if (!((BoolValue)res).val) { return ValFalse; } Value v0 = this.eval(args[1], c, s0, TLCState.Empty, control); Value v1 = this.eval(args[1], c, s1, null, EvalControl.setPrimedIfEnabled(control)); return v0.equals(v1) ? ValFalse : ValTrue; } case OPCODE_sa: { Value res = this.eval(args[0], c, s0, s1, control); if (!(res instanceof BoolValue)) { Assert.fail("Attempted to evaluate an expression of form [A]_e," + " but A was not a boolean.\n" + expr); } if (((BoolValue)res).val) { return ValTrue; } Value v0 = this.eval(args[1], c, s0, TLCState.Empty, control); Value v1 = this.eval(args[1], c, s1, null, EvalControl.setPrimedIfEnabled(control)); return (v0.equals(v1)) ? ValTrue : ValFalse; } case OPCODE_cdot: { Assert.fail("The current version of TLC does not support action composition."); return null; // make compiler happy } case OPCODE_sf: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"SF", expr.toString()}); return null; // make compiler happy } case OPCODE_wf: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"WF", expr.toString()}); return null; // make compiler happy } case OPCODE_te: // TemporalExists { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"\\EE", expr.toString()}); return null; // make compiler happy } case OPCODE_tf: // TemporalForAll { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"\\AA", expr.toString()}); return null; // make compiler happy } case OPCODE_leadto: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"a ~> b", expr.toString()}); return null; // make compiler happy } case OPCODE_arrow: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"a -+-> formula", expr.toString()}); return null; // make compiler happy } case OPCODE_box: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"[]A", expr.toString()}); return null; // make compiler happy } case OPCODE_diamond: { Assert.fail(EC.TLC_ENCOUNTERED_FORMULA_IN_PREDICATE, new String[]{"<>A", expr.toString()}); return null; // make compiler happy } default: { Assert.fail("TLC BUG: could not evaluate this expression.\n" + expr); return null; } } } private final Value setSource(final SemanticNode expr, final Value value) { if (this.callStack != null) { value.setSource(expr); } return value; } public final boolean isGoodState(TLCState state) { return state.allAssigned(); } /* This method determines if a state satisfies the model constraints. */ public final boolean isInModel(TLCState state) throws EvalException { ExprNode[] constrs = this.getModelConstraints(); for (int i = 0; i < constrs.length; i++) { Value bval = this.eval(constrs[i], Context.Empty, state); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", constrs[i].toString()}); } if (!((BoolValue)bval).val) return false; } return true; } /* This method determines if a pair of states satisfy the action constraints. */ public final boolean isInActions(TLCState s1, TLCState s2) throws EvalException { ExprNode[] constrs = this.getActionConstraints(); for (int i = 0; i < constrs.length; i++) { Value bval = this.eval(constrs[i], Context.Empty, s1, s2, EvalControl.Clear); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", constrs[i].toString()}); } if (!((BoolValue)bval).val) return false; } return true; } /** * This method determines if an action is enabled in the given state. * More precisely, it determines if (act.pred /\ (sub' # sub)) is * enabled in the state s and context act.con. */ public final TLCState enabled(SemanticNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1) { if (this.callStack != null) this.callStack.push(pred); try { switch (pred.getKind()) { case OpApplKind: { OpApplNode pred1 = (OpApplNode)pred; return this.enabledAppl(pred1, acts, c, s0, s1); } case LetInKind: { LetInNode pred1 = (LetInNode)pred; OpDefNode[] letDefs = pred1.getLets(); Context c1 = c; for (int i = 0; i < letDefs.length; i++) { OpDefNode opDef = letDefs[i]; if (opDef.getArity() == 0) { Value rhs = new LazyValue(opDef.getBody(), c1); c1 = c1.cons(opDef, rhs); } } return this.enabled(pred1.getBody(), acts, c1, s0, s1); } case SubstInKind: { SubstInNode pred1 = (SubstInNode)pred; Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false)); } return this.enabled(pred1.getBody(), acts, c1, s0, s1); } // Added by LL on 13 Nov 2009 to handle theorem and assumption names. case APSubstInKind: { APSubstInNode pred1 = (APSubstInNode)pred; Subst[] subs = pred1.getSubsts(); int slen = subs.length; Context c1 = c; for (int i = 0; i < slen; i++) { Subst sub = subs[i]; c1 = c1.cons(sub.getOp(), this.getVal(sub.getExpr(), c, false)); } return this.enabled(pred1.getBody(), acts, c1, s0, s1); } // LabelKind class added by LL on 13 Jun 2007 case LabelKind: { LabelNode pred1 = (LabelNode)pred; return this.enabled(pred1.getBody(), acts, c, s0, s1); } default: { // We should not compute enabled on anything else. Assert.fail("Attempted to compute ENABLED on a non-boolean expression.\n" + pred); return null; // make compiler happy } } } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } private final TLCState enabled(ActionItemList acts, TLCState s0, TLCState s1) { if (acts.isEmpty()) return s1; final int kind = acts.carKind(); SemanticNode pred = acts.carPred(); Context c = acts.carContext(); ActionItemList acts1 = acts.cdr(); if (kind > ActionItemList.CONJUNCT) { TLCState res = this.enabled(pred, acts1, c, s0, s1); return res; } else if (kind == ActionItemList.PRED) { TLCState res = this.enabled(pred, acts1, c, s0, s1); return res; } if (kind == ActionItemList.UNCHANGED) { TLCState res = this.enabledUnchanged(pred, acts1, c, s0, s1); return res; } Value v1 = this.eval(pred, c, s0, TLCState.Empty, EvalControl.Enabled); // We are now in ENABLED and primed state. Second TLCState parameter being null // effectively disables LazyValue in evalAppl (same effect as // EvalControl.setPrimed(EvalControl.Enabled)). Value v2 = this.eval(pred, c, s1, null, EvalControl.Primed); if (v1.equals(v2)) return null; TLCState res = this.enabled(acts1, s0, s1); return res; } private final TLCState enabledAppl(OpApplNode pred, ActionItemList acts, Context c, TLCState s0, TLCState s1) { if (this.callStack != null) this.callStack.push(pred); try { ExprOrOpArgNode[] args = pred.getArgs(); int alen = args.length; SymbolNode opNode = pred.getOperator(); int opcode = BuiltInOPs.getOpCode(opNode.getName()); if (opcode == 0) { // This is a user-defined operator with one exception: it may // be substed by a builtin operator. This special case occurs // when the lookup returns an OpDef with opcode Object val = this.lookup(opNode, c, s0, false); if (val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode) val; opcode = BuiltInOPs.getOpCode(opDef.getName()); if (opcode == 0) { // Context c1 = this.getOpContext(opDef, args, c, false); Context c1 = this.getOpContext(opDef, args, c, true); return this.enabled(opDef.getBody(), acts, c1, s0, s1); } } // Added 13 Nov 2009 by LL to handle theorem or assumption names if (val instanceof ThmOrAssumpDefNode) { ThmOrAssumpDefNode opDef = (ThmOrAssumpDefNode) val; Context c1 = this.getOpContext(opDef, args, c, true); return this.enabled(opDef.getBody(), acts, c1, s0, s1); } if (val instanceof LazyValue) { LazyValue lv = (LazyValue) val; return this.enabled(lv.expr, acts, lv.con, s0, s1); } Object bval = val; if (alen == 0) { if (val instanceof MethodValue) { bval = ((MethodValue) val).apply(EmptyArgs, EvalControl.Clear); // EvalControl.Clear is ignored by MethodValuea#apply } } else { if (val instanceof OpValue) { Applicable op = (Applicable) val; Value[] argVals = new Value[alen]; // evaluate the actuals: for (int i = 0; i < alen; i++) { argVals[i] = this.eval(args[i], c, s0, s1, EvalControl.Enabled); } // apply the operator: bval = op.apply(argVals, EvalControl.Enabled); } } if (opcode == 0) { if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "ENABLED", "boolean", bval.toString(), pred.toString() }); } if (((BoolValue) bval).val) { return this.enabled(acts, s0, s1); } return null; } } switch (opcode) { case OPCODE_aa: // AngleAct <A>_e { ActionItemList acts1 = acts.cons(args[1], c, ActionItemList.CHANGED); return this.enabled(args[0], acts1, c, s0, s1); } case OPCODE_be: // BoundedExists { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Enabled); Context c1; while ((c1 = Enum.nextElement()) != null) { TLCState s2 = this.enabled(body, acts, c1, s0, s1); if (s2 != null) { return s2; } } return null; } case OPCODE_bf: // BoundedForall { SemanticNode body = args[0]; ContextEnumerator Enum = this.contexts(pred, c, s0, s1, EvalControl.Enabled); Context c1 = Enum.nextElement(); if (c1 == null) { return this.enabled(acts, s0, s1); } ActionItemList acts1 = acts; Context c2; while ((c2 = Enum.nextElement()) != null) { acts1 = acts1.cons(body, c2, ActionItemList.PRED); } return this.enabled(body, acts1, c1, s0, s1); } case OPCODE_case: // Case { SemanticNode other = null; for (int i = 0; i < alen; i++) { OpApplNode pair = (OpApplNode) args[i]; ExprOrOpArgNode[] pairArgs = pair.getArgs(); if (pairArgs[0] == null) { other = pairArgs[1]; } else { Value bval = this.eval(pairArgs[0], c, s0, s1, EvalControl.Enabled); if (!(bval instanceof BoolValue)) { Assert.fail("In computing ENABLED, a non-boolean expression(" + bval.getKindString() + ") was used as a guard condition" + " of a CASE.\n" + pairArgs[1]); } if (((BoolValue) bval).val) { return this.enabled(pairArgs[1], acts, c, s0, s1); } } } if (other == null) { Assert.fail("In computing ENABLED, TLC encountered a CASE with no" + " conditions true.\n" + pred); } return this.enabled(other, acts, c, s0, s1); } case OPCODE_cl: // ConjList case OPCODE_land: { ActionItemList acts1 = acts; for (int i = alen - 1; i > 0; i { acts1 = acts1.cons(args[i], c, i); } return this.enabled(args[0], acts1, c, s0, s1); } case OPCODE_dl: // DisjList case OPCODE_lor: { for (int i = 0; i < alen; i++) { TLCState s2 = this.enabled(args[i], acts, c, s0, s1); if (s2 != null) { return s2; } } return null; } case OPCODE_fa: // FcnApply { Value fval = this.eval(args[0], c, s0, s1, EvalControl.setKeepLazy(EvalControl.Enabled)); // KeepLazy does not interfere with EvalControl.Enabled in this.evalAppl if (fval instanceof FcnLambdaValue) { FcnLambdaValue fcn = (FcnLambdaValue) fval; if (fcn.fcnRcd == null) { Context c1 = this.getFcnContext(fcn, args, c, s0, s1, EvalControl.Enabled); // EvalControl.Enabled passed on to nested this.evalAppl return this.enabled(fcn.body, acts, c1, s0, s1); } fval = fcn.fcnRcd; } if (fval instanceof Applicable) { Applicable fcn = (Applicable) fval; Value argVal = this.eval(args[1], c, s0, s1, EvalControl.Enabled); Value bval = fcn.apply(argVal, EvalControl.Enabled); // EvalControl.Enabled not taken into account by any subclass of Applicable if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING2, new String[] { "ENABLED", "boolean", pred.toString() }); } if (!((BoolValue) bval).val) { return null; } } else { Assert.fail("In computing ENABLED, a non-function (" + fval.getKindString() + ") was applied as a function.\n" + pred); } return this.enabled(acts, s0, s1); } case OPCODE_ite: // IfThenElse { Value guard = this.eval(args[0], c, s0, s1, EvalControl.Enabled); if (!(guard instanceof BoolValue)) { Assert.fail("In computing ENABLED, a non-boolean expression(" + guard.getKindString() + ") was used as the guard condition" + " of an IF.\n" + pred); } int idx = (((BoolValue) guard).val) ? 1 : 2; return this.enabled(args[idx], acts, c, s0, s1); } case OPCODE_sa: // SquareAct [A]_e { TLCState s2 = this.enabled(args[0], acts, c, s0, s1); if (s2 != null) { return s2; } return this.enabledUnchanged(args[1], acts, c, s0, s1); } case OPCODE_te: // TemporalExists case OPCODE_tf: // TemporalForAll { Assert.fail("In computing ENABLED, TLC encountered temporal quantifier.\n" + pred); return null; // make compiler happy } case OPCODE_uc: // UnboundedChoose { Assert.fail("In computing ENABLED, TLC encountered unbounded CHOOSE. " + "Make sure that the expression is of form CHOOSE x \\in S: P(x).\n" + pred); return null; // make compiler happy } case OPCODE_ue: // UnboundedExists { Assert.fail("In computing ENABLED, TLC encountered unbounded quantifier. " + "Make sure that the expression is of form \\E x \\in S: P(x).\n" + pred); return null; // make compiler happy } case OPCODE_uf: // UnboundedForall { Assert.fail("In computing ENABLED, TLC encountered unbounded quantifier. " + "Make sure that the expression is of form \\A x \\in S: P(x).\n" + pred); return null; // make compiler happy } case OPCODE_sf: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[]{ "SF", pred.toString()}); return null; // make compiler happy } case OPCODE_wf: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "WF", pred.toString() }); return null; // make compiler happy } case OPCODE_box: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "[]", pred.toString() }); return null; // make compiler happy } case OPCODE_diamond: { Assert.fail(EC.TLC_ENABLED_WRONG_FORMULA, new String[] { "<>", pred.toString() }); return null; // make compiler happy } case OPCODE_unchanged: { return this.enabledUnchanged(args[0], acts, c, s0, s1); } case OPCODE_eq: { SymbolNode var = this.getPrimedVar(args[0], c, true); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled); if (!((BoolValue) bval).val) { return null; } } else { UniqueString varName = var.getName(); Value lval = s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Enabled); if (lval == null) { TLCState s2 = s1.bind(var, rval, pred); return this.enabled(acts, s0, s2); } else { if (!lval.equals(rval)) { return null; } } } return this.enabled(acts, s0, s1); } case OPCODE_implies: { Value bval = this.eval(args[0], c, s0, s1, EvalControl.Enabled); if (!(bval instanceof BoolValue)) { Assert.fail("While computing ENABLED of an expression of the form" + " P => Q, P was " + bval.getKindString() + ".\n" + pred); } if (((BoolValue) bval).val) { return this.enabled(args[1], acts, c, s0, s1); } return this.enabled(acts, s0, s1); } case OPCODE_cdot: { Assert.fail("The current version of TLC does not support action composition."); return null; // make compiler happy } case OPCODE_leadto: { Assert.fail("In computing ENABLED, TLC encountered a temporal formula" + " (a ~> b).\n" + pred); return null; // make compiler happy } case OPCODE_arrow: { Assert.fail("In computing ENABLED, TLC encountered a temporal formula" + " (a -+-> formula).\n" + pred); return null; // make compiler happy } case OPCODE_in: { SymbolNode var = this.getPrimedVar(args[0], c, true); if (var == null) { Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled); if (!((BoolValue) bval).val) { return null; } } else { UniqueString varName = var.getName(); Value lval = s1.lookup(varName); Value rval = this.eval(args[1], c, s0, s1, EvalControl.Enabled); if (lval == null) { if (!(rval instanceof Enumerable)) { Assert.fail("The right side of \\IN is not enumerable.\n" + pred); } ValueEnumeration Enum = ((Enumerable) rval).elements(); Value val; while ((val = Enum.nextElement()) != null) { TLCState s2 = s1.bind(var, val, pred); s2 = this.enabled(acts, s0, s2); if (s2 != null) { return s2; } } return null; } else { if (!rval.member(lval)) { return null; } } } return this.enabled(acts, s0, s1); } // The following case added by LL on 13 Nov 2009 to handle subexpression names. case OPCODE_nop: { return this.enabled(args[0], acts, c, s0, s1); } default: { // We handle all the other builtin operators here. Value bval = this.eval(pred, c, s0, s1, EvalControl.Enabled); if (!(bval instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_EXPRESSION_IN_COMPUTING, new String[] { "ENABLED", "boolean", bval.toString(), pred.toString() }); } if (((BoolValue) bval).val) { return this.enabled(acts, s0, s1); } return null; } } } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } private final TLCState enabledUnchanged(SemanticNode expr, ActionItemList acts, Context c, TLCState s0, TLCState s1) { if (this.callStack != null) this.callStack.push(expr); try { SymbolNode var = this.getVar(expr, c, true); if (var != null) { // a state variable, e.g. UNCHANGED var1 UniqueString varName = var.getName(); Value v0 = this.eval(expr, c, s0, s1, EvalControl.Enabled); Value v1 = s1.lookup(varName); if (v1 == null) { s1 = s1.bind(var, v0, expr); return this.enabled(acts, s0, s1); } if (v1.equals(v0)) { return this.enabled(acts, s0, s1); } MP.printWarning(EC.TLC_UNCHANGED_VARIABLE_CHANGED, new String[]{varName.toString() , expr.toString()}); return null; } if (expr instanceof OpApplNode) { OpApplNode expr1 = (OpApplNode)expr; ExprOrOpArgNode[] args = expr1.getArgs(); int alen = args.length; SymbolNode opNode = expr1.getOperator(); UniqueString opName = opNode.getName(); int opcode = BuiltInOPs.getOpCode(opName); if (opcode == OPCODE_tup) { // a tuple, e.g. UNCHANGED <<var1, var2>> if (alen != 0) { ActionItemList acts1 = acts; for (int i = 1; i < alen; i++) { acts1 = acts1.cons(args[i], c, ActionItemList.UNCHANGED); } return this.enabledUnchanged(args[0], acts1, c, s0, s1); } return this.enabled(acts, s0, s1); } if (opcode == 0 && alen == 0) { // a 0-arity operator: Object val = this.lookup(opNode, c, false); if (val instanceof LazyValue) { LazyValue lv = (LazyValue)val; return this.enabledUnchanged(lv.expr, acts, lv.con, s0, s1); } else if (val instanceof OpDefNode) { return this.enabledUnchanged(((OpDefNode)val).getBody(), acts, c, s0, s1); } else if (val == null) { Assert.fail("In computing ENABLED, TLC found the undefined identifier\n" + opName + " in an UNCHANGED expression at\n" + expr); } return this.enabled(acts, s0, s1); } } final Value v0 = this.eval(expr, c, s0, TLCState.Empty, EvalControl.Enabled); // We are in ENABLED and primed but why pass only primed? This appears to // be the only place where we call eval from the ENABLED scope without // additionally passing EvalControl.Enabled. Not passing Enabled allows a // cached LazyValue could be used (see comments above on line 1384). // The current scope is a nested UNCHANGED in an ENABLED and evaluation is set // to primed. However, UNCHANGED e equals e' = e , so anything primed in e // which is rejected by SANY's level checking. A perfectly valid spec - where // e is not primed - but that also causes this code path to be taken is 23 below: // VARIABLE t // op(var) == var // Next == /\ (ENABLED (UNCHANGED op(t))) // /\ (t'= t) // Spec == (t = 0) /\ [][Next]_t // However, spec 23 causes the call to this.eval(...) below to throw an // EvalException either with EvalControl.Primed. The exception's message is // "In evaluation, the identifier t is either undefined or not an operator." // indicating that this code path is buggy. // If this bug is ever fixed to make TLC accept spec 23, EvalControl.Primed // should likely be rewritten to EvalControl.setPrimed(EvalControl.Enabled) // to disable reusage of LazyValues on line ~1384 above. final Value v1 = this.eval(expr, c, s1, TLCState.Empty, EvalControl.Primed); if (!v0.equals(v1)) { return null; } return this.enabled(acts, s0, s1); } catch (TLCRuntimeException | EvalException e) { // see tlc2.tool.Tool.getInitStates(SemanticNode, ActionItemList, Context, TLCState, IStateFunctor) if (this.callStack != null) { this.callStack.freeze(); } throw e; } finally { if (this.callStack != null) { this.callStack.pop(); } } } /* This method determines if the action predicate is valid in (s0, s1). */ public final boolean isValid(Action act, TLCState s0, TLCState s1) { Value val = this.eval(act.pred, act.con, s0, s1, EvalControl.Clear); if (!(val instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", act.pred.toString()}); } return ((BoolValue)val).val; } /* Returns true iff the predicate is valid in the state. */ public final boolean isValid(Action act, TLCState state) { return this.isValid(act, state, TLCState.Empty); } /* Returns true iff the predicate is valid in the state. */ public final boolean isValid(Action act) { return this.isValid(act, TLCState.Empty, TLCState.Empty); } public final boolean isValid(ExprNode expr) { Value val = this.eval(expr, Context.Empty, TLCState.Empty); if (!(val instanceof BoolValue)) { Assert.fail(EC.TLC_EXPECTED_VALUE, new String[]{"boolean", expr.toString()}); } return ((BoolValue)val).val; } /* Reconstruct the initial state whose fingerprint is fp. */ public final TLCStateInfo getState(final long fp) { class InitStateSelectorFunctor implements IStateFunctor { private final long fp; public TLCState state; public InitStateSelectorFunctor(long fp) { this.fp = fp; } @Override public Object addElement(TLCState state) { if (state == null) { return null; } else if (this.state != null) { // Always return the first match found. Do not let later matches override // this.state. This is in line with the original implementation that called // getInitStates(). return null; } else if (fp == state.fingerPrint()) { this.state = state; // TODO Stop generation of initial states preemptively. E.g. make the caller of // addElement check for a special return value such as this (the functor). } return null; } } // Registry a selector that extract out of the (possibly) large set of initial // states the one identified by fp. The functor pattern has the advantage // compared to this.getInitStates(), that it kind of streams the initial states // to the functor whereas getInitStates() stores _all_ init states in a set // which is traversed afterwards. This is also consistent with // ModelChecker#DoInitFunctor. Using the functor pattern for the processing of // init states in ModelChecker#doInit but calling getInitStates() here results // in a bug during error trace generation when the set of initial states is too // large for getInitStates(). Earlier TLC would have refused to run the model // during ModelChecker#doInit. final InitStateSelectorFunctor functor = new InitStateSelectorFunctor(fp); this.getInitStates(functor); if (functor.state != null) { final String info = "<Initial predicate>"; final TLCStateInfo tlcStateInfo = new TLCStateInfo(functor.state, info, 1, fp); return tlcStateInfo; } return null; } /** * Reconstruct the next state of state s whose fingerprint is fp. * * @return Returns the TLCState wrapped in TLCStateInfo. TLCStateInfo stores * the stateNumber (relative to the given sinfo) and a pointer to * the predecessor. */ public final TLCStateInfo getState(long fp, TLCStateInfo sinfo) { final TLCStateInfo tlcStateInfo = getState(fp, sinfo.state); if (tlcStateInfo == null) { throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT); } tlcStateInfo.stateNumber = sinfo.stateNumber + 1; tlcStateInfo.predecessorState = sinfo; tlcStateInfo.fp = fp; return tlcStateInfo; } /* Reconstruct the next state of state s whose fingerprint is fp. */ public final TLCStateInfo getState(long fp, TLCState s) { IdThread.setCurrentState(s); for (int i = 0; i < this.actions.length; i++) { Action curAction = this.actions[i]; StateVec nextStates = this.getNextStates(curAction, s); for (int j = 0; j < nextStates.size(); j++) { TLCState state = nextStates.elementAt(j); long nfp = state.fingerPrint(); if (fp == nfp) { return new TLCStateInfo(state, curAction.getLocation()); } } } return null; } /* Reconstruct the info for s1. */ public final TLCStateInfo getState(TLCState s1, TLCState s) { IdThread.setCurrentState(s); for (int i = 0; i < this.actions.length; i++) { Action curAction = this.actions[i]; StateVec nextStates = this.getNextStates(curAction, s); for (int j = 0; j < nextStates.size(); j++) { TLCState state = nextStates.elementAt(j); if (s1.equals(state)) { return new TLCStateInfo(state, curAction.getLocation()); } } } return null; } /* Return the set of all permutations under the symmetry assumption. */ public final MVPerm[] getSymmetryPerms() { final String name = this.config.getSymmetry(); if (name.length() == 0) { return null; } final Object symm = this.defns.get(name); if (symm == null) { Assert.fail(EC.TLC_CONFIG_SPECIFIED_NOT_DEFINED, new String[] { "symmetry function", name}); } if (!(symm instanceof OpDefNode)) { Assert.fail("The symmetry function " + name + " must specify a set of permutations."); } // This calls tlc2.module.TLC.Permutations(Value) and returns a Value of |fcns| // = n! where n is the capacity of the symmetry set. final Value fcns = this.eval(((OpDefNode)symm).getBody(), Context.Empty, TLCState.Empty); if (!(fcns instanceof Enumerable)) { Assert.fail("The symmetry operator must specify a set of functions."); } return MVPerm.permutationSubgroup((Enumerable) fcns); } public final boolean hasSymmetry() { if (this.config == null) { return false; } final String name = this.config.getSymmetry(); return name.length() > 0; } public final Context getFcnContext(FcnLambdaValue fcn, ExprOrOpArgNode[] args, Context c, TLCState s0, TLCState s1, final int control) { Context fcon = fcn.con; int plen = fcn.params.length(); FormalParamNode[][] formals = fcn.params.formals; Value[] domains = fcn.params.domains; boolean[] isTuples = fcn.params.isTuples; Value argVal = this.eval(args[1], c, s0, s1, control); if (plen == 1) { if (!domains[0].member(argVal)) { Assert.fail("In applying the function\n" + Value.ppr(fcn.toString()) + ",\nthe first argument is:\n" + Value.ppr(argVal.toString()) + "which is not in its domain.\n" + args[0]); } if (isTuples[0]) { FormalParamNode[] ids = formals[0]; TupleValue tv = argVal.toTuple(); if (tv == null || argVal.size() != ids.length) { Assert.fail("In applying the function\n" + Value.ppr(this.toString()) + ",\nthe argument is:\n" + Value.ppr(argVal.toString()) + "which does not match its formal parameter.\n" + args[0]); } Value[] elems = tv.elems; for (int i = 0; i < ids.length; i++) { fcon = fcon.cons(ids[i], elems[i]); } } else { fcon = fcon.cons(formals[0][0], argVal); } } else { TupleValue tv = argVal.toTuple(); if (tv == null) { Assert.fail("Attempted to apply a function to an argument not in its" + " domain.\n" + args[0]); } int argn = 0; Value[] elems = tv.elems; for (int i = 0; i < formals.length; i++) { FormalParamNode[] ids = formals[i]; Value domain = domains[i]; if (isTuples[i]) { if (!domain.member(elems[argn])) { Assert.fail("In applying the function\n" + Value.ppr(fcn.toString()) + ",\nthe argument number " + (argn+1) + " is:\n" + Value.ppr(elems[argn].toString()) + "\nwhich is not in its domain.\n" + args[0]); } TupleValue tv1 = elems[argn++].toTuple(); if (tv1 == null || tv1.size() != ids.length) { Assert.fail("In applying the function\n" + Value.ppr(fcn.toString()) + ",\nthe argument number " + argn + " is:\n" + Value.ppr(elems[argn-1].toString()) + "which does not match its formal parameter.\n" + args[0]); } Value[] avals = tv1.elems; for (int j = 0; j < ids.length; j++) { fcon = fcon.cons(ids[j], avals[j]); } } else { for (int j = 0; j < ids.length; j++) { if (!domain.member(elems[argn])) { Assert.fail("In applying the function\n" + Value.ppr(fcn.toString()) + ",\nthe argument number " + (argn+1) + " is:\n" + Value.ppr(elems[argn].toString()) + "which is not in its domain.\n" + args[0]); } fcon = fcon.cons(ids[j], elems[argn++]); } } } } return fcon; } /* A context enumerator for an operator application. */ public final ContextEnumerator contexts(OpApplNode appl, Context c, TLCState s0, TLCState s1, final int control) { FormalParamNode[][] formals = appl.getBdedQuantSymbolLists(); boolean[] isTuples = appl.isBdedQuantATuple(); ExprNode[] domains = appl.getBdedQuantBounds(); int flen = formals.length; int alen = 0; for (int i = 0; i < flen; i++) { alen += (isTuples[i]) ? 1 : formals[i].length; } Object[] vars = new Object[alen]; ValueEnumeration[] enums = new ValueEnumeration[alen]; int idx = 0; for (int i = 0; i < flen; i++) { Value boundSet = this.eval(domains[i], c, s0, s1, control); if (!(boundSet instanceof Enumerable)) { Assert.fail("TLC encountered a non-enumerable quantifier bound\n" + Value.ppr(boundSet.toString()) + ".\n" + domains[i]); } FormalParamNode[] farg = formals[i]; if (isTuples[i]) { vars[idx] = farg; enums[idx++] = ((Enumerable)boundSet).elements(); } else { for (int j = 0; j < farg.length; j++) { vars[idx] = farg[j]; enums[idx++] = ((Enumerable)boundSet).elements(); } } } return new ContextEnumerator(vars, enums, c); } private void processConstantDefns() { ModuleNode[] mods = this.moduleTbl.getModuleNodes(); for (int i = 0; i < mods.length; i++) { if ( (! mods[i].isInstantiated()) || ( (mods[i].getConstantDecls().length == 0) && (mods[i].getVariableDecls().length == 0) ) ) { this.processConstantDefns(mods[i]); } } } private void processConstantDefns(ModuleNode mod) { // run for constant definitions OpDeclNode[] consts = mod.getConstantDecls(); for (int i = 0; i < consts.length; i++) { Object val = consts[i].getToolObject(TLCGlobals.ToolId); if (val != null && val instanceof Value) { ((Value)val).deepNormalize(); // System.err.println(consts[i].getName() + ": " + val); } // The following else clause was added by LL on 17 March 2012. else if (val != null && val instanceof OpDefNode) { OpDefNode opDef = (OpDefNode) val; // The following check logically belongs in Spec.processSpec, but it's not there. // So, LL just added it here. This error cannot occur when running TLC from // the Toolbox. Assert.check(opDef.getArity() == consts[i].getArity(), EC.TLC_CONFIG_WRONG_SUBSTITUTION_NUMBER_OF_ARGS, new String[] {consts[i].getName().toString(), opDef.getName().toString()}); if (opDef.getArity() == 0) { try { Value defVal = this.eval(opDef.getBody(), Context.Empty, TLCState.Empty); defVal.deepNormalize(); consts[i].setToolObject(TLCGlobals.ToolId, defVal); } catch (Assert.TLCRuntimeException e) { Assert.fail(EC.TLC_CONFIG_SUBSTITUTION_NON_CONSTANT, new String[] { consts[i].getName().toString(), opDef.getName().toString() }); } } } } // run for constant operator definitions OpDefNode[] opDefs = mod.getOpDefs(); for (int i = 0; i < opDefs.length; i++) { OpDefNode opDef = opDefs[i]; // The following variable evaluate and its value added by LL on 24 July 2013 // to prevent pre-evaluation of a definition from an EXTENDS of a module that // is also instantiated. ModuleNode moduleNode = opDef.getOriginallyDefinedInModuleNode() ; boolean evaluate = (moduleNode == null) || (! moduleNode.isInstantiated()) || ( (moduleNode.getConstantDecls().length == 0) && (moduleNode.getVariableDecls().length == 0) ) ; if (evaluate && opDef.getArity() == 0) { Object realDef = this.lookup(opDef, Context.Empty, false); if (realDef instanceof OpDefNode) { opDef = (OpDefNode)realDef; if (this.getLevelBound(opDef.getBody(), Context.Empty) == 0) { try { UniqueString opName = opDef.getName(); // System.err.println(opName); Value val = this.eval(opDef.getBody(), Context.Empty, TLCState.Empty); val.deepNormalize(); // System.err.println(opName + ": " + val); opDef.setToolObject(TLCGlobals.ToolId, val); Object def = this.defns.get(opName); if (def == opDef) { this.defns.put(opName, val); } } catch (Throwable e) { // Assert.printStack(e); } } } } } // run for all inner modules ModuleNode[] imods = mod.getInnerModules(); for (int i = 0; i < imods.length; i++) { this.processConstantDefns(imods[i]); } } }
/* This file is generated by bindings/java.py */ package org.hyperdex.client; import java.util.List; import java.util.Map; import java.util.HashMap; public class Client { static { System.loadLibrary("hyperdex-client-java"); initialize(); } private long ptr = 0; private Map<Long, Operation> ops = null; public Client(String host, Integer port) { _create(host, port.intValue()); this.ops = new HashMap<Long, Operation>(); } public Client(String host, int port) { _create(host, port); this.ops = new HashMap<Long, Operation>(); } protected void finalize() throws Throwable { try { destroy(); } finally { super.finalize(); } } public synchronized void destroy() { if (ptr != 0) { _destroy(); ptr = 0; } } /* utilities */ public Operation loop() throws HyperDexClientException { long ret = inner_loop(); Operation o = ops.get(ret); if (o != null) { o.callback(); } return o; } /* cached IDs */ private static native void initialize(); private static native void terminate(); /* ctor/dtor */ private native void _create(String host, int port); private native void _destroy(); /* utilities */ private native long inner_loop() throws HyperDexClientException; private void add_op(long l, Operation op) { ops.put(l, op); } private void remove_op(long l) { ops.remove(l); } /* operations */ public native Deferred async_get(String spacename, Object key) throws HyperDexClientException; public Map<String, Object> get(String spacename, Object key) throws HyperDexClientException { return (Map<String, Object>) async_get(spacename, key).waitForIt(); } public native Deferred async_get_partial(String spacename, Object key, List<String> attributenames) throws HyperDexClientException; public Map<String, Object> get_partial(String spacename, Object key, List<String> attributenames) throws HyperDexClientException { return (Map<String, Object>) async_get_partial(spacename, key, attributenames).waitForIt(); } public native Deferred async_put(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean put(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_put(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_put(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_put(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_put(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_put_if_not_exist(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean put_if_not_exist(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_put_if_not_exist(spacename, key, attributes).waitForIt(); } public native Deferred async_del(String spacename, Object key) throws HyperDexClientException; public Boolean del(String spacename, Object key) throws HyperDexClientException { return (Boolean) async_del(spacename, key).waitForIt(); } public native Deferred async_cond_del(String spacename, Object key, Map<String, Object> predicates) throws HyperDexClientException; public Boolean cond_del(String spacename, Object key, Map<String, Object> predicates) throws HyperDexClientException { return (Boolean) async_cond_del(spacename, key, predicates).waitForIt(); } public native Deferred async_atomic_add(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_add(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_add(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_add(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_sub(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_sub(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_sub(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_sub(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_sub(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_sub(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_mul(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_mul(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_mul(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_mul(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_mul(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_mul(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_div(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_div(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_div(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_div(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_div(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_div(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_mod(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_mod(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_mod(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_mod(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_mod(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_mod(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_and(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_and(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_and(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_and(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_and(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_and(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_or(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_or(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_or(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_or(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_or(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_or(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_atomic_xor(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean atomic_xor(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_atomic_xor(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_atomic_xor(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_atomic_xor(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_atomic_xor(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_string_prepend(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean string_prepend(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_string_prepend(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_string_prepend(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_string_prepend(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_string_prepend(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_string_append(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean string_append(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_string_append(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_string_append(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_string_append(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_string_append(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_list_lpush(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean list_lpush(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_list_lpush(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_list_lpush(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_list_lpush(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_list_lpush(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_list_rpush(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean list_rpush(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_list_rpush(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_list_rpush(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_list_rpush(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_list_rpush(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_set_add(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean set_add(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_set_add(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_set_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_set_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_set_add(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_set_remove(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean set_remove(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_set_remove(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_set_remove(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_set_remove(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_set_remove(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_set_intersect(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean set_intersect(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_set_intersect(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_set_intersect(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_set_intersect(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_set_intersect(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_set_union(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean set_union(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_set_union(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_set_union(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_set_union(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_set_union(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_map_add(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_add(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_add(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_add(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_remove(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException; public Boolean map_remove(String spacename, Object key, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_map_remove(spacename, key, attributes).waitForIt(); } public native Deferred async_cond_map_remove(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException; public Boolean cond_map_remove(String spacename, Object key, Map<String, Object> predicates, Map<String, Object> attributes) throws HyperDexClientException { return (Boolean) async_cond_map_remove(spacename, key, predicates, attributes).waitForIt(); } public native Deferred async_document_atomic_add(String spacename, Object key, Object docattributes) throws HyperDexClientException; public Boolean document_atomic_add(String spacename, Object key, Object docattributes) throws HyperDexClientException { return (Boolean) async_document_atomic_add(spacename, key, docattributes).waitForIt(); } public native Deferred async_map_atomic_add(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_add(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_add(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_add(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_add(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_sub(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_sub(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_sub(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_sub(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_sub(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_sub(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_mul(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_mul(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_mul(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_mul(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_mul(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_mul(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_div(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_div(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_div(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_div(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_div(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_div(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_mod(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_mod(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_mod(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_mod(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_mod(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_mod(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_and(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_and(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_and(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_and(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_and(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_and(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_or(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_or(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_or(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_or(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_or(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_or(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_atomic_xor(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_atomic_xor(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_atomic_xor(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_atomic_xor(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_atomic_xor(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_atomic_xor(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_string_prepend(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_string_prepend(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_string_prepend(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_string_prepend(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_string_prepend(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_string_prepend(spacename, key, predicates, mapattributes).waitForIt(); } public native Deferred async_map_string_append(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean map_string_append(String spacename, Object key, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_map_string_append(spacename, key, mapattributes).waitForIt(); } public native Deferred async_cond_map_string_append(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException; public Boolean cond_map_string_append(String spacename, Object key, Map<String, Object> predicates, Map<String, Map<Object, Object>> mapattributes) throws HyperDexClientException { return (Boolean) async_cond_map_string_append(spacename, key, predicates, mapattributes).waitForIt(); } public native Iterator search(String spacename, Map<String, Object> predicates); public native Deferred async_search_describe(String spacename, Map<String, Object> predicates) throws HyperDexClientException; public String search_describe(String spacename, Map<String, Object> predicates) throws HyperDexClientException { return (String) async_search_describe(spacename, predicates).waitForIt(); } public native Iterator sorted_search(String spacename, Map<String, Object> predicates, String sortby, int limit, boolean maxmin); public native Deferred async_group_del(String spacename, Map<String, Object> predicates) throws HyperDexClientException; public Boolean group_del(String spacename, Map<String, Object> predicates) throws HyperDexClientException { return (Boolean) async_group_del(spacename, predicates).waitForIt(); } public native Deferred async_count(String spacename, Map<String, Object> predicates) throws HyperDexClientException; public Long count(String spacename, Map<String, Object> predicates) throws HyperDexClientException { return (Long) async_count(spacename, predicates).waitForIt(); } }
package org.jpmml.xjc; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.LinkedHashSet; import java.util.Set; import com.sun.codemodel.ClassType; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JEnumConstant; import com.sun.codemodel.JExpr; import com.sun.codemodel.JFieldRef; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JJavaName; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JPackage; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.istack.build.NameConverter; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.Plugin; import com.sun.tools.xjc.model.CPropertyInfo; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.FieldOutline; import com.sun.tools.xjc.outline.Outline; import com.sun.tools.xjc.util.CodeModelClassFactory; import org.xml.sax.ErrorHandler; public class VisitorPlugin extends Plugin { @Override public String getOptionName(){ return "Xvisitor"; } @Override public String getUsage(){ return null; } @Override public boolean run(Outline outline, Options options, ErrorHandler errorHandler){ JCodeModel codeModel = outline.getCodeModel(); CodeModelClassFactory clazzFactory = outline.getClassFactory(); JClass objectClazz = codeModel.ref(Object.class); JClass pmmlObjectClazz = codeModel.ref("org.dmg.pmml.PMMLObject"); JClass visitableInterface = codeModel.ref("org.dmg.pmml.Visitable"); JClass dequeClazz = codeModel.ref(Deque.class); JClass dequeImplementationClazz = codeModel.ref(ArrayDeque.class); JPackage pmmlPackage = pmmlObjectClazz._package(); JDefinedClass visitorActionClazz = clazzFactory.createClass(pmmlPackage, JMod.PUBLIC, "VisitorAction", null, ClassType.ENUM); JEnumConstant continueAction = visitorActionClazz.enumConstant("CONTINUE"); JEnumConstant skipAction = visitorActionClazz.enumConstant("SKIP"); JEnumConstant terminateAction = visitorActionClazz.enumConstant("TERMINATE"); JDefinedClass visitorInterface = clazzFactory.createClass(pmmlPackage, JMod.PUBLIC, "Visitor", null, ClassType.INTERFACE); JMethod visitorApplyTo = visitorInterface.method(JMod.PUBLIC, void.class, "applyTo"); visitorApplyTo.javadoc().append("@see Visitable#accept(Visitor)"); visitorApplyTo.param(visitableInterface, "visitable"); JMethod visitorPushParent = visitorInterface.method(JMod.PUBLIC, void.class, "pushParent"); visitorPushParent.param(pmmlObjectClazz, "object"); JMethod visitorPopParent = visitorInterface.method(JMod.PUBLIC, pmmlObjectClazz, "popParent"); JMethod visitorGetParents = visitorInterface.method(JMod.PUBLIC, dequeClazz.narrow(pmmlObjectClazz), "getParents"); JPackage visitorPackage = codeModel._package("org.jpmml.model.visitors"); JDefinedClass abstractVisitorClazz = clazzFactory.createClass(visitorPackage, JMod.ABSTRACT | JMod.PUBLIC, "AbstractVisitor", null, ClassType.CLASS)._implements(visitorInterface); JFieldVar abstractVisitorParents = abstractVisitorClazz.field(JMod.PRIVATE, dequeClazz.narrow(pmmlObjectClazz), "parents", JExpr._new(dequeImplementationClazz.narrow(pmmlObjectClazz))); JFieldRef abstractVisitorParentsRef = JExpr.refthis(abstractVisitorParents.name()); JMethod abstractVisitorApplyTo = abstractVisitorClazz.method(JMod.PUBLIC, void.class, "applyTo"); abstractVisitorApplyTo.annotate(Override.class); JVar visitable = abstractVisitorApplyTo.param(visitableInterface, "visitable"); abstractVisitorApplyTo.body().add(JExpr.invoke(visitable, "accept").arg(JExpr._this())); JMethod abstractVisitorPushParent = abstractVisitorClazz.method(JMod.PUBLIC, void.class, "pushParent"); abstractVisitorPushParent.annotate(Override.class); JVar parent = abstractVisitorPushParent.param(pmmlObjectClazz, "parent"); abstractVisitorPushParent.body().add(abstractVisitorParentsRef.invoke("addFirst").arg(parent)); JMethod abstractVisitorPopParent = abstractVisitorClazz.method(JMod.PUBLIC, pmmlObjectClazz, "popParent"); abstractVisitorPopParent.annotate(Override.class); abstractVisitorPopParent.body()._return(abstractVisitorParentsRef.invoke("removeFirst")); JMethod abstractVisitorGetParents = abstractVisitorClazz.method(JMod.PUBLIC, dequeClazz.narrow(pmmlObjectClazz), "getParents"); abstractVisitorGetParents.annotate(Override.class); abstractVisitorGetParents.body()._return(abstractVisitorParentsRef); JDefinedClass abstractSimpleVisitorClazz = clazzFactory.createClass(visitorPackage, JMod.ABSTRACT | JMod.PUBLIC, "AbstractSimpleVisitor", null, ClassType.CLASS)._extends(abstractVisitorClazz); JMethod abstractSimpleVisitorDefaultVisit = abstractSimpleVisitorClazz.method(JMod.ABSTRACT | JMod.PUBLIC, visitorActionClazz, "visit"); abstractSimpleVisitorDefaultVisit.param(pmmlObjectClazz, "object"); Set<String> traversableTypes = new LinkedHashSet<>(); Collection<? extends ClassOutline> clazzes = outline.getClasses(); for(ClassOutline clazz : clazzes){ JDefinedClass beanClazz = clazz.implClass; traversableTypes.add(beanClazz.name()); JClass beanSuperClazz = beanClazz._extends(); traversableTypes.add(beanSuperClazz.name()); } // End for for(ClassOutline clazz : clazzes){ JDefinedClass beanClazz = clazz.implClass; String parameterName = NameConverter.standard.toVariableName(beanClazz.name()); if(!JJavaName.isJavaIdentifier(parameterName)){ parameterName = ("_" + parameterName); } JMethod visitorVisit = visitorInterface.method(JMod.PUBLIC, visitorActionClazz, "visit"); visitorVisit.param(beanClazz, parameterName); JMethod abstractVisitorVisit = abstractVisitorClazz.method(JMod.PUBLIC, visitorActionClazz, "visit"); abstractVisitorVisit.annotate(Override.class); abstractVisitorVisit.param(beanClazz, parameterName); abstractVisitorVisit.body()._return(continueAction); JClass beanSuperClazz = beanClazz._extends(); JMethod abstractSimpleVisitorVisit = abstractSimpleVisitorClazz.method(JMod.PUBLIC, visitorActionClazz, "visit"); abstractSimpleVisitorVisit.annotate(Override.class); abstractSimpleVisitorVisit.param(beanClazz, parameterName); abstractSimpleVisitorVisit.body()._return(JExpr.invoke(abstractSimpleVisitorDefaultVisit).arg(JExpr.cast(beanSuperClazz, JExpr.ref(parameterName)))); JMethod beanAccept = beanClazz.method(JMod.PUBLIC, visitorActionClazz, "accept"); beanAccept.annotate(Override.class); JVar visitorParameter = beanAccept.param(visitorInterface, "visitor"); JBlock body = beanAccept.body(); JVar status = body.decl(visitorActionClazz, "status", JExpr.invoke(visitorParameter, "visit").arg(JExpr._this())); int pushPos = body.pos(); JInvocation traverseVarargs = null; FieldOutline[] fields = clazz.getDeclaredFields(); for(FieldOutline field : fields){ CPropertyInfo propertyInfo = field.getPropertyInfo(); JType fieldType = field.getRawType(); JMethod getterMethod = beanClazz.getMethod("get" + propertyInfo.getName(true), new JType[0]); // Collection of values if(propertyInfo.isCollection()){ JType fieldElementType = CodeModelUtil.getElementType(fieldType); if(traversableTypes.contains(fieldElementType.name()) || objectClazz.equals(fieldElementType)){ JMethod hasElementsMethod = beanClazz.getMethod("has" + propertyInfo.getName(true), new JType[0]); body._if((status.eq(continueAction)).cand(JExpr.invoke(hasElementsMethod)))._then().assign(status, pmmlObjectClazz.staticInvoke(traversableTypes.contains(fieldElementType.name()) ? "traverse" : "traverseMixed").arg(visitorParameter).arg(JExpr.invoke(getterMethod))); traverseVarargs = null; } } else // Simple value { if(traversableTypes.contains(fieldType.name())){ if(traverseVarargs == null){ traverseVarargs = pmmlObjectClazz.staticInvoke("traverse").arg(visitorParameter); body._if(status.eq(continueAction))._then().assign(status, traverseVarargs); } traverseVarargs.arg(JExpr.invoke(getterMethod)); } } } int popPos = body.pos(); body._if(status.eq(terminateAction))._then()._return(terminateAction); body._return(continueAction); if(pushPos < popPos){ body.pos(popPos); body.add(JExpr.invoke(visitorParameter, visitorPopParent)); body.pos(pushPos); body.add(JExpr.invoke(visitorParameter, visitorPushParent).arg(JExpr._this())); } } return true; } }
package com4j; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Wraps COM VARIANT data structure. * * This class allows you to deal with the raw VARIANT type in case you need it, * but in general you should bind <tt>VARIANT*</tt> to {@link Object} or * {@link Holder<Object>} for more natural Java binding. * * TODO: more documentation. * * <h2>Notes</h2> * <ol> * <li> * Calling methods defined on {@link Number} changes the variant * type (i.e., similar to a cast in Java) accordingly and returns its value. * </ol> * * <p> * Method names that end with '0' are native methods. * * @author Kohsuke Kawaguchi (kk@kohsuke.org) */ public final class Variant extends Number { /** * The memory image of the VARIANT. */ final ByteBuffer image = ByteBuffer.allocateDirect(16); public static enum Type implements ComEnum { VT_EMPTY(0), VT_NULL(1), VT_I2(2), VT_I4(3), VT_R4(4), VT_R8(5), VT_CY(6), VT_DATE(7), VT_BSTR(8), VT_DISPATCH(9), VT_ERROR(10), VT_BOOL(11), VT_VARIANT(12), VT_UNKNOWN(13), VT_DECIMAL(14), VT_RECORD(36), VT_I1(16), VT_UI1(17), VT_UI2(18), VT_UI4(19), VT_INT(22), VT_UINT(23), // VT_ARRAY(), // VT_BYREF ; private final int value; private Type( int value ) { this.value = value; } public int comEnumValue() { return value; } } /** * Creates an empty {@link Variant}. */ public Variant() { image.order(ByteOrder.LITTLE_ENDIAN); } /** * Creates an empty {@link Variant} with the given type. */ public Variant(Type type) { this(); setType(type); } /** * Empties the current contents. * * <p> * Sometimes a {@link Variant} holds things like interface pointers or * arrays, which require some clean up actions. Therefore, when you * want to reuse an existing {@link Variant} that may hold a value, * you should first clear it. */ public void clear() { clear0(image); } /** * Makes sure the variant is cleared before GC-ed. */ public void finalize() { clear(); } /** * Calls <tt>VariantClear</tt> method. */ private static native void clear0( ByteBuffer image ); /** * Sets the type of the variant. */ public void setType( Type t ) { image.putLong(0,t.comEnumValue()); } /** * Gets the type of the variant. */ public Type getType() { return EnumDictionary.get(Type.class).constant((int)image.getLong(0)); } private static native void changeType0( int type, ByteBuffer image ); /** * Changes the variant type to the specified one. */ private void changeType( Type t ) { changeType0( t.comEnumValue(), image ); } public int intValue() { changeType(Type.VT_I4); return image.getInt(8); } public long longValue() { // VARIANT doesn't seem to support 64bit int return intValue(); } public float floatValue() { changeType(Type.VT_R4); return image.getFloat(8); } public double doubleValue() { changeType(Type.VT_R8); return image.getDouble(8); } public <T extends Com4jObject> T object( Class<T> type ) { changeType(Type.VT_UNKNOWN); int ptr = image.getInt(8); if(ptr==0) return null; Native.addRef(ptr); return Wrapper.create(type,ptr); } public static final Variant MISSING = new Variant(Type.VT_ERROR); }
package raptor.connector.fics; import static raptor.chess.util.GameUtils.getChessPieceCharacter; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.PreferenceNode; import org.eclipse.jface.preference.PreferencePage; import raptor.Raptor; import raptor.RaptorWindowItem; import raptor.action.RaptorAction; import raptor.action.RaptorAction.Category; import raptor.action.RaptorAction.RaptorActionContainer; import raptor.chat.ChatEvent; import raptor.chat.ChatType; import raptor.chess.Game; import raptor.chess.GameConstants; import raptor.connector.fics.pref.FicsPage; import raptor.connector.fics.pref.FicsRightClickChannelMenu; import raptor.connector.fics.pref.FicsRightClickGamesMenu; import raptor.connector.fics.pref.FicsRightClickPersonMenu; import raptor.connector.ics.IcsConnector; import raptor.connector.ics.IcsConnectorContext; import raptor.connector.ics.IcsParser; import raptor.connector.ics.IcsUtils; import raptor.connector.ics.dialog.IcsLoginDialog; import raptor.pref.PreferenceKeys; import raptor.pref.page.ActionContainerPage; import raptor.pref.page.ConnectorMessageBlockPage; import raptor.pref.page.ConnectorQuadrantsPage; import raptor.service.ActionScriptService; import raptor.service.ThreadService; import raptor.swt.BugButtonsWindowItem; import raptor.swt.FicsSeekDialog; import raptor.swt.RegularExpressionEditorDialog; import raptor.swt.SWTUtils; import raptor.swt.chat.ChatConsole; import raptor.swt.chat.ChatConsoleWindowItem; import raptor.swt.chat.ChatUtils; import raptor.swt.chat.controller.RegExController; import raptor.swt.chess.controller.PlayingMouseAction; import raptor.util.RaptorLogger; import raptor.util.RaptorStringTokenizer; public class FicsConnector extends IcsConnector implements PreferenceKeys, GameConstants { private static final RaptorLogger LOG = RaptorLogger .getLog(FicsConnector.class); protected static final String[][] PROBLEM_ACTIONS = { { "Tactics", "tell puzzlebot gettactics" }, { "Mate", "tell puzzlebot getmate" }, { "separator", "separator" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(PAWN, true) + " vs " + getChessPieceCharacter(KING, false), "tell endgamebot play kpk" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(PAWN, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(PAWN, false), "tell endgamebot play kpkp" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(PAWN, true) + getChessPieceCharacter(PAWN, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(PAWN, false), "tell endgamebot play kppkp" }, { "separator", "separator" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(QUEEN, true) + " vs " + getChessPieceCharacter(KING, false), "tell endgamebot play kqk" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(QUEEN, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(ROOK, false), "tell endgamebot play kqkr" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(QUEEN, true) + getChessPieceCharacter(PAWN, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(QUEEN, false), "tell endgamebot play kqpkq" }, { "separator", "separator" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(ROOK, true) + " vs " + getChessPieceCharacter(KING, false), "tell endgamebot play krk" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(ROOK, true) + getChessPieceCharacter(PAWN, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(ROOK, false), "tell endgamebot play krpk" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(ROOK, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(PAWN, false), "tell endgamebot play krkp" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(ROOK, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(KNIGHT, false), "tell endgamebot play krkn" }, { "separator", "separator" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(BISHOP, true) + getChessPieceCharacter(BISHOP, true) + " vs " + getChessPieceCharacter(KING, false), "tell endgamebot play kbbk" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(BISHOP, true) + getChessPieceCharacter(KNIGHT, true) + " vs " + getChessPieceCharacter(KING, false), "tell endgamebot play kbnk" }, { getChessPieceCharacter(KING, true) + getChessPieceCharacter(KNIGHT, true) + getChessPieceCharacter(KNIGHT, true) + " vs " + getChessPieceCharacter(KING, false) + getChessPieceCharacter(PAWN, false), "tell endgamebot play knnkp" } }; protected MenuManager ficsMenu; protected Action autoConnectAction; protected Action connectAction; protected List<Action> onlyEnabledOnConnectActions = new ArrayList<Action>( 20); /** * Raptor allows connecting to fics twice with different profiles. Override * short name and change it to fics2 so users can distinguish the two. * * This is also used to handle partnerships in simul bug. * * If this is fics 1 it will contain the fics2 connector. If this is fics2 * it will be null. */ protected FicsConnector fics2 = null; protected Object extendedCensorSync = new Object(); protected static final String EXTENDED_CENSOR_FILE_NAME = Raptor.USER_RAPTOR_HOME_PATH + "/fics/extendedCensor.txt"; /** * This is used by the fics2 connector. You need a reference back to fics1 * to handle simul bug partnerships. If this is fics2 it will contain the * fics1 connector, otherwise its null. */ protected FicsConnector fics1 = null; protected GameBotService gameBotService = new GameBotService(this); protected GameBotParser gameBotParser = new GameBotParser(this); protected String partnerOnConnect; public FicsConnector() { this(new IcsConnectorContext(new IcsParser(false))); } public FicsConnector(IcsConnectorContext context) { super(context); context.getParser().setConnector(this); initFics2(); createMenuActions(); } protected String getInitialTimesealString() { return "TIMESTAMP|iv|OpenSeal|"; // if (getPreferences().getBoolean(FICS_TIMESEAL_IS_TIMESEAL_2)) { // return "TIMESEAL2|OpenSeal|OpenSeal|"; // } else { // return "TIMESTAMP|iv|OpenSeal|"; } public GameBotService getGameBotService() { return gameBotService; } public void setGameBotService(GameBotService gameBotService) { this.gameBotService = gameBotService; } @Override public void disconnect() { synchronized (this) { if (isConnected()) { try { for (Game game : getGameService().getAllActiveGames()) { if (game.isInState(Game.PLAYING_STATE)) { onResign(game); } } } catch (Throwable t) { LOG.warn("Error trying to resign game:", t); } super.disconnect(); connectAction.setEnabled(true); if (autoConnectAction != null) { autoConnectAction.setEnabled(true); } for (Action action : onlyEnabledOnConnectActions) { action.setEnabled(false); } } } } @Override public void dispose() { super.dispose(); if (fics2 != null) { fics2.dispose(); fics2 = null; } // stop circular refs for easier gc. fics1 = null; } /** * Returns the menu manager for this connector. */ public MenuManager getMenuManager() { return ficsMenu; } /** * Return the preference node to add to the root preference dialog. This * preference node will show up with the connectors first name. You can add * secondary nodes by implementing getSecondaryPreferenceNodes. These nodes * will show up below the root node. */ public PreferencePage getRootPreferencePage() { return new FicsPage(); } /** * Returns an array of the secondary preference nodes. */ public PreferenceNode[] getSecondaryPreferenceNodes() { return new PreferenceNode[] { new PreferenceNode( "ficsMenuActions", new ActionContainerPage( "Fics Menu URLs", "\tOn this page you can configure the actions shown in the Fics Links " + "menu. You can add new actions on the Action Scripts Page.", RaptorActionContainer.FicsMenu)), new PreferenceNode("fics", new ConnectorMessageBlockPage("fics")), new PreferenceNode("fics", new FicsRightClickChannelMenu()), new PreferenceNode("fics", new FicsRightClickGamesMenu()), new PreferenceNode("fics", new FicsRightClickPersonMenu()), new PreferenceNode("fics", new ConnectorQuadrantsPage("fics")), new PreferenceNode("fics", new ConnectorQuadrantsPage("fics2")), }; } /** * Returns true if isConnected and a user is playing a game. */ public boolean isLoggedInUserPlayingAGame() { boolean result = false; if (isConnected()) { for (Game game : getGameService().getAllActiveGames()) { if (game.isInState(Game.PLAYING_STATE)) { result = true; break; } } } // Check the fics2 connection. if (!result && fics2 != null && fics2.isConnected()) { for (Game game : getGameService().getAllActiveGames()) { if (game.isInState(Game.PLAYING_STATE)) { result = true; break; } } } return result; } /** * This method is overridden to support simul bughouse. */ @Override public void publishEvent(final ChatEvent event) { if (chatService != null) { // Could have been disposed. // handle gamebot tab messages. GameBotParseResults gameBotResults = gameBotParser.parse(event); if (gameBotResults != null) { if (!gameBotResults.isIncomplete()) { if (gameBotResults.isPlayerInDb()) { gameBotService.fireGameBotPageArrived( gameBotResults.getRows(), gameBotResults.hasNextPage); } else { gameBotService .fireGameBotPlayerNotInDb(gameBotResults.playerName); } } return; } if (event.getType() == ChatType.PARTNERSHIP_CREATED) { if (fics2 != null && isConnected() && fics2.isConnected() && StringUtils.equalsIgnoreCase( IcsUtils.stripTitles(event.getSource()).trim(), fics2.getUserName())) { // here we are in fics1 where a partnership was created. if (LOG.isDebugEnabled()) { LOG.debug("Created simul bughouse partnership with " + fics2.getUserName()); } isSimulBugConnector = true; simulBugPartnerName = event.getSource(); fics2.isSimulBugConnector = true; fics2.simulBugPartnerName = getUserName(); } else if (fics2 == null && fics1 != null && fics1.isConnected() && isConnected() && StringUtils.equalsIgnoreCase( IcsUtils.stripTitles(event.getSource()).trim(), fics1.getUserName())) { // here we are in fics2 when a partnership was created. if (LOG.isDebugEnabled()) { LOG.debug("Created simul bughouse partnership with " + fics1.getUserName()); } isSimulBugConnector = true; simulBugPartnerName = event.getSource(); fics1.isSimulBugConnector = true; fics1.simulBugPartnerName = getUserName(); } if (!isSimulBugConnector && getPreferences() .getBoolean( PreferenceKeys.FICS_SHOW_BUGBUTTONS_ON_PARTNERSHIP)) { SWTUtils.openBugButtonsWindowItem(this); } if (getPreferences().getBoolean( PreferenceKeys.BUGHOUSE_SHOW_BUGWHO_ON_PARTNERSHIP)) { SWTUtils.openBugWhoWindowItem(this); } } else if (event.getType() == ChatType.PARTNERSHIP_DESTROYED) { isSimulBugConnector = false; simulBugPartnerName = null; if (LOG.isDebugEnabled()) { LOG.debug("Partnership destroyed. Resetting partnership information."); } // clear out the fics2 or fics1 depending on what this is. if (fics2 != null) { fics2.isSimulBugConnector = false; fics2.simulBugPartnerName = null; } if (fics1 != null) { fics1.isSimulBugConnector = false; fics1.simulBugPartnerName = null; } // Remove bug buttons if up displayed you have no partner. RaptorWindowItem[] windowItems = Raptor.getInstance() .getWindow().getWindowItems(BugButtonsWindowItem.class); for (RaptorWindowItem item : windowItems) { BugButtonsWindowItem bugButtonsItem = (BugButtonsWindowItem) item; if (bugButtonsItem.getConnector() == this) { Raptor.getInstance().getWindow() .disposeRaptorWindowItem(bugButtonsItem); } } } super.publishEvent(event); } } protected void addProblemActions(MenuManager problemMenu) { for (int i = 0; i < PROBLEM_ACTIONS.length; i++) { if (PROBLEM_ACTIONS[i][0].equals("separator")) { problemMenu.add(new Separator()); } else { final String action = PROBLEM_ACTIONS[i][1]; Action problemAction = new Action(PROBLEM_ACTIONS[i][0]) { public void run() { sendMessage(action); } }; problemAction.setEnabled(false); onlyEnabledOnConnectActions.add(problemAction); problemMenu.add(problemAction); } } } @Override protected void connect(final String profileName) { synchronized (this) { if (!isConnected()) { for (Action action : onlyEnabledOnConnectActions) { action.setEnabled(true); } connectAction.setEnabled(false); if (autoConnectAction != null) { autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); autoConnectAction.setEnabled(true); } super.connect(profileName); if (isConnecting) { if (getPreferences().getBoolean( context.getPreferencePrefix() + "show-bugbuttons-on-connect")) { Raptor.getInstance() .getWindow() .addRaptorWindowItem( new BugButtonsWindowItem(this)); } } } } } /** * Creates the connectionsMenu and all of the actions associated with it. */ protected void createMenuActions() { ficsMenu = new MenuManager("&Fics"); connectAction = new Action("&Connect") { @Override public void run() { IcsLoginDialog dialog = new IcsLoginDialog( context.getPreferencePrefix(), "Fics Login"); dialog.open(); getPreferences().setValue( context.getPreferencePrefix() + "profile", dialog.getSelectedProfile()); autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); getPreferences().save(); if (dialog.wasLoginPressed()) { connect(); } } }; Action disconnectAction = new Action("&Disconnect") { @Override public void run() { disconnect(); } }; Action reconnectAction = new Action("&Reconnect") { @Override public void run() { disconnect(); // Sleep half a second for everything to adjust. try { Thread.sleep(500); } catch (InterruptedException ie) { } connect(currentProfileName); } }; Action seekTableAction = new Action("&Seeks") { @Override public void run() { SWTUtils.openSeekTableWindowItem(FicsConnector.this); } }; Action bugwhoAction = new Action("Bug Who") { @Override public void run() { SWTUtils.openBugWhoWindowItem(FicsConnector.this); } }; Action bugbuttonsAction = new Action("Bug &Buttons") { @Override public void run() { SWTUtils.openBugButtonsWindowItem(FicsConnector.this); } }; Action gamesAction = new Action("&Games") { @Override public void run() { SWTUtils.openGamesWindowItem(FicsConnector.this); } }; Action regexTabAction = new Action("&Regular Expression") { @Override public void run() { RegularExpressionEditorDialog regExDialog = new RegularExpressionEditorDialog( Raptor.getInstance().getWindow().getShell(), getShortName() + " Regular Expression Dialog", "Enter the regular expression below:"); String regEx = regExDialog.open(); if (StringUtils.isNotBlank(regEx)) { final RegExController controller = new RegExController( FicsConnector.this, regEx); ChatConsoleWindowItem chatConsoleWindowItem = new ChatConsoleWindowItem( controller); Raptor.getInstance().getWindow() .addRaptorWindowItem(chatConsoleWindowItem, false); ChatUtils .appendPreviousChatsToController((ChatConsole) chatConsoleWindowItem .getControl()); } } }; autoConnectAction = new Action("Toggle Auto &Login", IAction.AS_CHECK_BOX) { @Override public void run() { getPreferences().setValue( context.getPreferencePrefix() + "auto-connect", isChecked()); getPreferences().save(); } }; fics2.connectAction = new Action("&Connect") { @Override public void run() { IcsLoginDialog dialog = new IcsLoginDialog( context.getPreferencePrefix(), "Fics Simultaneous Login"); if (isConnected()) { dialog.setShowingSimulBug(true); } dialog.setShowingAutoLogin(false); dialog.open(); if (autoConnectAction != null) { autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); } if (dialog.wasLoginPressed()) { fics2.connect(dialog.getSelectedProfile()); if (dialog.isSimulBugLogin()) { // This is used to automatically send the partner // message after login. // When the partnership is received a // PARTNERSHIP_CREATED message // is fired and the names of the bug partners are set in // that see the overridden publishEvent for how that // works. fics2.partnerOnConnect = userName; // Force bug-open to get the partnership message. sendMessage("set bugopen on"); } } } }; Action fics2DisconnectAction = new Action("&Disconnect") { @Override public void run() { fics2.disconnect(); } }; Action fics2ReconnectAction = new Action("&Reconnect") { @Override public void run() { fics2.disconnect(); // Sleep half a second for everything to adjust. try { Thread.sleep(500); } catch (InterruptedException ie) { } fics2.connect(fics2.currentProfileName); } }; Action fics2SeekTableAction = new Action("&Seeks") { @Override public void run() { SWTUtils.openSeekTableWindowItem(fics2); } }; Action fics2GamesAction = new Action("&Games") { @Override public void run() { SWTUtils.openGamesWindowItem(fics2); } }; Action fics2bugwhoAction = new Action("Bug &Who") { @Override public void run() { SWTUtils.openBugWhoWindowItem(fics2); } }; Action fics2RegexTabAction = new Action("&Regular Expression") { @Override public void run() { RegularExpressionEditorDialog regExDialog = new RegularExpressionEditorDialog( Raptor.getInstance().getWindow().getShell(), getShortName() + " Regular Expression Dialog", "Enter the regular expression below:"); String regEx = regExDialog.open(); if (StringUtils.isNotBlank(regEx)) { final RegExController controller = new RegExController( fics2, regEx); ChatConsoleWindowItem chatConsoleWindowItem = new ChatConsoleWindowItem( controller); Raptor.getInstance().getWindow() .addRaptorWindowItem(chatConsoleWindowItem, false); ChatUtils .appendPreviousChatsToController((ChatConsole) chatConsoleWindowItem .getControl()); } } }; Action fics2BugbuttonsAction = new Action("Bughouse &Buttons") { @Override public void run() { SWTUtils.openBugButtonsWindowItem(fics2); } }; Action showSeekDialogAction = new Action("Seek A Game") { public void run() { FicsSeekDialog dialog = new FicsSeekDialog(Raptor.getInstance() .getWindow().getShell()); String seek = dialog.open(); if (seek != null) { sendMessage(seek); } } }; MenuManager actions = new MenuManager("Actions"); RaptorAction[] scripts = ActionScriptService.getInstance().getActions( Category.IcsCommands); for (final RaptorAction raptorAction : scripts) { Action action = new Action(raptorAction.getName()) { public void run() { raptorAction.setConnectorSource(FicsConnector.this); raptorAction.run(); } }; action.setEnabled(false); action.setToolTipText(raptorAction.getDescription()); onlyEnabledOnConnectActions.add(action); actions.add(action); } connectAction.setEnabled(true); disconnectAction.setEnabled(false); reconnectAction.setEnabled(false); autoConnectAction.setEnabled(true); bugwhoAction.setEnabled(false); seekTableAction.setEnabled(false); regexTabAction.setEnabled(false); bugbuttonsAction.setEnabled(false); showSeekDialogAction.setEnabled(false); gamesAction.setEnabled(false); onlyEnabledOnConnectActions.add(bugwhoAction); onlyEnabledOnConnectActions.add(disconnectAction); onlyEnabledOnConnectActions.add(reconnectAction); onlyEnabledOnConnectActions.add(regexTabAction); onlyEnabledOnConnectActions.add(seekTableAction); onlyEnabledOnConnectActions.add(bugbuttonsAction); onlyEnabledOnConnectActions.add(showSeekDialogAction); onlyEnabledOnConnectActions.add(gamesAction); fics2.connectAction.setEnabled(true); fics2DisconnectAction.setEnabled(false); fics2ReconnectAction.setEnabled(false); fics2SeekTableAction.setEnabled(false); fics2bugwhoAction.setEnabled(false); fics2RegexTabAction.setEnabled(false); fics2BugbuttonsAction.setEnabled(false); fics2GamesAction.setEnabled(false); fics2.onlyEnabledOnConnectActions.add(fics2bugwhoAction); fics2.onlyEnabledOnConnectActions.add(fics2DisconnectAction); fics2.onlyEnabledOnConnectActions.add(fics2ReconnectAction); fics2.onlyEnabledOnConnectActions.add(fics2RegexTabAction); fics2.onlyEnabledOnConnectActions.add(fics2SeekTableAction); fics2.onlyEnabledOnConnectActions.add(fics2BugbuttonsAction); fics2.onlyEnabledOnConnectActions.add(fics2GamesAction); autoConnectAction.setChecked(getPreferences().getBoolean( context.getPreferencePrefix() + "auto-connect")); ficsMenu.add(connectAction); ficsMenu.add(disconnectAction); ficsMenu.add(reconnectAction); ficsMenu.add(autoConnectAction); MenuManager fics2Menu = new MenuManager( "&Another Simultaneous Connection"); MenuManager fics2TabsMenu = new MenuManager("&Tabs"); fics2Menu.add(fics2.connectAction); fics2Menu.add(fics2DisconnectAction); fics2Menu.add(fics2ReconnectAction); fics2Menu.add(new Separator()); fics2TabsMenu.add(fics2GamesAction); fics2TabsMenu.add(fics2SeekTableAction); fics2TabsMenu.add(new Separator()); fics2TabsMenu.add(fics2BugbuttonsAction); fics2TabsMenu.add(fics2bugwhoAction); fics2TabsMenu.add(new Separator()); fics2TabsMenu.add(fics2RegexTabAction); fics2Menu.add(fics2TabsMenu); ficsMenu.add(fics2Menu); ficsMenu.add(new Separator()); ficsMenu.add(actions); MenuManager tabsMenu = new MenuManager("&Tabs"); tabsMenu.add(gamesAction); tabsMenu.add(seekTableAction); tabsMenu.add(new Separator()); tabsMenu.add(bugbuttonsAction); tabsMenu.add(bugwhoAction); tabsMenu.add(new Separator()); tabsMenu.add(regexTabAction); ficsMenu.add(tabsMenu); MenuManager linksMenu = new MenuManager("&Links"); RaptorAction[] ficsMenuActions = ActionScriptService.getInstance() .getActions(RaptorActionContainer.FicsMenu); for (final RaptorAction raptorAction : ficsMenuActions) { if (raptorAction instanceof Separator) { linksMenu.add(new Separator()); } else { Action action = new Action(raptorAction.getName()) { @Override public void run() { raptorAction.setConnectorSource(FicsConnector.this); raptorAction.run(); } }; action.setToolTipText(raptorAction.getDescription()); linksMenu.add(action); } } ficsMenu.add(linksMenu); MenuManager problems = new MenuManager("&Puzzles"); addProblemActions(problems); ficsMenu.add(problems); ficsMenu.add(showSeekDialogAction); } protected void initFics2() { fics2 = new FicsConnector( new IcsConnectorContext(new IcsParser(false)) { @Override public String getDescription() { return "Free Internet Chess Server Another Simultaneous Connection"; } @Override public String getShortName() { return "fics2"; } }) { /** * Override not needed. */ @Override public PreferencePage getRootPreferencePage() { return null; } /** * Override not needed. */ @Override public PreferenceNode[] getSecondaryPreferenceNodes() { return null; } /** * Override not needed. */ @Override protected void createMenuActions() { } /** * Override the initFics2 method to do nothing to avoid the * recursion. */ @Override protected void initFics2() { } }; fics2.fics1 = this; } protected boolean isSmartMoveEnabled() { return isSmartMoveOption(getPreferences().getString( PreferenceKeys.PLAYING_CONTROLLER + PreferenceKeys.RIGHT_MOUSE_BUTTON_ACTION)) || isSmartMoveOption(getPreferences() .getString( PreferenceKeys.PLAYING_CONTROLLER + PreferenceKeys.LEFT_DOUBLE_CLICK_MOUSE_BUTTON_ACTION)) || isSmartMoveOption(getPreferences().getString( PreferenceKeys.PLAYING_CONTROLLER + PreferenceKeys.LEFT_MOUSE_BUTTON_ACTION)) || isSmartMoveOption(getPreferences().getString( PreferenceKeys.PLAYING_CONTROLLER + PreferenceKeys.MIDDLE_MOUSE_BUTTON_ACTION)) || isSmartMoveOption(getPreferences().getString( PreferenceKeys.PLAYING_CONTROLLER + PreferenceKeys.MISC1_MOUSE_BUTTON_ACTION)) || isSmartMoveOption(getPreferences().getString( PreferenceKeys.PLAYING_CONTROLLER + PreferenceKeys.MISC2_MOUSE_BUTTON_ACTION)); } protected boolean isSmartMoveOption(String option) { return option != null && (option.equals(PlayingMouseAction.SmartMove.toString()) || option.equals(PlayingMouseAction.RandomCapture .toString()) || option.equals(PlayingMouseAction.RandomMove .toString()) || option .equals(PlayingMouseAction.RandomRecapture.toString())); } protected void loadExtendedCensorList() { if (new File(EXTENDED_CENSOR_FILE_NAME).exists()) { if (LOG.isInfoEnabled()) { LOG.info("Loading " + EXTENDED_CENSOR_FILE_NAME); } synchronized (extendedCensorSync) { extendedCensorList.clear(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader( EXTENDED_CENSOR_FILE_NAME)); String currentLine = null; while ((currentLine = reader.readLine()) != null) { String user = currentLine.trim(); if (StringUtils.isNotBlank(user)) { extendedCensorList.add(IcsUtils.stripTitles(user) .toLowerCase()); } } } catch (Throwable t) { onError("Error reading " + EXTENDED_CENSOR_FILE_NAME, t); } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } } } else { if (LOG.isInfoEnabled()) { LOG.info("No extended censor list found."); } } } @Override protected void onSuccessfulLogin() { ThreadService.getInstance().run(new Runnable() { public void run() { isConnecting = false; fireConnected(); hasVetoPower = false; sendMessage("iset defprompt 1", true); sendMessage("iset gameinfo 1", true); sendMessage("iset ms 1", true); sendMessage("iset allresults 1", true); sendMessage("iset startpos 1", true); sendMessage("iset pendinfo 1", true); if (getPreferences().getBoolean( PreferenceKeys.FICS_NO_WRAP_ENABLED)) { sendMessage("iset nowrap 1", true); } sendMessage("iset smartmove " + (isSmartMoveEnabled() ? "1" : "0"), true); sendMessage( "iset premove " + (getPreferences().getBoolean( BOARD_PREMOVE_ENABLED) ? "1" : "0"), true); sendMessage("set interface " + getPreferences().getString(APP_NAME)); sendMessage("set style 12", true); sendMessage("set bell 0", true); sendMessage("set ptime 0", true); String loginScript = getPreferences().getString( FICS_LOGIN_SCRIPT); if (StringUtils.isNotBlank(loginScript)) { RaptorStringTokenizer tok = new RaptorStringTokenizer( loginScript, "\n\r", true); while (tok.hasMoreTokens()) { try { Thread.sleep(50L); } catch (InterruptedException ie) { } sendMessage(tok.nextToken().trim()); } } if (StringUtils.isNotBlank(partnerOnConnect)) { try { Thread.sleep(300); } catch (InterruptedException ie) { } sendMessage("set bugopen on"); sendMessage("partner " + partnerOnConnect); partnerOnConnect = null; } sendMessage("iset lock 1", true); hasVetoPower = true; } }); } protected void writeExtendedCensorList() { synchronized (extendedCensorSync) { FileWriter writer = null; try { writer = new FileWriter(EXTENDED_CENSOR_FILE_NAME, false); for (String user : extendedCensorList) { writer.write(user + "\n"); } writer.flush(); } catch (Throwable t) { onError("Error writing " + EXTENDED_CENSOR_FILE_NAME, t); } finally { if (writer != null) { try { writer.close(); } catch (Throwable t) { } } } } } }
package leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RadixSort { final private int RADIX = 10; // decimal public void sort(int[] arr) { // declare and initialize bucket[] List<List<Integer>> bucket = new ArrayList<List<Integer>>(RADIX); for (int i = 0; i < RADIX; i++) bucket.add(new ArrayList<Integer>()); // sort boolean maxLength = false; int tmp = -1; int placement = 1; // getting unit's place first while (!maxLength) { maxLength = true; // split input between lists for (int i : arr) { tmp = i / placement; // int indexToAddTo = tmp % RADIX; // try { // bucket.get(indexToAddTo).add(i); // } catch(Exception e) { // List<Integer> list = new ArrayList<Integer>(); // list.add(i); // bucket.add(indexToAddTo, list); bucket.get(tmp % RADIX).add(i); if (maxLength && tmp > 0) { maxLength = false; } } // empty lists into input array int a = 0; for (int b = 0; b < RADIX; b++) { for (int i : bucket.get(b)) { arr[a++] = i; } bucket.get(b).clear(); } // move to next digit placement *= RADIX; } } public static void main(String[] args) { int[] arr = {3, 4, 2, 5, 1, 7, 6, 9, 8, 0, 19, 81, 71, 65, 99, 191, 153, 132}; RadixSort Sorter = new RadixSort(); System.out.println("Array: " + Arrays.toString(arr)); Sorter.sort(arr); System.out.println("Array: " + Arrays.toString(arr)); } }
package soot; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.jimple.SpecialInvokeExpr; import soot.util.ArraySet; import soot.util.Chain; /** Represents the class hierarchy. It is closely linked to a Scene, * and must be recreated if the Scene changes. * * The general convention is that if a method name contains * "Including", then it returns the non-strict result; otherwise, * it does a strict query (e.g. strict superclass). */ public class Hierarchy { // These two maps are not filled in the constructor. private Map<SootClass, List<SootClass>> classToSubclasses; private Map<SootClass, List<SootClass>> interfaceToSubinterfaces; private Map<SootClass, List<SootClass>> interfaceToSuperinterfaces; private Map<SootClass, List<SootClass>> classToDirSubclasses; private Map<SootClass, List<SootClass>> interfaceToDirSubinterfaces; private Map<SootClass, List<SootClass>> interfaceToDirSuperinterfaces; // This holds the direct implementers. private Map<SootClass, List<SootClass>> interfaceToDirImplementers; int state; Scene sc; /** Constructs a hierarchy from the current scene. */ public Hierarchy() { this.sc = Scene.v(); state = sc.getState(); // Well, this used to be describable by 'Duh'. // Construct the subclasses hierarchy and the subinterfaces hierarchy. { Chain<SootClass> allClasses = sc.getClasses(); classToSubclasses = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToSubinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToSuperinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); classToDirSubclasses = new HashMap<SootClass, List<SootClass>> (allClasses.size() * 2 + 1, 0.7f); interfaceToDirSubinterfaces = new HashMap<SootClass, List<SootClass>> (allClasses.size() * 2 + 1, 0.7f); interfaceToDirSuperinterfaces = new HashMap<SootClass, List<SootClass>> (allClasses.size() * 2 + 1, 0.7f); interfaceToDirImplementers = new HashMap<SootClass, List<SootClass>> (allClasses.size() * 2 + 1, 0.7f); for (SootClass c : allClasses) { if( c.resolvingLevel() < SootClass.HIERARCHY ) continue; if (c.isInterface()) { interfaceToDirSubinterfaces.put(c, new ArrayList<SootClass>()); interfaceToDirSuperinterfaces.put(c, new ArrayList<SootClass>()); interfaceToDirImplementers.put(c, new ArrayList<SootClass>()); } else classToDirSubclasses.put(c, new ArrayList<SootClass>()); } for (SootClass c : allClasses) { if( c.resolvingLevel() < SootClass.HIERARCHY ) continue; if (c.hasSuperclass()) { if (c.isInterface()) { List<SootClass> l2 = interfaceToDirSuperinterfaces.get(c); for (SootClass i : c.getInterfaces()) { if( c.resolvingLevel() < SootClass.HIERARCHY ) continue; List<SootClass> l = interfaceToDirSubinterfaces.get(i); if (l != null) l.add(c); if (l2 != null) l2.add(i); } } else { List<SootClass> l = classToDirSubclasses.get(c.getSuperclass()); if (l != null) l.add(c); for (SootClass i : c.getInterfaces()) { if( c.resolvingLevel() < SootClass.HIERARCHY ) continue; l = interfaceToDirImplementers.get(i); if (l != null) l.add(c); } } } } // Fill the directImplementers lists with subclasses. for (SootClass c : allClasses) { if( c.resolvingLevel() < SootClass.HIERARCHY ) continue; if (c.isInterface()) { List<SootClass> imp = interfaceToDirImplementers.get(c); Set<SootClass> s = new ArraySet<SootClass>(); for (SootClass c0 : imp) { if( c.resolvingLevel() < SootClass.HIERARCHY ) continue; s.addAll(getSubclassesOfIncluding(c0)); } imp.clear(); imp.addAll(s); } } } } private void checkState() { if (state != sc.getState()) throw new ConcurrentModificationException("Scene changed for Hierarchy!"); } // This includes c in the list of subclasses. /** Returns a list of subclasses of c, including itself. */ public List<SootClass> getSubclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(getSubclassesOf(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of subclasses of c, excluding itself. */ public List<SootClass> getSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); // If already cached, return the value. if (classToSubclasses.get(c) != null) return classToSubclasses.get(c); // Otherwise, build up the hashmap. List<SootClass> l = new ArrayList<SootClass>(); for (SootClass cls : classToDirSubclasses.get(c)) { if( cls.resolvingLevel() < SootClass.HIERARCHY ) continue; l.addAll(getSubclassesOfIncluding(cls)); } l = Collections.unmodifiableList(l); classToSubclasses.put(c, l); return l; } /** Returns a list of superclasses of c, including itself. */ public List<SootClass> getSuperclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); List<SootClass> l = getSuperclassesOf(c); ArrayList<SootClass> al = new ArrayList<SootClass>(); al.add(c); al.addAll(l); return Collections.unmodifiableList(al); } /** Returns a list of strict superclasses of c, starting with c's parent. */ public List<SootClass> getSuperclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); ArrayList<SootClass> l = new ArrayList<SootClass>(); SootClass cl = c; while (cl.hasSuperclass()) { l.add(cl.getSuperclass()); cl = cl.getSuperclass(); } return Collections.unmodifiableList(l); } /** Returns a list of subinterfaces of c, including itself. */ public List<SootClass> getSubinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(getSubinterfacesOf(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of subinterfaces of c, excluding itself. */ public List<SootClass> getSubinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); // If already cached, return the value. if (interfaceToSubinterfaces.get(c) != null) return interfaceToSubinterfaces.get(c); // Otherwise, build up the hashmap. List<SootClass> l = new ArrayList<SootClass>(); for (SootClass si : interfaceToDirSubinterfaces.get(c)) { l.addAll(getSubinterfacesOfIncluding(si)); } interfaceToSubinterfaces.put(c, Collections.unmodifiableList(l)); return Collections.unmodifiableList(l); } /** Returns a list of superinterfaces of c, including itself. */ public List<SootClass> getSuperinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(getSuperinterfacesOf(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of superinterfaces of c, excluding itself. */ public List<SootClass> getSuperinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); // If already cached, return the value. List<SootClass> cached = interfaceToSuperinterfaces.get(c); if (cached != null) return cached; // Otherwise, build up the hashmap. List<SootClass> l = new ArrayList<SootClass>(); for (SootClass si : interfaceToDirSuperinterfaces.get(c)) { l.addAll(getSuperinterfacesOfIncluding(si)); } interfaceToSuperinterfaces.put(c, Collections.unmodifiableList(l)); return Collections.unmodifiableList(l); } /** Returns a list of direct superclasses of c, excluding c. */ public List<SootClass> getDirectSuperclassesOf(SootClass c) { throw new RuntimeException("Not implemented yet!"); } /** Returns a list of direct subclasses of c, excluding c. */ public List<SootClass> getDirectSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); return Collections.unmodifiableList(classToDirSubclasses.get(c)); } // This includes c in the list of subclasses. /** Returns a list of direct subclasses of c, including c. */ public List<SootClass> getDirectSubclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(classToDirSubclasses.get(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of direct superinterfaces of c. */ public List<SootClass> getDirectSuperinterfacesOf(SootClass c) { throw new RuntimeException("Not implemented yet!"); } /** Returns a list of direct subinterfaces of c. */ public List<SootClass> getDirectSubinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); return interfaceToDirSubinterfaces.get(c); } /** Returns a list of direct subinterfaces of c, including itself. */ public List<SootClass> getDirectSubinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(interfaceToDirSubinterfaces.get(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of direct implementers of c, excluding itself. */ public List<SootClass> getDirectImplementersOf(SootClass i) { i.checkLevel(SootClass.HIERARCHY); if (!i.isInterface()) throw new RuntimeException("interface needed; got "+i); checkState(); return Collections.unmodifiableList(interfaceToDirImplementers.get(i)); } /** Returns a list of implementers of c, excluding itself. */ public List<SootClass> getImplementersOf(SootClass i) { i.checkLevel(SootClass.HIERARCHY); if (!i.isInterface()) throw new RuntimeException("interface needed; got "+i); checkState(); ArraySet<SootClass> set = new ArraySet<SootClass>(); for (SootClass c : getSubinterfacesOfIncluding(i)) { set.addAll(getDirectImplementersOf(c)); } ArrayList<SootClass> l = new ArrayList<SootClass>(); l.addAll(set); return Collections.unmodifiableList(l); } /** * Returns true if child is a subclass of possibleParent. If one of the * known parent classes is phantom, we conservatively assume that the * current class might be a child. */ public boolean isClassSubclassOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); List<SootClass> parentClasses = getSuperclassesOf(child); if (parentClasses.contains(possibleParent)) return true; for (SootClass sc : parentClasses) if (sc.isPhantom()) return true; return false; } /** * Returns true if child is, or is a subclass of, possibleParent. If one of * the known parent classes is phantom, we conservatively assume that the * current class might be a child. */ public boolean isClassSubclassOfIncluding(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); List<SootClass> parentClasses = getSuperclassesOfIncluding(child); if (parentClasses.contains(possibleParent)) return true; for (SootClass sc : parentClasses) if (sc.isPhantom()) return true; return false; } /** Returns true if child is a direct subclass of possibleParent. */ public boolean isClassDirectSubclassOf(SootClass c, SootClass c2) { throw new RuntimeException("Not implemented yet!"); } /** Returns true if child is a superclass of possibleParent. */ public boolean isClassSuperclassOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSubclassesOf(parent).contains(possibleChild); } /** Returns true if parent is, or is a superclass of, possibleChild. */ public boolean isClassSuperclassOfIncluding(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSubclassesOfIncluding(parent).contains(possibleChild); } /** Returns true if child is a subinterface of possibleParent. */ public boolean isInterfaceSubinterfaceOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); return getSubinterfacesOf(possibleParent).contains(child); } /** Returns true if child is a direct subinterface of possibleParent. */ public boolean isInterfaceDirectSubinterfaceOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); return getDirectSubinterfacesOf(possibleParent).contains(child); } /** Returns true if parent is a superinterface of possibleChild. */ public boolean isInterfaceSuperinterfaceOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSuperinterfacesOf(possibleChild).contains(parent); } /** Returns true if parent is a direct superinterface of possibleChild. */ public boolean isInterfaceDirectSuperinterfaceOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getDirectSuperinterfacesOf(possibleChild).contains(parent); } /** Returns the most specific type which is an ancestor of both c1 and c2. */ public SootClass getLeastCommonSuperclassOf(SootClass c1, SootClass c2) { c1.checkLevel(SootClass.HIERARCHY); c2.checkLevel(SootClass.HIERARCHY); throw new RuntimeException("Not implemented yet!"); } // Questions about method invocation. /** Checks whether check is a visible class in view of the from class. * It assumes that protected and private classes do not exit. * If they exist and check is either protected or private, * the check will return false. */ public boolean isVisible( SootClass from, SootClass check) { if (check.isPublic()) return true; if( check.isProtected() || check.isPrivate()) return false; //package visibility return from.getJavaPackageName().equals( check.getJavaPackageName() ); } /** Returns true if the classmember m is visible from code in the class from. */ public boolean isVisible( SootClass from, ClassMember m ) { from.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); if (!isVisible(from, m.getDeclaringClass())) return false; if( m.isPublic() ) return true; if( m.isPrivate() ) { return from.equals( m.getDeclaringClass() ); } if( m.isProtected() ) { return isClassSubclassOfIncluding( from, m.getDeclaringClass() ); } // m is package return from.getJavaPackageName().equals( m.getDeclaringClass().getJavaPackageName() ); //|| isClassSubclassOfIncluding( from, m.getDeclaringClass() ); } /** * Given an object of actual type C (o = new C()), returns the method which * will be called on an o.f() invocation. */ public SootMethod resolveConcreteDispatch(SootClass concreteType, SootMethod m) { concreteType.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); if (concreteType.isInterface()) throw new RuntimeException("class needed!"); String methodSig = m.getSubSignature(); for (SootClass c : getSuperclassesOfIncluding(concreteType)) { SootMethod sm = c.getMethodUnsafe(methodSig); if (sm != null && isVisible(c, m)) { return sm; } } throw new RuntimeException( "could not resolve concrete dispatch!\nType: " + concreteType + "\nMethod: " + m); } /** Given a set of definite receiver types, returns a list of possible targets. */ public List<SootMethod> resolveConcreteDispatch(List<Type> classes, SootMethod m) { m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); Set<SootMethod> s = new ArraySet<SootMethod>(); for (Type cls : classes) { if (cls instanceof RefType) s.add(resolveConcreteDispatch(((RefType)cls).getSootClass(), m)); else if (cls instanceof ArrayType) { s.add(resolveConcreteDispatch((RefType.v("java.lang.Object")).getSootClass(), m)); } else throw new RuntimeException("Unable to resolve concrete dispatch of type "+ cls); } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } // what can get called for c & all its subclasses /** Given an abstract dispatch to an object of type c and a method m, gives * a list of possible receiver methods. */ public List<SootMethod> resolveAbstractDispatch(SootClass c, SootMethod m) { c.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); Set<SootMethod> s = new ArraySet<SootMethod>(); Collection<SootClass> classesIt; if (c.isInterface()) { Set<SootClass> classes = new HashSet<SootClass>(); for (SootClass sootClass : getImplementersOf(c)) { classes.addAll(getSubclassesOfIncluding(sootClass)); } classesIt = classes; } else classesIt = getSubclassesOfIncluding(c); for (SootClass cl : classesIt) { if( !Modifier.isAbstract( cl.getModifiers() ) ) { s.add(resolveConcreteDispatch(cl, m)); } } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } // what can get called if you have a set of possible receiver types /** Returns a list of possible targets for the given method and set of receiver types. */ public List<SootMethod> resolveAbstractDispatch(List<SootClass> classes, SootMethod m) { m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); Set<SootMethod> s = new ArraySet<SootMethod>(); for (SootClass sootClass : classes ) { s.addAll(resolveAbstractDispatch(sootClass, m)); } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } /** Returns the target for the given SpecialInvokeExpr. */ public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) { container.getDeclaringClass().checkLevel(SootClass.HIERARCHY); SootMethod target = ie.getMethod(); target.getDeclaringClass().checkLevel(SootClass.HIERARCHY); /* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the definition of invokespecial. */ if ("<init>".equals(target.getName()) || target.isPrivate()) return target; else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) return resolveConcreteDispatch(container.getDeclaringClass(), target); else return target; } }