answer
stringlengths
17
10.2M
package istc.bigdawg.migration; import static istc.bigdawg.utils.JdbcUtils.getColumnNames; import static istc.bigdawg.utils.JdbcUtils.getRows; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.HashSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.jgrapht.graph.DefaultEdge; import istc.bigdawg.catalog.CatalogViewer; import istc.bigdawg.exceptions.BigDawgCatalogException; import istc.bigdawg.exceptions.MigrationException; import istc.bigdawg.executor.plan.QueryExecutionPlan; import istc.bigdawg.islands.CrossIslandCastNode; import istc.bigdawg.islands.CrossIslandQueryNode; import istc.bigdawg.islands.CrossIslandQueryPlan; import istc.bigdawg.monitoring.Monitor; import istc.bigdawg.monitoring.MonitoringTask; import istc.bigdawg.network.NetworkIn; import istc.bigdawg.postgresql.PostgreSQLConnectionInfo; import istc.bigdawg.postgresql.PostgreSQLHandler; import istc.bigdawg.postgresql.PostgreSQLInstance; import istc.bigdawg.properties.BigDawgConfigProperties; import istc.bigdawg.query.QueryClient; import istc.bigdawg.signature.Signature; import istc.bigdawg.sstore.SStoreSQLConnectionInfo; import istc.bigdawg.sstore.SStoreSQLHandler; /** * @author Adam Dziedzic * * Mar 9, 2016 7:20:55 PM */ public class MigratorTask implements Runnable { private ExecutorService executor = null; private final ScheduledExecutorService scheduledExecutor; public static final int MIGRATION_RATE_SEC = 300; private static final String[] tables = {"sflavg_tbl"}; /** * Run the service for migrator - this network task accepts remote request * for data migration. */ public MigratorTask() { int numberOfThreads = 1; executor = Executors.newFixedThreadPool(numberOfThreads); executor.submit(new NetworkIn()); scheduledExecutor = Executors.newScheduledThreadPool(1); } /** * Close the migrator task. */ public void close() { if (executor != null) { if (!executor.isShutdown()) { executor.shutdownNow(); } } executor = null; } public static boolean serverListening(String host, int port) { Socket s = null; try { s = new Socket(host, port); return true; } catch (Exception e) { return false; } finally { if(s != null) { try { s.close(); } catch(Exception e){ ; } } } } @Override public void run() { final int sstoreDBID = BigDawgConfigProperties.INSTANCE.getSStoreDBID(); try { SStoreSQLConnectionInfo sstoreConnInfo = (SStoreSQLConnectionInfo) CatalogViewer.getConnectionInfo(sstoreDBID); String host = sstoreConnInfo.getHost(); int port = Integer.parseInt(sstoreConnInfo.getPort()); if (serverListening(host, port)) { cleanHistoricalData(); this.scheduledExecutor.scheduleAtFixedRate(new Task(tables), MIGRATION_RATE_SEC, MIGRATION_RATE_SEC, TimeUnit.SECONDS); } } catch (BigDawgCatalogException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void cleanHistoricalData() { // clean the historical data before any migration int psqlDBID = BigDawgConfigProperties.INSTANCE.getSeaflowDBID(); PostgreSQLConnectionInfo psqlConnInfo = null; Connection psqlConn = null; try { psqlConnInfo = (PostgreSQLConnectionInfo) CatalogViewer.getConnectionInfo(psqlDBID); psqlConn = PostgreSQLHandler.getConnection(psqlConnInfo); } catch (BigDawgCatalogException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (String table : tables) { String cmd = "DELETE FROM " + table + " WHERE s_cruise ilike 'CRUISE_7'"; try { PostgreSQLHandler.executeStatement(psqlConn, cmd); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Task implements Runnable { private static final int sstoreDBID = BigDawgConfigProperties.INSTANCE.getSStoreDBID(); private static final int psqlDBID = BigDawgConfigProperties.INSTANCE.getSeaflowDBID(); private static SStoreSQLConnectionInfo sstoreConnInfo; private static PostgreSQLConnectionInfo psqlConnInfo; private static String[] tables; Task(String[] tables){ this.tables = tables; try { this.sstoreConnInfo = (SStoreSQLConnectionInfo) CatalogViewer.getConnectionInfo(sstoreDBID); this.psqlConnInfo = (PostgreSQLConnectionInfo) CatalogViewer.getConnectionInfo(psqlDBID); } catch (BigDawgCatalogException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run(){ for (String table : tables) { String tableFrom = table; String tableTo = "psql_"+table; try { FromSStoreToPostgres migrator = new FromSStoreToPostgres(); migrator.migrate(sstoreConnInfo, tableFrom, psqlConnInfo, tableTo); } catch (MigrationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package jelly.repository; import jelly.config.EntityManagerCreator; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import java.io.Serializable; import java.util.List; public abstract class AbstractRepository<T extends Serializable> { private Class<T> clazz; protected final void setClazz(final Class<T> clazzToSet) { this.clazz = clazzToSet; } public T findOne(final long id) { EntityManager em = EntityManagerCreator.create(); try { return em.find(clazz, id); } finally { if (em.isOpen()) { em.close(); } } } public List<T> findAll(String name) { EntityManager em = EntityManagerCreator.create(); EntityTransaction transaction = em.getTransaction(); try { return em.createNamedQuery(name, clazz).getResultList(); } finally { if (em.isOpen()) { em.close(); } } } public void create(final T entity) { EntityManager em = EntityManagerCreator.create(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); em.persist(entity); transaction.commit(); } finally { if (transaction.isActive()) { transaction.rollback(); } if (em.isOpen()) { em.close(); } } } public T update(final T entity) { EntityManager em = EntityManagerCreator.create(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); em.merge(entity); transaction.commit(); } finally { if (transaction.isActive()) { transaction.rollback(); } if (em.isOpen()) { em.close(); } } return entity; } public void delete(final long entityId) { EntityManager em = EntityManagerCreator.create(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); em.remove(em.getReference(clazz, entityId)); transaction.commit(); } finally { if (transaction.isActive()) { transaction.rollback(); } if (em.isOpen()) { em.close(); } } } }
package jme3_ext_spatial_explorer; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.LinkedList; import java.util.List; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Side; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.ToolBar; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.control.cell.TextFieldTreeCell; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import org.controlsfx.control.MasterDetailPane; import org.controlsfx.control.PropertySheet; import org.controlsfx.control.PropertySheet.Item; import org.controlsfx.control.PropertySheet.Mode; import org.controlsfx.control.action.Action; import org.controlsfx.control.action.ActionUtils; import org.controlsfx.property.BeanProperty; import com.jme3.light.Light; import com.jme3.scene.Spatial; import com.jme3.scene.control.Control; public class Explorer0<Entry, Root extends Entry> { TreeItem<Entry> rootItem = new TreeItem<>(); Stage stage; PropertySheet details; ActionShowInPropertySheet<Entry> selectAction; public final ObjectProperty<Entry> selection = new SimpleObjectProperty<>(); /** List of actions on TreeItem via ContextMenu. actions should be registered before start(). */ public final List<Action> treeItemActions = new LinkedList<>(); public final List<Action> barActions = new LinkedList<>(); public Stage getStage() { return stage; } public PropertySheet getDetails() { return details; } MasterDetailPane makePane() { details = new PropertySheet(); details.setMode(Mode.CATEGORY); details.setModeSwitcherVisible(true); details.setSearchBoxVisible(true); selectAction = new ActionShowInPropertySheet<Entry>("test", null, details); TreeView<Entry> tree = new TreeView<>(rootItem); tree.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); tree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { try { if (newValue == null) { select(null); } else { select(newValue.getValue()); } } catch(Exception exc){ exc.printStackTrace(); } }); tree.setCellFactory((treeview) -> new MyTreeCell()); //StackPane root = new StackPane(); MasterDetailPane pane = new MasterDetailPane(); pane.setMasterNode(tree); pane.setDetailNode(details); pane.setDetailSide(Side.RIGHT); pane.setDividerPosition(0.5); pane.setShowDetailNode(true); return pane; } public ToolBar makeBar() { // ToolBar b = new ToolBar(); // for(Action a : barActions) { // javafx.scene.Node n = a.getGraphic(); // if (n == null) { // n = ActionUtils.createButton(a); // b.getItems().add(n); // return b; return ActionUtils.createToolBar(barActions, ActionUtils.ActionTextBehavior.SHOW); } public void start(Stage primaryStage, String title) { stop(); this.stage = primaryStage; primaryStage.setTitle(title); BorderPane root = new BorderPane(); root.setTop(makeBar()); root.setCenter(makePane()); primaryStage.setScene(new Scene(root, 600, 500)); primaryStage.show(); } public void stop() { if (stage != null) { updateRoot(null); stage.hide(); stage.close(); stage = null; } } public void updateRoot(Root value) { } public void select(Entry value) { selectAction.select(value); selection.set(value); } class MyTreeCell extends TextFieldTreeCell<Entry> { private ContextMenu menu = new ContextMenu(); public MyTreeCell() { editableProperty().set(false); setContextMenu(menu); for (Action a : treeItemActions) { MenuItem mi = ActionUtils.createMenuItem(a); //MenuItem mi = new MenuItem(a.getText()); mi.setOnAction((evt) -> { try { a.handle(new ActionEvent(getTreeItem(), evt.getTarget())); } catch(Exception exc) { exc.printStackTrace(); } }); menu.getItems().add(mi); } } } } class ActionShowInPropertySheet<T> extends Action { T bean; final PropertySheet propertySheet; public ActionShowInPropertySheet(String title, T bean, PropertySheet propertySheet) { super(title); setEventHandler(this::handleAction); this.bean = bean; this.propertySheet = propertySheet; } public void select(T v) { bean = v; handle(null); } private void handleAction(ActionEvent ae) { // retrieving bean properties may take some time // so we have to put it on separate thread to keep UI responsive Service<?> service = new Service<ObservableList<Item>>() { @Override protected Task<ObservableList<Item>> createTask() { return new Task<ObservableList<Item>>() { @Override protected ObservableList<Item> call() throws Exception { return bean == null ? null : getProperties(bean); } }; } }; service.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @SuppressWarnings("unchecked") @Override public void handle(WorkerStateEvent e) { ObservableList<Item> items = (ObservableList<Item>) e.getSource().getValue(); if (items != null) { propertySheet.getItems().setAll(items.filtered((v) -> v != null)); } else { propertySheet.getItems().clear(); } } }); service.start(); } /** * Given a JavaBean, this method will return a list of {@link Item} intances, * which may be directly placed inside a {@link PropertySheet} (via its * {@link PropertySheet#getItems() items list}. * * @param bean The JavaBean that should be introspected and be editable via * a {@link PropertySheet}. * @return A list of {@link Item} instances representing the properties of the * JavaBean. */ public static ObservableList<Item> getProperties(final Object bean) { ObservableList<Item> list = FXCollections.observableArrayList(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) { if (isProperty(p) && !p.isHidden()) { BeanProperty bp = new BeanProperty(bean, p); bp.setEditable(p.getWriteMethod() != null); list.add(bp); } } if (bean instanceof Spatial) { Spatial sp = (Spatial)bean; for(String key : sp.getUserDataKeys()) { list.add(new BasicItem("UserData", key, sp.getUserData(key))); } for(int i = 0; i < sp.getNumControls(); i++){ Control ctrl = sp.getControl(i); list.add(new BasicItem("Controls", ctrl.getClass().getSimpleName(), ctrl)); } for(int i = 0; i < sp.getLocalLightList().size(); i++){ Light light = sp.getLocalLightList().get(i); list.add(new BasicItem("Light", light.getClass().getSimpleName(), light)); } } } catch (IntrospectionException e) { e.printStackTrace(); } return list; } private static boolean isProperty(final PropertyDescriptor p) { //TODO Add more filtering return p.getReadMethod() != null ;//&& !p.getPropertyType().isAssignableFrom(EventHandler.class); } static class BasicItem implements PropertySheet.Item { public BasicItem(String category, String name, Object value) { super(); this.category = category; this.name = name; this.value = value; } final String category; final String name; final Object value; @Override public void setValue(Object value) { } @Override public Object getValue() { return value; } @Override public Class<?> getType() { return getValue().getClass(); } @Override public String getName() { return name; } @Override public String getDescription() { return null; } @Override public String getCategory() { return category; } /** {@inheritDoc} */ @Override public boolean isEditable() { return false; } } }
package mariculture.fishery.tile; import static mariculture.core.util.Fluids.getFluidID; import static mariculture.core.util.Fluids.getFluidStack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import mariculture.api.core.Environment.Salinity; import mariculture.api.core.MaricultureHandlers; import mariculture.api.fishery.FishTickEvent; import mariculture.api.fishery.Fishing; import mariculture.api.fishery.fish.FishSpecies; import mariculture.api.util.CachedCoords; import mariculture.core.config.FishMechanics; import mariculture.core.config.Machines.Ticks; import mariculture.core.gui.feature.FeatureEject.EjectSetting; import mariculture.core.gui.feature.FeatureNotifications.NotificationType; import mariculture.core.gui.feature.FeatureRedstone.RedstoneMode; import mariculture.core.helpers.FluidHelper; import mariculture.core.lib.MachineSpeeds; import mariculture.core.network.PacketHandler; import mariculture.core.network.PacketSyncFeeder; import mariculture.core.tile.base.TileMachineTank; import mariculture.core.util.IHasNotification; import mariculture.core.util.MCTranslate; import mariculture.fishery.Fish; import mariculture.fishery.FishFoodHandler; import mariculture.fishery.FishyHelper; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; import cofh.api.energy.IEnergyConnection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class TileFeeder extends TileMachineTank implements IHasNotification, IEnergyConnection { private static final int fluid = 3; public static final int male = 5; public static final int female = 6; public ArrayList<CachedCoords> coords = new ArrayList<CachedCoords>(); private int isInit = 50; private boolean isDay; private boolean swap = false; private int foodTick; private int tankSize; public Block tankBlock; //Fish Locations and animations public int mPos = 0; public int fPos = 0; public int mTicker = 0; public int fTicker = 0; public double mRot = 0F; public double fRot = 0F; public TileFeeder() { max = MachineSpeeds.getFeederSpeed(); inventory = new ItemStack[13]; output = new int[] { 7, 8, 9, 10, 11, 12 }; } @SideOnly(Side.CLIENT) public AxisAlignedBB getRenderBoundingBox() { return super.getRenderBoundingBox().expand(5D, 5D, 5D); } @Override public int getTankCapacity(int storage) { return 2 * tankSize * (storage + 1); } @Override public int[] getAccessibleSlotsFromSide(int var1) { return new int[] { male, female, 3, 7, 8, 9, 10, 11, 12 }; } @Override public boolean canInsertItem(int slot, ItemStack stack, int side) { if (slot == male) return inventory[male] == null && Fishing.fishHelper.isMale(stack); if (slot == female) return inventory[female] == null && Fishing.fishHelper.isFemale(stack); if (slot == fluid) return FluidHelper.isFluidOrEmpty(stack); return false; } @Override public boolean canExtractItem(int slot, ItemStack stack, int side) { return slot > female; } @Override public void setInventorySlotContents(int slot, ItemStack stack) { super.setInventorySlotContents(slot, stack); if (!worldObj.isRemote) { if (slot == male && Fishing.fishHelper.isMale(stack)) { updateTankSize(); } else if (slot == female) { PacketHandler.syncInventory(this, inventory); } } } //Updates the size of the tank private void updateTankSize() { int xP = 0, xN = 0, yP = 0, yN = 0, zP = 0, zN = 0; ItemStack male = inventory[this.male]; ItemStack female = inventory[this.female]; if (male != null) { xP = Fish.east.getDNA(male); xN = Fish.west.getDNA(male); yP = Fish.up.getDNA(male); yN = Fish.down.getDNA(male); zP = Fish.south.getDNA(male); zN = Fish.north.getDNA(male); } FishSpecies m = Fishing.fishHelper.getSpecies(inventory[this.male]); FishSpecies f = Fishing.fishHelper.getSpecies(inventory[this.female]); HashMap<Integer, Integer> count = new HashMap(); coords = new ArrayList<CachedCoords>(); if (m != null && f != null) { for (int x = -5 - xN; x <= 5 + xP; x++) { for (int z = -5 - zN; z <= 5 + zP; z++) { for (int y = -5 - yN; y <= 5 + yP; y++) { Block block = worldObj.getBlock(xCoord + x, yCoord + y, zCoord + z); if (m.isFluidValid(block) && f.isFluidValid(block)) { coords.add(new CachedCoords(xCoord + x, yCoord + y, zCoord + z)); int id = Block.getIdFromBlock(block); int amount = count.get(id) != null? count.get(id) + 1: 1; count.put(id, amount); } } } } } int highest_id = 0; int highest_amount = 0; for (Map.Entry<Integer, Integer> entry : count.entrySet()) { int value = entry.getValue(); if(value >= highest_amount) { highest_amount = value; highest_id = entry.getKey(); } } tankBlock = highest_id == 0? null: Block.getBlockById(highest_id); tankSize = coords.size(); updateUpgrades(); if (!worldObj.isRemote) { PacketHandler.syncInventory(this, inventory); PacketHandler.sendAround(new PacketSyncFeeder(xCoord, yCoord, zCoord, coords, tankBlock), this); } } //Processes fish public void process() { if (swap) { makeProduct(inventory[female]); } else { makeProduct(inventory[male]); } damageFish(inventory[female], true); damageFish(inventory[male], true); } private void fixFish(int slot) { ItemStack fish = inventory[slot]; if(fish != null && fish.hasTagCompound()) { FishSpecies species = Fishing.fishHelper.getSpecies(fish); FishSpecies secondary = Fishing.fishHelper.getSpecies(Fishing.fishHelper.getLowerDNA(Fish.species.getName(), fish)); if(!fish.stackTagCompound.hasKey(Fish.temperature.getName())) { Fish.temperature.addDNA(fish, species.getTemperatureTolerance()); Fish.temperature.addLowerDNA(fish, secondary.getTemperatureTolerance()); } if(!fish.stackTagCompound.hasKey(Fish.temperature.getName())) { Fish.temperature.addDNA(fish, species.getSalinityTolerance()); Fish.temperature.addDNA(fish, secondary.getSalinityTolerance()); } } inventory[slot] = fish; } //Damages Fish private void damageFish(ItemStack fish, boolean giveProduct) { FishSpecies species = Fishing.fishHelper.getSpecies(fish); if (species != null) { int gender = Fish.gender.getDNA(fish); if (gender == FishyHelper.FEMALE && MaricultureHandlers.upgrades.hasUpgrade("female", this)) return; if (gender == FishyHelper.MALE && MaricultureHandlers.upgrades.hasUpgrade("male", this)) return; int reduce = max - purity * 15; fish.stackTagCompound.setInteger("CurrentLife", fish.stackTagCompound.getInteger("CurrentLife") - reduce); if (fish.stackTagCompound.getInteger("CurrentLife") <= 0 || MaricultureHandlers.upgrades.hasUpgrade("debugKill", this)) { killFish(species, gender, giveProduct); } } } //Makes a Fish Product private void makeProduct(ItemStack fish) { FishSpecies species = Fishing.fishHelper.getSpecies(fish); if (species != null) { int gender = Fish.gender.getDNA(fish); if (!MinecraftForge.EVENT_BUS.post(new FishTickEvent(this, species, gender == 1))) { for (int i = 0; i < Fish.production.getDNA(fish); i++) { ItemStack product = species.getProduct(worldObj.rand); if (product != null) { helper.insertStack(product, output); } if (MaricultureHandlers.upgrades.hasUpgrade("female", this)) { int fertility = Math.max(1, (5500 - Fish.fertility.getDNA(fish)) / 50); if (worldObj.rand.nextInt(fertility) == 0) { generateEgg(); } } if (MaricultureHandlers.upgrades.hasUpgrade("male", this)) { product = species.getProduct(worldObj.rand); if (product != null) { helper.insertStack(product, output); } } } } } } //Kills a Fish private void killFish(FishSpecies species, int gender, boolean giveProduct) { if (giveProduct) { ItemStack raw = species.getRawForm(1); if (raw != null) { helper.insertStack(raw, output); } if (gender == FishyHelper.FEMALE) { generateEgg(); } } if (gender == FishyHelper.FEMALE) { decrStackSize(female, 1); } else if (gender == FishyHelper.MALE) { decrStackSize(male, 1); } } //Generates an egg private void generateEgg() { if (Fishing.fishHelper.getSpecies(inventory[male]) != null) { helper.insertStack(Fishing.fishHelper.generateEgg(inventory[male], inventory[female]), output); } } @Override public void updateEntity() { if (!worldObj.isRemote) { if (isInit <= 0 && isInit > -1000) { isInit = -1000; updateTankSize(); } else isInit } super.updateEntity(); } @Override public void update() { super.update(); if (canWork) { foodTick++; if (onTick(Ticks.EFFECT_TICK)) { if (swap) { doEffect(inventory[male]); swap = false; } else { doEffect(inventory[female]); swap = true; } } //Fish will eat every 25 seconds by default if (foodTick % (Ticks.FISH_FOOD_TICK * 20) == 0) { if (swap) { useFood(inventory[male]); } else { useFood(inventory[female]); } } if (Ticks.PICKUP_TICK >= 0 && onTick(Ticks.PICKUP_TICK)) { pickupFood(); } } } //Performs an effect on the world private void doEffect(ItemStack fish) { FishSpecies species = Fishing.fishHelper.getSpecies(fish); if (species != null) { if (!worldObj.isRemote) { species.affectWorld(worldObj, xCoord, yCoord, zCoord, coords); for (CachedCoords cord : coords) { List list = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, Blocks.stone.getCollisionBoundingBoxFromPool(worldObj, cord.x, cord.y, cord.z)); if (!list.isEmpty()) { for (Object i : list) { species.affectLiving((EntityLivingBase) i); } } } } } } //Uses fish food private void useFood(ItemStack fish) { int usage = 0; FishSpecies species = Fishing.fishHelper.getSpecies(fish); if (species != null) { usage = Fish.foodUsage.getDNA(fish); usage = usage == 0 && species.requiresFood() ? 1 : usage; } drain(ForgeDirection.DOWN, getFluidStack("fish_food", usage), true); } private void pickupFood() { for (CachedCoords coord : coords) { List list = worldObj.getEntitiesWithinAABB(EntityItem.class, Blocks.stone.getCollisionBoundingBoxFromPool(worldObj, coord.x, coord.y, coord.z)); if (!list.isEmpty()) { for (Object i : list) { EntityItem entity = (EntityItem) i; ItemStack item = entity.getEntityItem(); if (((entity.handleWaterMovement()) || entity.worldObj.provider.isHellWorld && entity.handleLavaMovement())) { item = addFishFood(item); if (item == null) { entity.setDead(); } } } } } } private ItemStack addFishFood(ItemStack stack) { if (FishFoodHandler.isFishFood(stack)) { int increase = FishFoodHandler.getValue(stack); int loop = stack.stackSize; for (int i = 0; i < loop; i++) { int fill = fill(ForgeDirection.UP, getFluidStack("fish_food", increase), false); if (fill > 0) { fill(ForgeDirection.UP, getFluidStack("fish_food", increase), true); stack.stackSize } } } if (stack.stackSize <= 0) { return null; } return stack; } @Override public boolean canWork() { if(FishMechanics.FIX_FISH) { fixFish(female); fixFish(male); } return RedstoneMode.canWork(this, mode) && hasMale() && hasFemale() && fishCanLive(inventory[male]) && fishCanLive(inventory[female]) && hasRoom(null); } //Returns whether we have a male fish private boolean hasMale() { return inventory[male] != null && Fishing.fishHelper.isMale(inventory[male]); } //Returns where there is a female fish private boolean hasFemale() { return inventory[female] != null && Fishing.fishHelper.isFemale(inventory[female]); } private boolean fishCanLive(ItemStack fish) { FishSpecies species = Fishing.fishHelper.getSpecies(fish); if (species != null) { if (MaricultureHandlers.upgrades.hasUpgrade("debugLive", this)) return true; else if (tank.getFluid() == null || tank.getFluid() != null && tank.getFluid().fluidID != getFluidID("fish_food")) return false; return tankSize >= Fish.tankSize.getDNA(fish) && species.isFluidValid(tankBlock) && Fishing.fishHelper.canLive(worldObj, xCoord, yCoord, zCoord, fish); } else return false; } @Override public boolean canConnectEnergy(ForgeDirection from) { for (int slot = 0; slot < 2; slot++) { if (inventory[slot] == null) { continue; } FishSpecies species = Fishing.fishHelper.getSpecies(inventory[slot]); if (species != null) return species.canConnectEnergy(from); } return false; } public int getLightValue() { int lM = 0, lF = 0; FishSpecies sMale = Fishing.fishHelper.getSpecies(inventory[male]); FishSpecies sFemale = Fishing.fishHelper.getSpecies(inventory[female]); if (sMale != null && sMale.getLightValue() > 0) { lM = sMale.getLightValue(); } if (sFemale != null && sFemale.getLightValue() > 0) { lF = sFemale.getLightValue(); } if (lM == 0) return lF; else if (lF == 0) return lM; else return (lM + lF) / 2; } //Gui Stuffs private boolean addToolTip(ArrayList<String> tooltip, String text) { tooltip.add(mariculture.lib.util.Text.RED + text); return false; } public Salinity getSalinity() { Salinity salt = MaricultureHandlers.environment.getSalinity(worldObj, xCoord, zCoord); int salinity = salt.ordinal() + MaricultureHandlers.upgrades.getData("salinity", this); if (salinity <= 0) { salinity = 0; } if (salinity > 2) { salinity = 2; } salt = Salinity.values()[salinity]; return salt; } public ArrayList<String> getTooltip(int slot, ArrayList<String> tooltip) { boolean noBad = true; ItemStack fish = inventory[slot]; if (fish != null && fish.hasTagCompound() && !Fishing.fishHelper.isEgg(fish) && fish.stackTagCompound.hasKey("SpeciesID")) { int currentLife = fish.stackTagCompound.getInteger("CurrentLife") / 20; if (!MaricultureHandlers.upgrades.hasUpgrade("debugLive", this)) { FishSpecies species = FishSpecies.species.get(Fish.species.getDNA(fish)); if (!MaricultureHandlers.upgrades.hasUpgrade("ethereal", this) && !species.isValidDimensionForWork(worldObj)) { noBad = addToolTip(tooltip, MCTranslate.translate("badWorld")); } int temperature = MaricultureHandlers.environment.getTemperature(worldObj, xCoord, yCoord, zCoord) + heat; int minTempAccepted = species.getTemperatureBase() - Fish.temperature.getDNA(fish); int maxTempAccepted = species.getTemperatureBase() + Fish.temperature.getDNA(fish); if (temperature < minTempAccepted) { int required = minTempAccepted - temperature; noBad = addToolTip(tooltip, MCTranslate.translate("tooCold")); noBad = addToolTip(tooltip, " +" + required + mariculture.lib.util.Text.DEGREES); } else if (temperature > maxTempAccepted) { int required = temperature - maxTempAccepted; noBad = addToolTip(tooltip, MCTranslate.translate("tooHot")); noBad = addToolTip(tooltip, " -" + required + mariculture.lib.util.Text.DEGREES); } boolean match = false; Salinity salt = getSalinity(); int minSaltAccepted = Math.max(0, species.getSalinityBase().ordinal() - Fish.salinity.getDNA(fish)); int maxSaltAccepted = Math.min(2, species.getSalinityBase().ordinal() + Fish.salinity.getDNA(fish)); if (salt.ordinal() >= minSaltAccepted && salt.ordinal() <= maxSaltAccepted) { match = true; } if (!match) { for (int s = minSaltAccepted; s <= maxSaltAccepted; s++) { noBad = addToolTip(tooltip, MCTranslate.translate("salinity.prefers") + " " + MCTranslate.translate("salinity." + Salinity.values()[s].toString().toLowerCase())); } } int size = Fish.tankSize.getDNA(fish); if (tankSize < size || !species.isFluidValid(tankBlock)) { noBad = addToolTip(tooltip, MCTranslate.translate("notAdvanced")); //Work out the block types accepted String block1 = species.getWater1().getLocalizedName(); String block2 = species.getWater2().getLocalizedName(); String text = block1.equals(block2)? block1: block1 + " / " + block2; noBad = addToolTip(tooltip, " +" + (size - tankSize) + " " + text); } if (!species.canWorkAtThisTime(isDay)) { noBad = addToolTip(tooltip, MCTranslate.translate("badTime")); } if (!hasMale() || !hasFemale()) { noBad = addToolTip(tooltip, MCTranslate.translate("missingMate")); } if (tank.getFluidAmount() < 1 || tank.getFluid().fluidID != getFluidID("fish_food")) { noBad = addToolTip(tooltip, MCTranslate.translate("noFood")); } if (noBad) { tooltip.add(mariculture.lib.util.Text.DARK_GREEN + currentLife + " HP"); } } else if (hasMale() && hasFemale()) { tooltip.add(mariculture.lib.util.Text.DARK_GREEN + currentLife + " HP"); } } return tooltip; } public int getFishLifeScaled(ItemStack fish, int scale) { FishSpecies species = Fishing.fishHelper.getSpecies(fish); if (species != null && fish.hasTagCompound()) { int gender = Fish.gender.getDNA(fish); int maxLife = fish.stackTagCompound.getInteger("Lifespan"); int currentLife = fish.stackTagCompound.getInteger("CurrentLife"); if (gender == FishyHelper.MALE && !hasFemale() || gender == FishyHelper.FEMALE && !hasMale()) return -1; if (fishCanLive(fish)) return currentLife * scale / maxLife; else return -1; } else return 0; } @Override public void setGUIData(int id, int value) { if (id == 6) tankSize = value; else if (id == 7) canWork = value == 1; else if (id == 8) isDay = value == 1; else if (id == 9) heat = value; else super.setGUIData(id, value); } @Override public ArrayList<Integer> getGUIData() { ArrayList<Integer> list = super.getGUIData(); list.add(tankSize); list.add(canWork ? 1 : 0); list.add(worldObj.isDaytime() ? 1 : 0); list.add(heat); return list; } @Override public boolean isNotificationVisible(NotificationType type) { switch (type) { case NO_FOOD: return tank.getFluid() == null || tank.getFluid() != null && tank.getFluid().fluidID != getFluidID("fish_food"); case NO_MALE: return !hasMale(); case NO_FEMALE: return !hasFemale(); case BAD_ENV: return (hasFemale() || hasMale()) && !canWork; default: return false; } } @Override public EjectSetting getEjectType() { return EjectSetting.ITEM; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); tankSize = nbt.getInteger("TankSize"); if (nbt.hasKey("TankBlock")) { tankBlock = (Block) Block.blockRegistry.getObject(nbt.getString("TankBlock")); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger("TankSize", tankSize); if (tankBlock != null) { nbt.setString("TankBlock", Block.blockRegistry.getNameForObject(tankBlock)); } } }
package mho.haskellesque.math; import mho.haskellesque.iterables.CachedIterable; import mho.haskellesque.iterables.Exhaustive; import mho.haskellesque.tuples.*; import org.jetbrains.annotations.NotNull; import java.math.BigInteger; import java.util.*; import java.util.function.Function; import static mho.haskellesque.iterables.IterableUtils.*; import static mho.haskellesque.ordering.Ordering.*; /** * Various combinatorial functions and <tt>Iterable</tt>s. */ public class Combinatorics { /** * The factorial function <tt>n</tt>! * * <ul> * <li><tt>n</tt> must be non-negative.</li> * <li>The result is a factorial.</li> * </ul> * * @param n the argument * @return <tt>n</tt>! */ public static @NotNull BigInteger factorial(int n) { if (n < 0) throw new ArithmeticException("cannot take factorial of " + n); return productBigInteger(range(BigInteger.ONE, BigInteger.valueOf(n))); } /** * The factorial function <tt>n</tt>! * * <ul> * <li><tt>n</tt> must be non-negative.</li> * <li>The result is a factorial.</li> * </ul> * * @param n the argument * @return <tt>n</tt>! */ public static @NotNull BigInteger factorial(@NotNull BigInteger n) { if (n.signum() == -1) throw new ArithmeticException("cannot take factorial of " + n); return productBigInteger(range(BigInteger.ONE, n)); } /** * The subfactorial function !<tt>n</tt> * * <ul> * <li><tt>n</tt> must be non-negative.</li> * <li>The result is a subfactorial (rencontres number).</li> * </ul> * * @param n the argument * @return !<tt>n</tt> */ public static @NotNull BigInteger subfactorial(int n) { if (n < 0) throw new ArithmeticException("cannot take subfactorial of " + n); BigInteger sf = BigInteger.ONE; for (int i = 1; i <= n; i++) { sf = sf.multiply(BigInteger.valueOf(i)); if ((i & 1) == 0) { sf = sf.add(BigInteger.ONE); } else { sf = sf.subtract(BigInteger.ONE); } } return sf; } /** * The subfactorial function !<tt>n</tt> * * <ul> * <li><tt>n</tt> must be non-negative.</li> * <li>The result is a subfactorial (rencontres number).</li> * </ul> * * @param n the argument * @return !<tt>n</tt> */ public static @NotNull BigInteger subfactorial(@NotNull BigInteger n) { if (n.signum() == -1) throw new ArithmeticException("cannot take subfactorial of " + n); BigInteger sf = BigInteger.ONE; for (BigInteger i = BigInteger.ONE; le(i, n); i = i.add(BigInteger.ONE)) { sf = sf.multiply(i); if (i.getLowestSetBit() != 0) { sf = sf.add(BigInteger.ONE); } else { sf = sf.subtract(BigInteger.ONE); } } return sf; } /** * Given two <tt>Iterable</tt>s, returns all ordered pairs of elements from these <tt>Iterable</tt>s in ascending * order. Both <tt>Iterable</tt>s must be finite; using long <tt>Iterable</tt>s is possible but discouraged. * * <ul> * <li><tt>as</tt> must be finite.</li> * <li><tt>bs</tt> must be finite.</li> * <li>The result is the Cartesian product of two finite <tt>Iterable</tt>s.</li> * </ul> * * Result length is |<tt>as</tt>||<tt>bs</tt>| * * @param as the first <tt>Iterable</tt> * @param bs the second <tt>Iterable</tt> * @param <A> the type of the first <tt>Iterable</tt>'s elements * @param <B> the type of the second <tt>Iterable</tt>'s elements * @return all ordered pairs of elements from <tt>as</tt> and <tt>bs</tt> */ public static @NotNull <A, B> Iterable<Pair<A, B>> pairsAscending( @NotNull Iterable<A> as, @NotNull Iterable<B> bs ) { return concatMap(p -> zip(repeat(p.a), p.b), zip(as, repeat(bs))); } /** * Given three <tt>Iterable</tt>s, returns all ordered triples of elements from these <tt>Iterable</tt>s in * ascending order. All <tt>Iterable</tt>s must be finite; using long <tt>Iterable</tt>s is possible but * discouraged. * * <ul> * <li><tt>as</tt> must be finite.</li> * <li><tt>bs</tt> must be finite.</li> * <li><tt>cs</tt> must be finite.</li> * <li>The result is the Cartesian product of three finite <tt>Iterable</tt>s.</li> * </ul> * * Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>| * * @param as the first <tt>Iterable</tt> * @param bs the second <tt>Iterable</tt> * @param cs the third <tt>Iterable</tt> * @param <A> the type of the first <tt>Iterable</tt>'s elements * @param <B> the type of the second <tt>Iterable</tt>'s elements * @param <C> the type of the third <tt>Iterable</tt>'s elements * @return all ordered triples of elements from <tt>as</tt>, <tt>bs</tt>, and <tt>cs</tt> */ public static @NotNull <A, B, C> Iterable<Triple<A, B, C>> triplesAscending( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs ) { return map( p -> new Triple<>(p.a, p.b.a, p.b.b), pairsAscending(as, (Iterable<Pair<B, C>>) pairsAscending(bs, cs)) ); } /** * Given four <tt>Iterable</tt>s, returns all ordered quadruples of elements from these <tt>Iterable</tt>s in * ascending order. All <tt>Iterable</tt>s must be finite; using long <tt>Iterable</tt>s is possible but * discouraged. * * <ul> * <li><tt>as</tt> must be finite.</li> * <li><tt>bs</tt> must be finite.</li> * <li><tt>cs</tt> must be finite.</li> * <li><tt>ds</tt> must be finite.</li> * <li>The result is the Cartesian product of four finite <tt>Iterable</tt>s.</li> * </ul> * * Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>| * * @param as the first <tt>Iterable</tt> * @param bs the second <tt>Iterable</tt> * @param cs the third <tt>Iterable</tt> * @param ds the fourth <tt>Iterable</tt> * @param <A> the type of the first <tt>Iterable</tt>'s elements * @param <B> the type of the second <tt>Iterable</tt>'s elements * @param <C> the type of the third <tt>Iterable</tt>'s elements * @param <D> the type of the fourth <tt>Iterable</tt>'s elements * @return all ordered quadruples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, and <tt>ds</tt> */ public static @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruplesAscending( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds ) { return map( p -> new Quadruple<>(p.a.a, p.a.b, p.b.a, p.b.b), pairsAscending( (Iterable<Pair<A, B>>) pairsAscending(as, bs), (Iterable<Pair<C, D>>) pairsAscending(cs, ds) ) ); } /** * Given five <tt>Iterable</tt>s, returns all ordered quintuples of elements from these <tt>Iterable</tt>s in * ascending order. All <tt>Iterable</tt>s must be finite; using long <tt>Iterable</tt>s is possible but * discouraged. * * <ul> * <li><tt>as</tt> must be finite.</li> * <li><tt>bs</tt> must be finite.</li> * <li><tt>cs</tt> must be finite.</li> * <li><tt>ds</tt> must be finite.</li> * <li><tt>es</tt> must be finite.</li> * <li>The result is the Cartesian product of five finite <tt>Iterable</tt>s.</li> * </ul> * * Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>| * * @param as the first <tt>Iterable</tt> * @param bs the second <tt>Iterable</tt> * @param cs the third <tt>Iterable</tt> * @param ds the fourth <tt>Iterable</tt> * @param es the fifth <tt>Iterable</tt> * @param <A> the type of the first <tt>Iterable</tt>'s elements * @param <B> the type of the second <tt>Iterable</tt>'s elements * @param <C> the type of the third <tt>Iterable</tt>'s elements * @param <D> the type of the fourth <tt>Iterable</tt>'s elements * @param <E> the type of the fifth <tt>Iterable</tt>'s elements * @return all ordered quintuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, and * <tt>es</tt> */ public static @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuplesAscending( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es ) { return map( p -> new Quintuple<>(p.a.a, p.a.b, p.b.a, p.b.b, p.b.c), pairsAscending( (Iterable<Pair<A, B>>) pairsAscending(as, bs), (Iterable<Triple<C, D, E>>) triplesAscending(cs, ds, es) ) ); } /** * Given six <tt>Iterable</tt>s, returns all ordered sextuples of elements from these <tt>Iterable</tt>s in * ascending order. All <tt>Iterable</tt>s must be finite; using long <tt>Iterable</tt>s is possible but * discouraged. * * <ul> * <li><tt>as</tt> must be finite.</li> * <li><tt>bs</tt> must be finite.</li> * <li><tt>cs</tt> must be finite.</li> * <li><tt>ds</tt> must be finite.</li> * <li><tt>es</tt> must be finite.</li> * <li><tt>fs</tt> must be finite.</li> * <li>The result is the Cartesian product of six finite <tt>Iterable</tt>s.</li> * </ul> * * Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>||<tt>fs</tt>| * * @param as the first <tt>Iterable</tt> * @param bs the second <tt>Iterable</tt> * @param cs the third <tt>Iterable</tt> * @param ds the fourth <tt>Iterable</tt> * @param es the fifth <tt>Iterable</tt> * @param fs the sixth <tt>Iterable</tt> * @param <A> the type of the first <tt>Iterable</tt>'s elements * @param <B> the type of the second <tt>Iterable</tt>'s elements * @param <C> the type of the third <tt>Iterable</tt>'s elements * @param <D> the type of the fourth <tt>Iterable</tt>'s elements * @param <E> the type of the fifth <tt>Iterable</tt>'s elements * @param <F> the type of the sixth <tt>Iterable</tt>'s elements * @return all ordered sextuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, <tt>es</tt>, * and <tt>fs</tt> */ public static @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuplesAscending( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es, @NotNull Iterable<F> fs ) { return map( p -> new Sextuple<>(p.a.a, p.a.b, p.a.c, p.b.a, p.b.b, p.b.c), pairsAscending( (Iterable<Triple<A, B, C>>) triplesAscending(as, bs, cs), (Iterable<Triple<D, E, F>>) triplesAscending(ds, es, fs) ) ); } /** * Given seven <tt>Iterable</tt>s, returns all ordered septuples of elements from these <tt>Iterable</tt>s in * ascending order. All <tt>Iterable</tt>s must be finite; using long <tt>Iterable</tt>s is possible but * discouraged. * * <ul> * <li><tt>as</tt> must be finite.</li> * <li><tt>bs</tt> must be finite.</li> * <li><tt>cs</tt> must be finite.</li> * <li><tt>ds</tt> must be finite.</li> * <li><tt>es</tt> must be finite.</li> * <li><tt>fs</tt> must be finite.</li> * <li><tt>gs</tt> must be finite.</li> * <li>The result is the Cartesian product of seven finite <tt>Iterable</tt>s.</li> * </ul> * * Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>||<tt>fs</tt>||<tt>gs</tt> * * @param as the first <tt>Iterable</tt> * @param bs the second <tt>Iterable</tt> * @param cs the third <tt>Iterable</tt> * @param ds the fourth <tt>Iterable</tt> * @param es the fifth <tt>Iterable</tt> * @param fs the sixth <tt>Iterable</tt> * @param gs the seventh <tt>Iterable</tt> * @param <A> the type of the first <tt>Iterable</tt>'s elements * @param <B> the type of the second <tt>Iterable</tt>'s elements * @param <C> the type of the third <tt>Iterable</tt>'s elements * @param <D> the type of the fourth <tt>Iterable</tt>'s elements * @param <E> the type of the fifth <tt>Iterable</tt>'s elements * @param <F> the type of the sixth <tt>Iterable</tt>'s elements * @param <G> the type of the seventh <tt>Iterable</tt>'s elements * @return all ordered septuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, <tt>es</tt>, * <tt>fs</tt>, and <tt>gs</tt> */ public static @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuplesAscending( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es, @NotNull Iterable<F> fs, @NotNull Iterable<G> gs ) { return map( p -> new Septuple<>(p.a.a, p.a.b, p.a.c, p.b.a, p.b.b, p.b.c, p.b.d), pairsAscending( (Iterable<Triple<A, B, C>>) triplesAscending(as, bs, cs), (Iterable<Quadruple<D, E, F, G>>) quadruplesAscending(ds, es, fs, gs) ) ); } /** * Returns an <tt>Iterable</tt> containing all lists of a given length with elements from a given * <tt>Iterable</tt>. The lists are ordered lexicographically, matching the order given by the original * <tt>Iterable</tt>. The <tt>Iterable</tt> must be finite; using a long <tt>Iterable</tt> is possible but * discouraged. * * <ul> * <li><tt>length</tt> must be non-negative.</li> * <li><tt>xs</tt> must be finite.</li> * <li>The result is finite. All of its elements have the same length. None are empty, unless the result consists * entirely of one empty element.</li> * </ul> * * @param length the length of the result lists * @param xs the <tt>Iterable</tt> from which elements are selected * @param <T> the type of the given <tt>Iterable</tt>'s elements * @return all lists of a given length created from <tt>xs</tt> */ public static @NotNull <T> Iterable<List<T>> listsAscending(int length, @NotNull Iterable<T> xs) { if (length < 0) throw new IllegalArgumentException("lists must have a non-negative length"); if (length == 0) { return Arrays.asList(new ArrayList<T>()); } Function<T, List<T>> makeSingleton = x -> { List<T> list = new ArrayList<>(); list.add(x); return list; }; List<Iterable<List<T>>> intermediates = new ArrayList<>(); intermediates.add(map(makeSingleton, xs)); for (int i = 1; i < length; i++) { Iterable<List<T>> lists = last(intermediates); intermediates.add(concatMap(x -> map(list -> toList(cons(x, list)), lists), xs)); } return last(intermediates); } /** * Returns an <tt>Iterable</tt> containing all lists of a given length with elements from a given * <tt>Iterable</tt>. The lists are ordered lexicographically, matching the order given by the original * <tt>Iterable</tt>. The <tt>Iterable</tt> must be finite; using a long <tt>Iterable</tt> is possible but * discouraged. * * <ul> * <li><tt>length</tt> must be non-negative.</li> * <li><tt>xs</tt> must be finite.</li> * <li>The result is finite. All of its elements have the same length. None are empty, unless the result consists * entirely of one empty element.</li> * </ul> * * @param length the length of the result lists * @param xs the <tt>Iterable</tt> from which elements are selected * @param <T> the type of the given <tt>Iterable</tt>'s elements * @return all lists of a given length created from <tt>xs</tt> */ public static @NotNull <T> Iterable<List<T>> listsAscending(@NotNull BigInteger length, @NotNull Iterable<T> xs) { if (lt(length, BigInteger.ZERO)) throw new IllegalArgumentException("lists must have a non-negative length"); if (eq(length, BigInteger.ZERO)) { return Arrays.asList(new ArrayList<T>()); } Function<T, List<T>> makeSingleton = x -> { List<T> list = new ArrayList<>(); list.add(x); return list; }; List<Iterable<List<T>>> intermediates = new ArrayList<>(); intermediates.add(map(makeSingleton, xs)); for (BigInteger i = BigInteger.ONE; lt(i, length); i = i.add(BigInteger.ONE)) { Iterable<List<T>> lists = last(intermediates); intermediates.add(concatMap(x -> map(list -> toList(cons(x, list)), lists), xs)); } return last(intermediates); } /** * Returns an <tt>Iterable</tt> containing all <tt>String</tt>s of a given length with characters from a given * <tt>Iterable</tt>. The <tt>String</tt>s are ordered lexicographically, matching the order given by the original * <tt>Iterable</tt>. Using long <tt>String</tt> is possible but discouraged. * * <ul> * <li><tt>length</tt> must be non-negative.</li> * <li><tt>s</tt> is non-null.</li> * <li>The result is finite. All of its <tt>String</tt>s have the same length. None are empty, unless the result * consists entirely of one empty <tt>String</tt>.</li> * </ul> * * @param length the length of the result <tt>String</tt> * @param s the <tt>String</tt> from which characters are selected * @return all Strings of a given length created from <tt>s</tt> */ public static @NotNull Iterable<String> listsAscending(int length, @NotNull String s) { if (length < 0) throw new IllegalArgumentException("strings must have a non-negative length"); BigInteger totalLength = BigInteger.valueOf(s.length()).pow(length); Function<BigInteger, String> f = bi -> charsToString( map( i -> s.charAt(i.intValue()), BasicMath.bigEndianDigitsPadded(BigInteger.valueOf(length), BigInteger.valueOf(s.length()), bi) ) ); return map(f, range(BigInteger.ZERO, totalLength.subtract(BigInteger.ONE))); } /** * Returns an <tt>Iterable</tt> containing all <tt>String</tt>s of a given length with characters from a given * <tt>Iterable</tt>. The <tt>String</tt>s are ordered lexicographically, matching the order given by the original * <tt>Iterable</tt>. Using long <tt>String</tt> is possible but discouraged. * * <ul> * <li><tt>length</tt> must be non-negative.</li> * <li><tt>s</tt> is non-null.</li> * <li>The result is finite. All of its <tt>String</tt>s have the same length. None are empty, unless the result * consists entirely of one empty <tt>String</tt>.</li> * </ul> * * @param length the length of the result <tt>String</tt> * @param s the <tt>String</tt> from which characters are selected * @return all Strings of a given length created from <tt>s</tt> */ public static @NotNull Iterable<String> listsAscending(@NotNull BigInteger length, @NotNull String s) { if (lt(length, BigInteger.ZERO)) throw new IllegalArgumentException("strings must have a non-negative length"); BigInteger totalLength = BigInteger.valueOf(s.length()).pow(length.intValue()); Function<BigInteger, String> f = bi -> charsToString( map( i -> s.charAt(i.intValue()), BasicMath.bigEndianDigitsPadded( BigInteger.valueOf(length.intValue()), BigInteger.valueOf(s.length()), bi ) ) ); return map(f, range(BigInteger.ZERO, totalLength.subtract(BigInteger.ONE))); } public static @NotNull <T> Iterable<List<T>> listsShortlex(@NotNull Iterable<T> xs) { return concatMap(i -> listsAscending(i, xs), Exhaustive.NATURAL_BIG_INTEGERS); } public static @NotNull Iterable<String> stringsShortlex(@NotNull String s) { return concatMap(i -> listsAscending(i, s), Exhaustive.NATURAL_BIG_INTEGERS); } public static <A, B> Iterable<Pair<A, B>> pairsExponentialOrder(Iterable<A> as, Iterable<B> bs) { CachedIterable<A> aii = new CachedIterable<>(as); CachedIterable<B> bii = new CachedIterable<>(bs); Function<BigInteger, Optional<Pair<A, B>>> f = bi -> { Pair<BigInteger, BigInteger> p = BasicMath.exponentialDemux(bi); assert p.a != null; Optional<A> optA = aii.get(p.a.intValue()); if (!optA.isPresent()) return Optional.empty(); assert p.b != null; Optional<B> optB = bii.get(p.b.intValue()); if (!optB.isPresent()) return Optional.empty(); return Optional.of(new Pair<A, B>(optA.get(), optB.get())); }; return map( Optional::get, filter( Optional<Pair<A, B>>::isPresent, (Iterable<Optional<Pair<A, B>>>) map(bi -> f.apply(bi), Exhaustive.BIG_INTEGERS) ) ); } public static <T> Iterable<Pair<T, T>> pairsExponentialOrder(Iterable<T> xs) { CachedIterable<T> ii = new CachedIterable<>(xs); Function<BigInteger, Optional<Pair<T, T>>> f = bi -> { Pair<BigInteger, BigInteger> p = BasicMath.exponentialDemux(bi); assert p.a != null; Optional<T> optA = ii.get(p.a.intValue()); if (!optA.isPresent()) return Optional.empty(); assert p.b != null; Optional<T> optB = ii.get(p.b.intValue()); if (!optB.isPresent()) return Optional.empty(); return Optional.of(new Pair<T, T>(optA.get(), optB.get())); }; return map( Optional::get, filter( Optional<Pair<T, T>>::isPresent, (Iterable<Optional<Pair<T, T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <A, B> Iterable<Pair<A, B>> pairs(Iterable<A> as, Iterable<B> bs) { CachedIterable<A> aii = new CachedIterable<>(as); CachedIterable<B> bii = new CachedIterable<>(bs); Function<BigInteger, Optional<Pair<A, B>>> f = bi -> { List<BigInteger> p = BasicMath.demux(2, bi); assert p.get(0) != null; Optional<A> optA = aii.get(p.get(0).intValue()); if (!optA.isPresent()) return Optional.empty(); assert p.get(1) != null; Optional<B> optB = bii.get(p.get(1).intValue()); if (!optB.isPresent()) return Optional.empty(); return Optional.of(new Pair<A, B>(optA.get(), optB.get())); }; return map( Optional::get, filter( Optional<Pair<A, B>>::isPresent, (Iterable<Optional<Pair<A, B>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <A, B, C> Iterable<Triple<A, B, C>> triples(Iterable<A> as, Iterable<B> bs, Iterable<C> cs) { CachedIterable<A> aii = new CachedIterable<>(as); CachedIterable<B> bii = new CachedIterable<>(bs); CachedIterable<C> cii = new CachedIterable<>(cs); Function<BigInteger, Optional<Triple<A, B, C>>> f = bi -> { List<BigInteger> p = BasicMath.demux(3, bi); assert p.get(0) != null; Optional<A> optA = aii.get(p.get(0).intValue()); if (!optA.isPresent()) return Optional.empty(); assert p.get(1) != null; Optional<B> optB = bii.get(p.get(1).intValue()); if (!optB.isPresent()) return Optional.empty(); assert p.get(2) != null; Optional<C> optC = cii.get(p.get(2).intValue()); if (!optC.isPresent()) return Optional.empty(); return Optional.of(new Triple<A, B, C>(optA.get(), optB.get(), optC.get())); }; return map( Optional::get, filter( Optional<Triple<A, B, C>>::isPresent, (Iterable<Optional<Triple<A, B, C>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples( Iterable<A> as, Iterable<B> bs, Iterable<C> cs, Iterable<D> ds ) { CachedIterable<A> aii = new CachedIterable<>(as); CachedIterable<B> bii = new CachedIterable<>(bs); CachedIterable<C> cii = new CachedIterable<>(cs); CachedIterable<D> dii = new CachedIterable<>(ds); Function<BigInteger, Optional<Quadruple<A, B, C, D>>> f = bi -> { List<BigInteger> p = BasicMath.demux(4, bi); assert p.get(0) != null; Optional<A> optA = aii.get(p.get(0).intValue()); if (!optA.isPresent()) return Optional.empty(); assert p.get(1) != null; Optional<B> optB = bii.get(p.get(1).intValue()); if (!optB.isPresent()) return Optional.empty(); assert p.get(2) != null; Optional<C> optC = cii.get(p.get(2).intValue()); if (!optC.isPresent()) return Optional.empty(); assert p.get(3) != null; Optional<D> optD = dii.get(p.get(3).intValue()); if (!optD.isPresent()) return Optional.empty(); return Optional.of(new Quadruple<A, B, C, D>(optA.get(), optB.get(), optC.get(), optD.get())); }; return map( Optional::get, filter( Optional<Quadruple<A, B, C, D>>::isPresent, (Iterable<Optional<Quadruple<A, B, C, D>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <T> Iterable<List<T>> lists(int size, Iterable<T> xs) { if (size == 0) { return Arrays.asList(new ArrayList<T>()); } CachedIterable<T> ii = new CachedIterable<>(xs); Function<BigInteger, Optional<List<T>>> f = bi -> ii.get(map(BigInteger::intValue, BasicMath.demux(size, bi))); return map( Optional::get, filter( Optional<List<T>>::isPresent, (Iterable<Optional<List<T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <T> Iterable<List<T>> lists(Iterable<T> xs) { CachedIterable<T> ii = new CachedIterable<>(xs); Function<BigInteger, Optional<List<T>>> f = bi -> { if (bi.equals(BigInteger.ZERO)) { return Optional.of(new ArrayList<T>()); } bi = bi.subtract(BigInteger.ONE); Pair<BigInteger, BigInteger> sizeIndex = BasicMath.exponentialDemux(bi); int size = sizeIndex.b.intValue() + 1; return ii.get(map(BigInteger::intValue, BasicMath.demux(size, sizeIndex.a))); }; return map( Optional::get, filter( Optional<List<T>>::isPresent, (Iterable<Optional<List<T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS) ) ); } public static <T> Iterable<List<T>> orderedSubsequences(Iterable<T> xs) { if (isEmpty(xs)) return Arrays.asList(new ArrayList<T>()); final CachedIterable<T> ii = new CachedIterable(xs); return () -> new Iterator<List<T>>() { private List<Integer> indices = new ArrayList<>(); @Override public boolean hasNext() { return indices != null; } @Override public List<T> next() { List<T> subsequence = ii.get(indices).get(); if (indices.isEmpty()) { indices.add(0); } else { int lastIndex = last(indices); if (lastIndex < ii.size() - 1) { indices.add(lastIndex + 1); } else if (indices.size() == 1) { indices = null; } else { indices.remove(indices.size() - 1); indices.set(indices.size() - 1, last(indices) + 1); } } return subsequence; } }; } }
package model.job.metadata; import java.util.List; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(Include.NON_NULL) public class ResourceMetadata { public String name; @JsonProperty("_id") public String id; public String description; public String url; public String filePath; public String format; public String networks; public String qos; public String availability; public String tags; public String classType; @JsonIgnore public DateTime termDate; public Boolean clientCertRequired; public Boolean credentialsRequired; public Boolean preAuthRequired; public String contacts; public String method; public String requestMimeType; public String param; @JsonProperty("params") public List<String> params; public String responseMimeType; public String reason; }
package name.matco.simcity.model; import java.util.List; import java.util.Optional; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(value = Include.NON_NULL) public class Ingredient { public String id; public String name; public Long time; public List<Dependency> dependencies; public Optional<Dependency> getDependency(final String dependencyId) { return dependencies.stream().filter((final Dependency d) -> d.id.equals(dependencyId)).findFirst(); } }
package net.addradio.streams; import java.io.IOException; import java.io.InputStream; /** * BitInputStream */ public class BitInputStream extends InputStream { /** {@code int} MAX_OFFSET */ static final int MAX_OFFSET = 7; /** {@code int} bitInByteOffset */ private int bitInByteOffset = -1; /** {@link InputStream} inner */ private InputStream inner; /** {@code int} lastByte */ private int lastByte; /** {@link Object} lock */ private final Object lock = new Object(); /** * BitInputStream constructor. * @param innerRef * {@link InputStream} */ public BitInputStream(final InputStream innerRef) { setInner(innerRef); } /** * available. * @see java.io.InputStream#available() * @return {@code int} * @throws IOException * in case of bad IO situations. */ @Override public int available() throws IOException { return this.inner.available(); } /** * close. * @see java.io.InputStream#close() * @throws IOException * in case of bad IO situations. */ @Override public void close() throws IOException { this.lastByte = 0; this.bitInByteOffset = -1; this.inner.close(); } /** * getInner. * @return {@link InputStream} the inner. */ public InputStream getInner() { return this.inner; } /** * innerRead. * @return {@code int} read from inner stream. * @throws IOException due to IO problems or if end of stream has been reached. */ private int innerRead() throws IOException { final int read = this.inner.read(); // System.out.println("read byte: 0x" + Integer.toHexString(read)); if (read < 0) { throw new EndOfStreamException(); } return read; } /** * isByteAligned. * @return {@code boolean true} if read pointer is aligned to byte boundaries. */ public boolean isByteAligned() { return this.bitInByteOffset < 0; } /** * isNextBitOne. Reads just one bit and checks whether it is 0b1 or not. * * @return {@code boolean true} only if the next bit is 0b1. * @throws IOException due to IO problems. */ public boolean isNextBitOne() throws IOException { return readBit() == 1; } /** * isNextBitOne. Reads just one bit and checks whether it is 0b0 or not. * * @return {@code boolean true} only if the next bit is 0b0. * @throws IOException due to IO problems. */ public boolean isNextBitZero() throws IOException { return readBit() == 0; } /** * read. * @see java.io.InputStream#read() * @return {@code int} * @throws IOException * in case of bad IO situations. */ @Override public int read() throws IOException { synchronized (this.lock) { if (isByteAligned()) { return innerRead(); } } return readBits(8); } /** * readBit. * @return {@code int} the read bit. * @throws IOException * in case of bad IO situations. */ public int readBit() throws IOException { synchronized (this.lock) { if (isByteAligned()) { this.bitInByteOffset = BitInputStream.MAX_OFFSET; this.lastByte = innerRead(); } final int returnVal = (this.lastByte & (0x1 << this.bitInByteOffset)) >> this.bitInByteOffset; this.bitInByteOffset // System.out.println("read bit: 0b" + Integer.toBinaryString(returnVal)); return returnVal; } } /** * readBits. * @param numberOfBitsToRead * <code>int</code> * @return <code>int</code> the value of the read bits; * @throws IOException * in case of bad IO situations. */ public int readBits(final int numberOfBitsToRead) throws IOException { int returnVal = 0; for (int offset = numberOfBitsToRead - 1; offset > -1; offset returnVal |= readBit() << offset; } // System.out.println("read bits: 0b" + Integer.toBinaryString(returnVal)); return returnVal; } /** * readFully. * @param toFill * <code>byte[]</code> * @throws IOException * in case of bad IO situations. */ public void readFully(final byte[] toFill) throws IOException { for (int i = 0; i < toFill.length; i++) { toFill[i] = (byte) read(); } } /** * readInt. * @param numOfBytes {@code int} to be read. * @return {@code int} * @throws IOException due to IO problems. */ public int readInt(final int numOfBytes) throws IOException { // SEBASTIAN check for max bytes int value = 0; for (int i = numOfBytes - 1; i > -1; i value |= (read() << (i * 8)); } return value; } /** * setInner. * @param innerRef * {@link InputStream} the inner to set. */ public void setInner(final InputStream innerRef) { this.inner = innerRef; } /** * skipBit. * @throws IOException due to bad IO situations. */ public void skipBit() throws IOException { skipBits(1); } // @Override // public long skip(long n) throws IOException { // // TODO Auto-generated method stub // return super.skip(n); /** * skipBits. * @param numberOfBitsToSkip {@code int} * @throws IOException in case of bad IO situations. */ public void skipBits(final int numberOfBitsToSkip) throws IOException { // SEBASTIAN implement more efficiently readBits(numberOfBitsToSkip); } }
package net.malisis.core.util; import java.util.HashMap; import net.malisis.core.MalisisCore; import net.malisis.core.util.chunkcollision.ChunkCollision; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; /** * RayTrace class that offers more control to handle raytracing. * * @author Ordinastie * */ public class RaytraceWorld { /** Number of blocks before we consider ray trace failed. */ private static int MAX_BLOCKS = 200; /** World object (needed for ray tracing inside each block). */ private World world; /** Source of the ray trace. */ private Point src; /** Destination of the ray trace. */ private Point dest; /** Ray describing the ray trace. */ private Ray ray; /** Vector describing the direction of steps to take when reaching limits of a block. */ private Vector step; /** The block coordinates of the source. */ private ChunkPosition blockSrc; /** The block coordinates of the destination. */ private ChunkPosition blockDest; /** Current X coordinate of the block being ray traced. */ private int currentX; /** Current Y coordinate of the block being ray traced. */ private int currentY; /** Current Z coordinate of the block being ray traced. */ private int currentZ; /** * The first block to be hit. If ray trace reaches <code>dest</code> without any hit, <code>firstHit</code> will have * <code>typeOfHit</code> = <b>MISS</b> */ public MovingObjectPosition firstHit; /** List of blocks passed by the ray trace. Only set if options <code>LOG_BLOCK_PASSED</code> is set */ public HashMap<ChunkPosition, MovingObjectPosition> blockPassed; /** Options for the ray tracing. */ public int options = 0; /** * Instantiates a new {@link RaytraceWorld}. * * @param ray the ray * @param options the options */ public RaytraceWorld(Ray ray, int options) { this.world = Minecraft.getMinecraft().theWorld; this.src = ray.origin; this.ray = ray; this.options = options; blockSrc = new ChunkPosition(src.toVec3()); int stepX = 1, stepY = 1, stepZ = 1; if (ray.direction.x < 0) stepX = -1; if (ray.direction.y < 0) stepY = -1; if (ray.direction.z < 0) stepZ = -1; step = new Vector(stepX, stepY, stepZ); if (hasOption(Options.LOG_BLOCK_PASSED)) blockPassed = new HashMap<ChunkPosition, MovingObjectPosition>(); } /** * Instantiates a new {@link RaytraceWorld}. * * @param ray the ray */ public RaytraceWorld(Ray ray) { this(ray, 0); } /** * Instantiates a new {@link RaytraceWorld}. * * @param src the src * @param v the v * @param options the options */ public RaytraceWorld(Point src, Vector v, int options) { this(new Ray(src, v), options); } /** * Instantiates a new {@link RaytraceWorld}. * * @param src the src * @param v the v */ public RaytraceWorld(Point src, Vector v) { this(new Ray(src, v), 0); } /** * Instantiates a new {@link RaytraceWorld}. * * @param src the src * @param dest the dest * @param options the options */ public RaytraceWorld(Point src, Point dest, int options) { this(new Ray(src, new Vector(src, dest)), options); this.dest = dest; blockDest = new ChunkPosition(dest.toVec3()); } /** * Instantiates a new {@link RaytraceWorld}. * * @param src the src * @param dest the dest */ public RaytraceWorld(Point src, Point dest) { this(new Ray(src, new Vector(src, dest)), 0); this.dest = dest; blockDest = new ChunkPosition(dest.toVec3()); } /** * Gets the source of this {@link RaytraceWorld} * * @return the source */ public Point getSource() { return src; } /** * Gets the destination of this {@link RaytraceWorld}. * * @return the destination */ public Point getDestination() { return dest; } /** * Gets the direction vector of the ray. * * @return the direction */ public Vector direction() { return ray.direction; } /** * Gets the length of the ray. * * @return the distance */ public double distance() { return ray.direction.length(); } /** * Sets the length of this {@link RaytraceWorld}. * * @param length the new length */ public void setLength(double length) { dest = ray.getPointAt(length); blockDest = new ChunkPosition(dest.toVec3()); } /** * Checks if the option <code>opt</code> is set. * * @param opt the option to check * @return true, if option is present, false otherwise */ public boolean hasOption(int opt) { return (options & opt) != 0; } /** * Does the raytracing. * * @return {@link MovingObjectPosition} with <code>typeOfHit</code> <b>BLOCK</b> if a ray hits a block in the way, or <b>MISS</b> if it * reaches <code>dest</code> without any hit */ public MovingObjectPosition trace() { MovingObjectPosition mop = null; double tX, tY, tZ, min; int count = 0; boolean ret = false; firstHit = null; currentX = blockSrc.chunkPosX; currentY = blockSrc.chunkPosY; currentZ = blockSrc.chunkPosZ; while (!ret && count++ <= MAX_BLOCKS) { tX = ray.intersectX(currentX + (ray.direction.x > 0 ? 1 : 0)); tY = ray.intersectY(currentY + (ray.direction.y > 0 ? 1 : 0)); tZ = ray.intersectZ(currentZ + (ray.direction.z > 0 ? 1 : 0)); min = getMin(tX, tY, tZ); // do not trace first block if (count != 1 || !hasOption(Options.IGNORE_FIRST_BLOCK)) mop = rayTraceBlock(currentX, currentY, currentZ, ray.getPointAt(min)); if (firstHit == null) firstHit = mop; if (hasOption(Options.LOG_BLOCK_PASSED)) blockPassed.put(new ChunkPosition(currentX, currentY, currentZ), mop); if (dest != null && currentX == blockDest.chunkPosX && currentY == blockDest.chunkPosY && currentZ == blockDest.chunkPosZ) ret = true; if (!ret) { if (min == tX) currentX += step.x; if (min == tY) currentY += step.y; if (min == tZ) currentZ += step.z; } if (dest != null && dest.equals(ray.getPointAt(min))) ret = true; } if (firstHit == null && dest != null) firstHit = new MovingObjectPosition(currentX, currentY, currentZ, -1, dest.toVec3(), false); ChunkCollision.get().setRayTraceInfos(src, dest); firstHit = ChunkCollision.get().getRayTraceResult(world, firstHit); if (!ret) MalisisCore.message("Trace fail : " + MAX_BLOCKS + " blocks passed (" + currentX + "," + currentY + "," + currentZ + ")"); return firstHit; } /** * Gets the minimum value of <code>x</code>, <code>y</code>, <code>z</code>. * * @param x the x * @param y the y * @param z the z * @return <code>Double.NaN</code> if <code>x</code>, <code>y</code> and <code>z</code> are all three are <code>Double.NaN</code> */ public double getMin(double x, double y, double z) { double ret = Double.NaN; if (!Double.isNaN(x)) ret = x; if (!Double.isNaN(y)) { if (!Double.isNaN(ret)) ret = Math.min(ret, y); else ret = y; } if (!Double.isNaN(z)) { if (!Double.isNaN(ret)) ret = Math.min(ret, z); else ret = z; } return ret; } /** * Raytraces inside an actual block area. Calls * {@link Block#collisionRayTrace(World, int, int, int, net.minecraft.util.Vec3, net.minecraft.util.Vec3)} * * @param x the x coordinate of the block to trace * @param y the y coordinate of the block to trace * @param z the z coordinate of the block to trace * @param exit the exit * @return the {@link MovingObjectPosition} return by block raytrace */ public MovingObjectPosition rayTraceBlock(int x, int y, int z, Point exit) { Block block = world.getBlock(x, y, z); int metadata = world.getBlockMetadata(x, y, z); if (hasOption(Options.CHECK_COLLISION) && block.getCollisionBoundingBoxFromPool(world, x, y, z) == null) return null; if (!block.canStopRayTrace(metadata, hasOption(Options.HIT_LIQUIDS))) return null; return RaytraceBlock.set(world, src, exit, x, y, z).trace(); } /** * The Class Options. */ public static class Options { /** Ray tracing through liquids returns a hit. */ public static int HIT_LIQUIDS = 1; /** Don't stop ray tracing on hit. */ public static int PASS_THROUGH = 1 << 1; /** Don't hit the block source of ray tracing. */ public static int IGNORE_FIRST_BLOCK = 1 << 2; /** Stores list of blocks passed through ray trace. */ public static int LOG_BLOCK_PASSED = 1 << 3; /** Whether a block has to have a collision bounding box to rayTrace it. */ public static int CHECK_COLLISION = 1 << 5; } }
package jade.imtp.leap.JICP; import jade.core.MicroRuntime; import jade.core.FEConnectionManager; import jade.core.FrontEnd; import jade.core.BackEnd; import jade.core.IMTPException; import jade.core.TimerDispatcher; import jade.core.Timer; import jade.core.TimerListener; import jade.mtp.TransportAddress; import jade.imtp.leap.BackEndStub; import jade.imtp.leap.MicroSkeleton; import jade.imtp.leap.FrontEndSkel; import jade.imtp.leap.Dispatcher; import jade.imtp.leap.ICPException; import jade.imtp.leap.ConnectionListener; import jade.util.leap.Properties; import jade.util.Logger; import java.io.*; import java.util.Vector; import java.util.Enumeration; /** * Class declaration * @author Giovanni Caire - TILAB */ public class BIFEDispatcher implements FEConnectionManager, Dispatcher, TimerListener, Runnable { protected static final byte INP = (byte) 1; protected static final byte OUT = (byte) 0; private static final String OWNER = "owner"; private static final String MSISDN = "msisdn"; protected String myMediatorClass = "jade.imtp.leap.JICP.BIBEDispatcher"; private MicroSkeleton mySkel = null; private BackEndStub myStub = null; // Variables related to the connection with the Mediator protected TransportAddress mediatorTA; private String myMediatorID; private long retryTime = JICPProtocol.DEFAULT_RETRY_TIME; private long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME; private long keepAliveTime = JICPProtocol.DEFAULT_KEEP_ALIVE_TIME; private Timer kaTimer; private Properties props; protected Connection outConnection; protected InputManager myInputManager; private ConnectionListener myConnectionListener; private boolean active = true; private boolean waitingForFlush = false; protected boolean refreshingInput = false; protected boolean refreshingOutput = false; private byte lastSid = 0x0f; private int outCnt = 0; private Thread terminator; private String beAddrsText; private String[] backEndAddresses; private Logger myLogger = Logger.getMyLogger(getClass().getName()); // FEConnectionManager interface implementation /** * Connect to a remote BackEnd and return a stub to communicate with it */ public BackEnd getBackEnd(FrontEnd fe, Properties props) throws IMTPException { this.props = props; try { beAddrsText = props.getProperty(FrontEnd.REMOTE_BACK_END_ADDRESSES); backEndAddresses = parseBackEndAddresses(beAddrsText); // Host String host = props.getProperty(MicroRuntime.HOST_KEY); if (host == null) { host = "localhost"; } // Port int port = JICPProtocol.DEFAULT_PORT; try { port = Integer.parseInt(props.getProperty(MicroRuntime.PORT_KEY)); } catch (NumberFormatException nfe) { // Use default } // Compose URL mediatorTA = JICPProtocol.getInstance().buildAddress(host, String.valueOf(port), null, null); if (myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE, "Remote URL="+JICPProtocol.getInstance().addrToString(mediatorTA)); } // Read (re)connection retry time String tmp = props.getProperty(JICPProtocol.RECONNECTION_RETRY_TIME_KEY); try { retryTime = Long.parseLong(tmp); } catch (Exception e) { // Use default } if (myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE, "Reconnection time="+retryTime); } // Read Max disconnection time tmp = props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY); try { maxDisconnectionTime = Long.parseLong(tmp); } catch (Exception e) { // Use default } if (myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE, "Max discon. time="+maxDisconnectionTime); } // Read Keep-alive time tmp = props.getProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY); try { keepAliveTime = Long.parseLong(tmp); } catch (Exception e) { // Use default } if (myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE, "Keep-alive time="+keepAliveTime); } // Create the BackEnd stub and the FrontEnd skeleton myStub = new BackEndStub(this); mySkel = new FrontEndSkel(fe); outConnection = createBackEnd(); // Start the InputManager dealing with incoming commands refreshInp(); return myStub; } catch (ICPException icpe) { throw new IMTPException("Connection error", icpe); } } /** Make this BIFEDispatcher terminate. */ public synchronized void shutdown() { active = false; terminator = Thread.currentThread(); if (terminator != myInputManager) { // This is a self-initiated shut down --> we must explicitly // notify the BackEnd. if (outConnection != null) { myLogger.log(Logger.FINE, "Sending termination notification"); JICPPacket pkt = new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.TERMINATED_INFO, null); try { writePacket(pkt, outConnection); myLogger.log(Logger.FINE, "Done."); } catch (Exception e) { // When the BackEnd receives the termination notification, // it just closes the connection --> we always have this // exception myLogger.log(Logger.FINE, "BackEnd closed"); } } } } /** Send the CREATE_MEDIATOR command with the necessary parameter in order to create the BackEnd in the fixed network. Executed - at bootstrap time by the thread that creates the FrontEndContainer. - To re-attach to the platform after a fault of the BackEnd */ private JICPConnection createBackEnd() throws IMTPException { StringBuffer sb = new StringBuffer(); appendProp(sb, JICPProtocol.MEDIATOR_CLASS_KEY, myMediatorClass); appendProp(sb, JICPProtocol.MAX_DISCONNECTION_TIME_KEY, String.valueOf(maxDisconnectionTime)); appendProp(sb, JICPProtocol.KEEP_ALIVE_TIME_KEY, String.valueOf(keepAliveTime)); if(myMediatorID != null) { // This is a request to re-create my expired back-end appendProp(sb, JICPProtocol.MEDIATOR_ID_KEY, myMediatorID); appendProp(sb, "outcnt", String.valueOf(outCnt)); appendProp(sb, "lastsid", String.valueOf(lastSid)); } appendProp(sb, FrontEnd.REMOTE_BACK_END_ADDRESSES, beAddrsText); appendProp(sb, OWNER, props.getProperty(OWNER)); appendProp(sb, MSISDN, props.getProperty(MSISDN)); JICPPacket pkt = new JICPPacket(JICPProtocol.CREATE_MEDIATOR_TYPE, JICPProtocol.DEFAULT_INFO, null, sb.toString().getBytes()); // Try first with the current transport address, then with the various backup addresses for(int i = -1; i < backEndAddresses.length; i++) { if(i >= 0) { // Set the mediator address to a new address.. String addr = backEndAddresses[i]; int colonPos = addr.indexOf(':'); String host = addr.substring(0, colonPos); String port = addr.substring(colonPos + 1, addr.length()); mediatorTA = new JICPAddress(host, port, myMediatorID, ""); } try { myLogger.log(Logger.INFO, "Creating BackEnd on jicp://"+mediatorTA.getHost()+":"+mediatorTA.getPort()); JICPConnection con = new JICPConnection(mediatorTA); writePacket(pkt, con); pkt = con.readPacket(); String replyMsg = new String(pkt.getData()); if (pkt.getType() != JICPProtocol.ERROR_TYPE) { // BackEnd creation successful int index = replyMsg.indexOf(' myMediatorID = replyMsg.substring(0, index); props.setProperty(JICPProtocol.MEDIATOR_ID_KEY, myMediatorID); props.setProperty(JICPProtocol.LOCAL_HOST_KEY, replyMsg.substring(index+1)); // Complete the mediator address with the mediator ID mediatorTA = new JICPAddress(mediatorTA.getHost(), mediatorTA.getPort(), myMediatorID, null); myLogger.log(Logger.INFO, "BackEnd OK"); return con; } else { myLogger.log(Logger.INFO, "Mediator error: "+replyMsg); } } catch (IOException ioe) { // Ignore it, and try the next address... myLogger.log(Logger.INFO, "Connection error. "+ioe.toString()); } } // No address succeeded: try to handle the problem... throw new IMTPException("Error creating the BackEnd."); } private void appendProp(StringBuffer sb, String key, String val) { if (val != null) { sb.append(key); sb.append('='); sb.append(val); sb.append(' } } // Dispatcher interface implementation /** Deliver a serialized command to the BackEnd. @return The serialized response */ public synchronized byte[] dispatch(byte[] payload, boolean flush) throws ICPException { if (outConnection != null) { if (waitingForFlush && !flush) { throw new ICPException("Upsetting dispatching order"); } waitingForFlush = false; int status = 0; if (myLogger.isLoggable(Logger.FINEST)) { myLogger.log(Logger.FINEST, "Issuing outgoing command "+outCnt); } JICPPacket pkt = new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.DEFAULT_INFO, payload); pkt.setSessionID((byte) outCnt); try { writePacket(pkt, outConnection); status = 1; pkt = outConnection.readPacket(); if (pkt.getSessionID() != outCnt) { pkt = outConnection.readPacket(); } status = 2; if (myLogger.isLoggable(Logger.FINEST)) { myLogger.log(Logger.FINEST, "Response received "+pkt.getSessionID()); } if (pkt.getType() == JICPProtocol.ERROR_TYPE) { // Communication OK, but there was a JICP error on the peer throw new ICPException(new String(pkt.getData())); } if ((pkt.getInfo() & JICPProtocol.RECONNECT_INFO) != 0) { // The BackEnd is considering the input connection no longer valid refreshInp(); } outCnt = (outCnt+1) & 0x0f; return pkt.getData(); } catch (IOException ioe) { // Can't reach the BackEnd. if (myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE, "IOException OC["+status+"]"+ioe); } refreshOut(); throw new ICPException("Dispatching error.", ioe); } } else { throw new ICPException("Unreachable"); } } // These variables are only used within the InputManager class, // but are declared externally since they must "survive" when // an InputManager is replaced private JICPPacket lastResponse = null; private int cnt = 0; /** Inner class InputManager. This class is responsible for serving incoming commands */ private class InputManager extends Thread { private int myId; private Connection myConnection = null; public void run() { if (cnt == 0) { // Give precedence to the Thread that is creating the BackEnd Thread.yield(); // In the meanwhile load the ConnectionListener if any try { myConnectionListener = (ConnectionListener) Class.forName(props.getProperty("connection-listener")).newInstance(); } catch (Exception e) { // Just ignore it } } myId = cnt++; if (myLogger.isLoggable(Logger.CONFIG)) { myLogger.log(Logger.CONFIG, "IM-"+myId+" started"); } int status = 0; connect(INP); try { while (isConnected()) { status = 0; JICPPacket pkt = myConnection.readPacket(); status = 1; byte sid = pkt.getSessionID(); if (sid == lastSid) { // Duplicated packet if (myLogger.isLoggable(Logger.FINE)) { myLogger.log(Logger.FINE, "Duplicated packet received "+sid); } pkt = lastResponse; } else { if (pkt.getType() == JICPProtocol.KEEP_ALIVE_TYPE) { // Keep-alive pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null); } else { // Incoming command if (myLogger.isLoggable(Logger.FINEST)) { myLogger.log(Logger.FINEST, "Incoming command received "+sid+" pkt-type="+pkt.getType()); } byte[] rspData = mySkel.handleCommand(pkt.getData()); if (myLogger.isLoggable(Logger.FINEST)) { myLogger.log(Logger.FINEST, "Incoming command served "+ sid); } pkt = new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, rspData); } pkt.setSessionID(sid); if (Thread.currentThread() == terminator) { // Attach the TERMINATED_INFO flag to the response pkt.setTerminatedInfo(true); } lastSid = sid; lastResponse = pkt; } status = 2; writePacket(pkt, myConnection); status = 3; } } catch (IOException ioe) { if (active) { if (myLogger.isLoggable(Logger.CONFIG)) { myLogger.log(Logger.CONFIG, "IOException IC["+status+"]"+ioe); } refreshInp(); } } if (myLogger.isLoggable(Logger.CONFIG)) { myLogger.log(Logger.CONFIG, "IM-"+myId+" terminated"); } } private void close() { try { myConnection.close(); } catch (Exception e) {} myConnection = null; } private final void setConnection(Connection c) { refreshingInput = false; myConnection = c; } private final boolean isConnected() { return myConnection != null; } } // END of inner class InputManager /** Close the current InputManager (if any) and start a new one */ protected synchronized void refreshInp() { // Avoid 2 refresh at the same time if (!refreshingInput && active) { // Close the current InputManager if (myInputManager != null && myInputManager.isConnected()) { myInputManager.close(); if (outConnection != null && myConnectionListener != null) { myConnectionListener.handleDisconnection(); } } // Start a new InputManager refreshingInput = true; myInputManager = new InputManager(); myInputManager.start(); } } /** Close the current outConnection (if any) and starts a new thread that asynchronously tries to restore it. */ protected synchronized void refreshOut() { // Avoid having two refreshing processes at the same time if (!refreshingOutput) { // Close the outConnection if (outConnection != null) { try { outConnection.close(); } catch (Exception e) {} outConnection = null; if (myInputManager.isConnected() && myConnectionListener != null) { myConnectionListener.handleDisconnection(); } } // Asynchronously try to recreate the outConnection refreshingOutput = true; Thread t = new Thread(this); t.start(); } } /** Asynchronously restore the OUT connection */ public void run() { connect(OUT); refreshingOutput = false; } private void connect(byte type) { int jicpErrorCnt = 0; int cnt = 0; long startTime = System.currentTimeMillis(); while (active) { try { if (myLogger.isLoggable(Logger.INFO)) { myLogger.log(Logger.INFO, "Connecting to "+mediatorTA.getHost()+":"+mediatorTA.getPort()+" "+type+"("+cnt+")"); } Connection c = new JICPConnection(mediatorTA); JICPPacket pkt = new JICPPacket(JICPProtocol.CONNECT_MEDIATOR_TYPE, JICPProtocol.DEFAULT_INFO, mediatorTA.getFile(), new byte[]{type}); writePacket(pkt, c); pkt = c.readPacket(); if (pkt.getType() == JICPProtocol.ERROR_TYPE) { c.close(); // The JICPServer didn't find my Mediator anymore. There was probably // a fault. Try to recreate the BackEnd if (type == OUT) { // BackEnd recreation is attempted only when restoring the // OUT connection since the BackEnd uses the connection that // creates it to receive outgoing commands. Moreover this ensures // end up with the INP and OUT connections pointing to different // hosts. try { c = createBackEnd(); handleReconnection(c, type); } catch (IMTPException imtpe) { handleError(); } } else { // In case the outConnection still appears to be OK, refresh it refreshOut(); // Then behave as if there was an IOException --> go to sleep for a while and try again throw new IOException(); } } else { // The local-host address may have changed props.setProperty(JICPProtocol.LOCAL_HOST_KEY, new String(pkt.getData())); if (myLogger.isLoggable(Logger.INFO)) { myLogger.log(Logger.INFO, "Connect OK"); } handleReconnection(c, type); } return; } catch (IOException ioe) { if (myLogger.isLoggable(Logger.INFO)) { myLogger.log(Logger.INFO, "Connect failed "+ioe.toString()); } cnt++; if ((System.currentTimeMillis() - startTime) > maxDisconnectionTime) { handleError(); return; } else { // Wait a bit before trying again try { Thread.sleep(retryTime); } catch (Exception e) {} } } } } protected synchronized void handleReconnection(Connection c, byte type) { boolean transition = false; if (type == INP) { myInputManager.setConnection(c); if (outConnection != null) { transition = true; } } else if (type == OUT) { outConnection = c; // The Output connection is available again --> // Activate postponed commands flushing waitingForFlush = myStub.flush(); if (myInputManager.isConnected()) { transition = true; } } if (transition && myConnectionListener != null) { myConnectionListener.handleReconnection(); } } private void handleError() { myLogger.log(Logger.SEVERE, "Can't reconnect ("+System.currentTimeMillis()+")"); if (myConnectionListener != null) { myConnectionListener.handleReconnectionFailure(); } myInputManager.close(); active = false; } private String[] parseBackEndAddresses(String addressesText) { Vector addrs = new Vector(); if(addressesText != null && !addressesText.equals("")) { // Copy the string with the specifiers into an array of char char[] addressesChars = new char[addressesText.length()]; addressesText.getChars(0, addressesText.length(), addressesChars, 0); // Create the StringBuffer to hold the first address StringBuffer sbAddr = new StringBuffer(); int i = 0; while(i < addressesChars.length) { char c = addressesChars[i]; if((c != ',') && (c != ';') && (c != ' ') && (c != '\n') && (c != '\t')) { sbAddr.append(c); } else { // The address is terminated --> Add it to the result list String tmp = sbAddr.toString().trim(); if (tmp.length() > 0) { // Add the Address to the list addrs.addElement(tmp); } // Create the StringBuffer to hold the next specifier sbAddr = new StringBuffer(); } ++i; } // Handle the last specifier String tmp = sbAddr.toString().trim(); if(tmp.length() > 0) { // Add the Address to the list addrs.addElement(tmp); } } // Convert the list into an array of strings String[] result = new String[addrs.size()]; for(int i = 0; i < result.length; i++) { result[i] = (String)addrs.elementAt(i); } return result; } protected void writePacket(JICPPacket pkt, Connection c) throws IOException { c.writePacket(pkt); if (Thread.currentThread() == terminator) { myInputManager.close(); } else { updateKeepAlive(); } } // Keep-alive mechanism management // Mutual exclusion with doTimeOut() private synchronized void updateKeepAlive() { if (keepAliveTime > 0) { TimerDispatcher td = TimerDispatcher.getTimerDispatcher(); if (kaTimer != null) { td.remove(kaTimer); } kaTimer = td.add(new Timer(System.currentTimeMillis()+keepAliveTime, this)); } } // Mutual exclusion with updateKeepAlive() public synchronized void doTimeOut(Timer t) { if (t == kaTimer) { sendKeepAlive(); } } // Mutual exclusion with dispatch() protected synchronized void sendKeepAlive() { // Send a keep-alive packet to the BackEnd if (outConnection != null) { JICPPacket pkt = new JICPPacket(JICPProtocol.KEEP_ALIVE_TYPE, JICPProtocol.DEFAULT_INFO, null); try { writePacket(pkt, outConnection); pkt = outConnection.readPacket(); if ((pkt.getInfo() & JICPProtocol.RECONNECT_INFO) != 0) { // The BackEnd is considering the input connection no longer valid refreshInp(); } } catch (IOException ioe) { myLogger.log(Logger.FINE, "KA error "+ioe.toString()); refreshOut(); } } } }
package net.mcft.copy.backpacks; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos.MutableBlockPos; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; import net.mcft.copy.backpacks.WearableBackpacks; import net.mcft.copy.backpacks.api.BackpackHelper; import net.mcft.copy.backpacks.api.BackpackRegistry; import net.mcft.copy.backpacks.api.IBackpack; import net.mcft.copy.backpacks.api.IBackpackData; import net.mcft.copy.backpacks.api.IBackpackType; import net.mcft.copy.backpacks.container.SlotArmorBackpack; import net.mcft.copy.backpacks.misc.BackpackCapability; import net.mcft.copy.backpacks.misc.util.WorldUtils; import net.mcft.copy.backpacks.network.MessageUpdateStack; public class ProxyCommon { public void preInit() { MinecraftForge.EVENT_BUS.register(this); CapabilityManager.INSTANCE.register(IBackpack.class, new BackpackCapability.Storage(), BackpackCapability.class); } public void init() { } // Attaching / sending capability @SubscribeEvent public void onAttachCapabilitiesEntity(AttachCapabilitiesEvent<Entity> event) { // Give entities that can wear backpacks the backpack capability. if (BackpackRegistry.canEntityWearBackpacks(event.getObject())) event.addCapability(BackpackCapability.IDENTIFIER, new BackpackCapability.Provider((EntityLivingBase)event.getObject())); } @SubscribeEvent public void onPlayerLogin(PlayerLoggedInEvent event) { sendBackpackStack(event.player, event.player); } @SubscribeEvent public void onPlayerChangedDimensionEvent(PlayerChangedDimensionEvent event) { sendBackpackStack(event.player, event.player); } @SubscribeEvent public void onPlayerRespawn(PlayerRespawnEvent event) { sendBackpackStack(event.player, event.player); } @SubscribeEvent public void onPlayerStartTracking(PlayerEvent.StartTracking event) { sendBackpackStack(event.getTarget(), event.getEntityPlayer()); } private void sendBackpackStack(Entity carrier, EntityPlayer player) { BackpackCapability backpack = (BackpackCapability)BackpackHelper.getBackpack(carrier); if (backpack != null) WearableBackpacks.CHANNEL.sendTo( new MessageUpdateStack(carrier, backpack.stack), player); } // Backpack interactions / events @SubscribeEvent public void onPlayerInteractBlock(PlayerInteractEvent.RightClickBlock event) { // When players sneak-right-click the ground with an // empty hand, place down their equipped backpack. EntityPlayer player = event.getEntityPlayer(); World world = event.getWorld(); if (!player.isSneaking() || (player.getHeldItemMainhand() != null)) return; IBackpack backpack = BackpackHelper.getBackpack(player); if (backpack == null) return; if (event.getHand() == EnumHand.MAIN_HAND) { // Since cancelling the event will not prevent the RightClickBlock event // for the other hand from being fired, we need to cancel this one first // and wait for the OFF_HAND one to actually do the unequipping, so we // can also cancel that. Otherwise, the OFF_HAND interaction would cause // items to be used or blocks being activated. event.setCanceled(true); return; } // Try place the equipped backpack on the ground by using it. Also takes // care of setting the tile entity stack and data as well as unequipping. // See ItemBackpack.onItemUse. if (backpack.getStack().onItemUse( player, world, event.getPos(), null, event.getFace(), 0.5F, 0.5F, 0.5F) == EnumActionResult.SUCCESS) { player.swingArm(EnumHand.MAIN_HAND); event.setCanceled(true); } } @SubscribeEvent public void onEntityInteract(PlayerInteractEvent.EntityInteract event) { // When players right-click equipped backpacks, interact with them. if (!WearableBackpacks.CONFIG.enableEquippedInteraction.getValue() || !(event.getTarget() instanceof EntityLivingBase)) return; EntityPlayer player = event.getEntityPlayer(); EntityLivingBase target = (EntityLivingBase)event.getTarget(); BackpackCapability backpack = (BackpackCapability)target.getCapability(IBackpack.CAPABILITY, null); if ((backpack == null) || !BackpackHelper.canInteractWithEquippedBackpack(player, target)) return; IBackpackType type = backpack.getType(); if (type == null) { WearableBackpacks.LOG.error("Backpack type was null when accessing equipped backpack"); return; } if (!player.worldObj.isRemote && (backpack.getData() == null)) { IBackpackData data = type.createBackpackData(); if (data != null) { // Only show this error message if the backpack type is supposed to have backpack data. // Some backpacks might not need any to function, for example an ender backpack. WearableBackpacks.LOG.error("Backpack data was null when accessing equipped backpack"); backpack.setData(data); } } type.onEquippedInteract(player, target, backpack); } @SubscribeEvent public void onLivingUpdate(LivingUpdateEvent event) { // Update equipped backpacks and check // if they've been removed somehow. EntityLivingBase entity = event.getEntityLiving(); if (!BackpackRegistry.canEntityWearBackpacks(entity)) return; BackpackCapability backpack = (BackpackCapability)entity .getCapability(IBackpack.CAPABILITY, null); if (backpack == null) return; if (backpack.isChestArmor()) { if (entity instanceof EntityPlayer) SlotArmorBackpack.replace((EntityPlayer)entity); if (backpack.getStack() == null) { // Backpack has been removed somehow. backpack.getType().onFaultyRemoval(entity, backpack); backpack.setStack(null); } } if (backpack.getStack() != null) { backpack.getType().onEquippedTick(entity, backpack); if (entity.worldObj.isRemote) BackpackHelper.updateLidTicks(backpack, entity.posX, entity.posY + 1.0, entity.posZ); } } @SubscribeEvent public void onLivingDeath(LivingDeathEvent event) { // If an entity wearing a backpack dies, try // to place it as a block, or drop the items. EntityLivingBase entity = event.getEntityLiving(); World world = entity.worldObj; if (world.isRemote) return; BackpackCapability backpack = (BackpackCapability)BackpackHelper.getBackpack(entity); if (backpack == null) return; // If keep inventory is on, keep the backpack capability so we // can copy it over to the new player entity in onPlayerClone. EntityPlayer player = ((entity instanceof EntityPlayer) ? (EntityPlayer)entity : null); boolean keepInventory = world.getGameRules().getBoolean("keepInventory"); if ((player != null) && keepInventory) return; // Attempt to place the backpack as a block instead of dropping the items. if (WearableBackpacks.CONFIG.dropAsBlockOnDeath.getValue()) { List<BlockCoord> coords = new ArrayList<BlockCoord>(); for (int x = -2; x <= 2; x++) for (int z = -2; z <= 2; z++) coords.add(new BlockCoord(entity, x, z)); // Try to place the backpack on the ground nearby, // or look for a ground above or below to place it. Collections.sort(coords, new Comparator<BlockCoord>() { @Override public int compare(BlockCoord o1, BlockCoord o2) { if (o1.distance < o2.distance) return -1; else if (o1.distance > o2.distance) return 1; else return 0; } }); while (!coords.isEmpty()) { Iterator<BlockCoord> iter = coords.iterator(); while (iter.hasNext()) { BlockCoord coord = iter.next(); // Attempt to place and unequip the backpack at // this coordinate. If successful, we're done here. if (BackpackHelper.placeBackpack(world, coord, backpack.getStack(), entity)) return; boolean replacable = world.getBlockState(coord).getBlock().isReplaceable(world, coord); coord.add(0, (replacable ? -1 : 1), 0); coord.moved += (replacable ? 1 : 5); if ((coord.getY() <= 0) || (coord.getY() > world.getHeight()) || (coord.moved > 24 - coord.distance * 4)) iter.remove(); } } } // In the case of regular backpacks, this causes their contents to be dropped. backpack.getType().onDeath(entity, backpack); // Drop the backpack as an item and remove it from the entity. if (backpack.getStack() != null) WorldUtils.dropStackFromEntity(entity, backpack.getStack(), 4.0F); BackpackHelper.setEquippedBackpack(entity, null, null); } // Would use a method local class but "extractRangemapReplacedMain" doesn't like that. private static class BlockCoord extends MutableBlockPos { public double distance; public int moved = 0; public BlockCoord(Entity entity, int x, int z) { super((int)entity.posX + x, (int)entity.posY, (int)entity.posZ + z); distance = Math.sqrt(Math.pow(getX() + 0.5 - entity.posX, 2) + Math.pow(getY() + 0.5 - entity.posY, 2) + Math.pow(getZ() + 0.5 - entity.posZ, 2)); } } @SubscribeEvent public void onPlayerClone(PlayerEvent.Clone event) { // This comes into play when the "keepInventory" gamerule is on. // In that case, onLivingDeath will keep the backpack information, // so we can transfer it to the new player entity. IBackpack originalBackpack = BackpackHelper.getBackpack(event.getOriginal()); if (originalBackpack == null) return; EntityPlayer player = event.getEntityPlayer(); IBackpack clonedBackpack = player.getCapability(IBackpack.CAPABILITY, null); clonedBackpack.setStack(originalBackpack.getStack()); clonedBackpack.setData(originalBackpack.getData()); } }
package net.sf.kerner.utils.math; public enum DoubleUnit implements PrefixableDouble { PICO { @Override public double toPicos(double units) { return units; } @Override public double toNanos(double units) { return units / (C1 / C0); } @Override public double toMicros(double units) { return units / (C2 / C0); } @Override public double toMillis(double units) { return units / (C3 / C0); } @Override public double toUnits(double units) { return units / (C4 / C0); } @Override public double toKilos(double units) { return units / (C5 / C0); } @Override public double toMegas(double units) { return units / (C6 / C0); } @Override public double toGigas(double units) { return units / (C7 / C0); } @Override public double toTeras(double units) { return units / (C8 / C0); } @Override public double convert(double units, DoubleUnit unit) { return unit.toPicos(units); } }, NANO { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C1 / C0); } @Override public double toNanos(double units) { return units; } @Override public double toMicros(double units) { return units / (C2 / C1); } @Override public double toMillis(double units) { return units / (C3 / C1); } @Override public double toUnits(double units) { return units / (C4 / C1); } @Override public double toKilos(double units) { return units / (C5 / C1); } @Override public double toMegas(double units) { return units / (C6 / C1); } @Override public double toGigas(double units) { return units / (C7 / C1); } @Override public double toTeras(double units) { return units / (C8 / C1); } @Override public double convert(double units, DoubleUnit unit) { return unit.toNanos(units); } }, MICRO { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C2 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C2 / C1); } @Override public double toMicros(double units) { return units; } @Override public double toMillis(double units) { return units / (C3 / C2); } @Override public double toUnits(double units) { return units / (C4 / C2); } @Override public double toKilos(double units) { return units / (C5 / C2); } @Override public double toMegas(double units) { return units / (C6 / C2); } @Override public double toGigas(double units) { return units / (C7 / C2); } @Override public double toTeras(double units) { return units / (C8 / C2); } @Override public double convert(double units, DoubleUnit unit) { return unit.toMicros(units); } }, MILLI { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C3 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C3 / C1); } @Override public double toMicros(double units) { return ArithmeticSavety.multiply(units, C3 / C2); } @Override public double toMillis(double units) { return units; } @Override public double toUnits(double units) { return units / (C4 / C3); } @Override public double toKilos(double units) { return units / (C5 / C3); } @Override public double toMegas(double units) { return units / (C6 / C3); } @Override public double toGigas(double units) { return units / (C7 / C3); } @Override public double toTeras(double units) { return units / (C8 / C3); } @Override public double convert(double units, DoubleUnit unit) { return unit.toMillis(units); } }, UNIT { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C4 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C4 / C1); } @Override public double toMicros(double units) { return ArithmeticSavety.multiply(units, C4 / C2); } @Override public double toMillis(double units) { return ArithmeticSavety.multiply(units, C4 / C3); } @Override public double toUnits(double units) { return units; } @Override public double toKilos(double units) { return units / (C5 / C4); } @Override public double toMegas(double units) { return units / (C6 / C4); } @Override public double toGigas(double units) { return units / (C7 / C4); } @Override public double toTeras(double units) { return units / (C8 / C4); } @Override public double convert(double units, DoubleUnit unit) { return unit.toUnits(units); } }, KILO { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C5 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C5 / C1); } @Override public double toMicros(double units) { return ArithmeticSavety.multiply(units, C5 / C2); } @Override public double toMillis(double units) { return ArithmeticSavety.multiply(units, C5 / C3); } @Override public double toUnits(double units) { return ArithmeticSavety.multiply(units, C5 / C4); } @Override public double toKilos(double units) { return units; } @Override public double toMegas(double units) { return units / (C6 / C5); } @Override public double toGigas(double units) { return units / (C7 / C5); } @Override public double toTeras(double units) { return units / (C8 / C5); } @Override public double convert(double units, DoubleUnit unit) { return unit.toKilos(units); } }, MEGA { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C6 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C6 / C1); } @Override public double toMicros(double units) { return ArithmeticSavety.multiply(units, C6 / C2); } @Override public double toMillis(double units) { return ArithmeticSavety.multiply(units, C6 / C3); } @Override public double toUnits(double units) { return ArithmeticSavety.multiply(units, C6 / C4); } @Override public double toKilos(double units) { return ArithmeticSavety.multiply(units, C6 / C5); } @Override public double toMegas(double units) { return units; } @Override public double toGigas(double units) { return units / (C7 / C6); } @Override public double toTeras(double units) { return units / (C8 / C6); } @Override public double convert(double units, DoubleUnit unit) { return unit.toMegas(units); } }, GIGA { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C7 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C7 / C1); } @Override public double toMicros(double units) { return ArithmeticSavety.multiply(units, C7 / C2); } @Override public double toMillis(double units) { return ArithmeticSavety.multiply(units, C7 / C3); } @Override public double toUnits(double units) { return ArithmeticSavety.multiply(units, C7 / C4); } @Override public double toKilos(double units) { return ArithmeticSavety.multiply(units, C7 / C5); } @Override public double toMegas(double units) { return ArithmeticSavety.multiply(units, C7 / C6); } @Override public double toGigas(double units) { return units; } @Override public double toTeras(double units) { return units / (C8 / C7); } @Override public double convert(double units, DoubleUnit unit) { return unit.toGigas(units); } }, TERA { @Override public double toPicos(double units) { return ArithmeticSavety.multiply(units, C8 / C0); } @Override public double toNanos(double units) { return ArithmeticSavety.multiply(units, C8 / C1); } @Override public double toMicros(double units) { return ArithmeticSavety.multiply(units, C8 / C2); } @Override public double toMillis(double units) { return ArithmeticSavety.multiply(units, C8 / C3); } @Override public double toUnits(double units) { return ArithmeticSavety.multiply(units, C8 / C4); } @Override public double toKilos(double units) { return ArithmeticSavety.multiply(units, C8 / C5); } @Override public double toMegas(double units) { return ArithmeticSavety.multiply(units, C8 / C6); } @Override public double toGigas(double units) { return ArithmeticSavety.multiply(units, C8 / C7); } @Override public double toTeras(double units) { return units; } @Override public double convert(double units, DoubleUnit unit) { return unit.toTeras(units); } }; static final double C0 = 1; static final double C1 = C0 * 1000; static final double C2 = C1 * 1000; static final double C3 = C2 * 1000; static final double C4 = C3 * 1000; static final double C5 = C4 * 1000; static final double C6 = C5 * 1000; static final double C7 = C6 * 1000; static final double C8 = C7 * 1000; public double toPicos(double units) { throw new AbstractMethodError(); } public double toNanos(double units) { throw new AbstractMethodError(); } /** * * Equivalent to UNIT.convert(units, this). * * @param units * the units to convert * @return the converted units */ public double toMicros(double units) { throw new AbstractMethodError(); } public double toMillis(double units) { throw new AbstractMethodError(); } public double toUnits(double units) { throw new AbstractMethodError(); } public double toKilos(double units) { throw new AbstractMethodError(); } public double toMegas(double units) { throw new AbstractMethodError(); } public double toGigas(double units) { throw new AbstractMethodError(); } public double toTeras(double units) { throw new AbstractMethodError(); } public double convert(double units, DoubleUnit unit) { throw new AbstractMethodError(); } }
package net.ucanaccess.converters; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.sql.Timestamp; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Currency; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import net.ucanaccess.converters.TypesMap.AccessType; import net.ucanaccess.ext.FunctionType; import net.ucanaccess.jdbc.UcanaccessSQLException; import net.ucanaccess.jdbc.UcanaccessSQLException.ExceptionMessages; import com.healthmarketscience.jackcess.DataType; public class Functions { private static Double rnd; private static Double lastRnd; public final static ArrayList<SimpleDateFormat> LDF = new ArrayList<SimpleDateFormat>(); public final static ArrayList<Boolean> LDFY = new ArrayList<Boolean>(); public final static RegionalSettings reg=new RegionalSettings(); private final static double APPROX=0.00000001; private static boolean pointDateSeparator; static { pointDateSeparator=getPointDateSeparator(); addDateP("yyyy-MM-dd h:m:s a"); addDateP("yyyy-MM-dd H:m:s"); addDateP("yyyy-MM-dd"); addDateP("yyyy/MM/dd h:m:s a"); addDateP("yyyy/MM/dd H:m:s"); addDateP("yyyy/MM/dd"); addDateP(reg.getGeneralPattern(),true); addDateP(reg.getLongDatePattern(),true); addDateP(reg.getMediumDatePattern(),true); addDateP(reg.getShortDatePattern(),true); if(!Locale.getDefault().equals(Locale.US)){ RegionalSettings s=new RegionalSettings(Locale.US); addDateP(s.getGeneralPattern(),false); addDateP(s.getLongDatePattern(),true); addDateP(s.getMediumDatePattern(),true); addDateP(s.getShortDatePattern(),true); } addDateP("MMM dd,yyyy"); addDateP("MM dd,yyyy"); addDateP("MMM dd hh:mm:ss",false,true); addDateP("MM dd hh:mm:ss",false,true); addDateP("MMM yy hh:mm:ss"); addDateP("MM yy hh:mm:ss"); //locale is MM/dd/yyyy like in US but user is trying to parse something like 22/11/2003 addDateP("dd/MM/yyyy h:m:s a",true); addDateP("dd/MM/yyyy H:m:s",true); addDateP("dd/MM/yyyy",true); } private static boolean getPointDateSeparator(){ String[] dfsp=new String[]{reg.getGeneralPattern(),reg.getLongDatePattern(),reg.getMediumDatePattern(),reg.getShortDatePattern()}; for(String pattern:dfsp){ if(pattern.indexOf(".")>0&&pattern.indexOf("h.")<0&&pattern.indexOf("H.")<0){ return true; } } return false; } private static void addDateP(String sdfs){ addDateP(sdfs,false,false); } private static void addDateP(String sdfs,boolean euristic){ addDateP(sdfs,euristic,false); } private static void addTogglePattern(String pattern){ if(pattern.indexOf("/")>0){ addDateP(pattern.replaceAll("/","-")); if(pointDateSeparator){ addDateP(pattern.replaceAll("/",".")); } }else if(pattern.indexOf("-")>0){ addDateP(pattern.replaceAll(Pattern.quote("-"),"/")); if(pointDateSeparator){ addDateP(pattern.replaceAll(Pattern.quote("-"),".")); } }else if(pattern.indexOf(".")>0&&pattern.indexOf("h.")<0&&pattern.indexOf("H.")<0){ addDateP(pattern.replaceAll(Pattern.quote("."),"/")); } } private static void addDateP( String sdfs,boolean euristic,boolean yearOverride){ if(euristic){ if(sdfs.indexOf("a")<0&&sdfs.indexOf("H")>0){ String chg=sdfs.replaceAll("H","h")+" a"; addDateP(chg); addTogglePattern(chg); } } SimpleDateFormat sdf=new SimpleDateFormat(sdfs); sdf.setLenient(false); if("true".equalsIgnoreCase(reg.getRS())){ DateFormatSymbols df=new DateFormatSymbols(); df.setAmPmStrings(new String[]{"AM","PM"}); sdf.setDateFormatSymbols(df); } LDF.add(sdf); LDFY.add(yearOverride); if(euristic){ addTogglePattern(sdfs); if(sdfs.endsWith(" a")&&sdfs.indexOf("h")>0){ String chg=sdfs.substring(0,sdfs.length()-2).trim().replaceAll("h","H"); addDateP(chg); addTogglePattern(chg); } } } @FunctionType(functionName = "ASC", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG) public static Integer asc(String s) { if (s == null || s.length() == 0) return null; return (int) s.charAt(0); } @FunctionType(functionName = "EQUALS", argumentTypes = { AccessType.COMPLEX,AccessType.COMPLEX }, returnType = AccessType.YESNO) public static Boolean equals(Object obj1,Object obj2) { if(obj1==null||obj2==null)return false; if(!obj1.getClass().equals(obj2.getClass())) return false; if(obj1.getClass().isArray()){ return Arrays.equals((Object[])obj1,(Object[])obj2); } return obj1.equals(obj2); } @FunctionType(functionName = "EQUALSIGNOREORDER", argumentTypes = { AccessType.COMPLEX,AccessType.COMPLEX }, returnType = AccessType.YESNO) public static Boolean equalsIgnoreOrder(Object obj1,Object obj2) { if(obj1==null||obj2==null)return false; if(!obj1.getClass().equals(obj2.getClass())) return false; if(obj1.getClass().isArray()){ List<Object> lo1= Arrays.asList((Object[])obj1); List<Object> lo2= Arrays.asList((Object[])obj2); return lo1.containsAll(lo2) && lo2.containsAll(lo1); } return obj1.equals(obj2); } @FunctionType(functionName = "CONTAINS", argumentTypes = { AccessType.COMPLEX,AccessType.COMPLEX }, returnType = AccessType.YESNO) public static Boolean contains(Object obj1,Object obj2) { if(obj1==null||obj2==null)return false; if(!obj1.getClass().isArray()) return false; List<Object> lo= Arrays.asList((Object[])obj1); List<Object> arg=obj2.getClass().isArray()? Arrays.asList((Object[])obj2): Arrays.asList(new Object[]{obj2}); return lo.containsAll(arg); } @FunctionType(functionName = "ATN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double atn(double v) { return Math.atan(v); } @FunctionType(functionName = "SQR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double sqr(double v) { return Math.sqrt(v); } @FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.YESNO) public static boolean cbool(BigDecimal value) { return cbool((Object) value); } @FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.YESNO }, returnType = AccessType.YESNO) public static boolean cbool(Boolean value) { return cbool((Object) value); } private static boolean cbool(Object obj) { boolean r = (obj instanceof Boolean) ? (Boolean) obj : (obj instanceof String) ? Boolean.valueOf((String) obj) : (obj instanceof Number) ? ((Number) obj) .doubleValue() != 0 : false; return r; } @FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean cbool(String value) { return cbool((Object) value); } @FunctionType(functionName = "CCUR", argumentTypes = { AccessType.CURRENCY }, returnType = AccessType.CURRENCY) public static BigDecimal ccur(BigDecimal value) throws UcanaccessSQLException { return value.setScale(4, BigDecimal.ROUND_HALF_UP);// .doubleValue(); } @FunctionType(functionName = "CDATE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DATETIME) public static Timestamp cdate(String dt) { return dateValue(dt,false); } @FunctionType(functionName = "CDBL", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double cdbl(Double value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CDEC", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double cdec(Double value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CINT", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.INTEGER) public static Short cint(Double value) throws UcanaccessSQLException { return new BigDecimal((long) Math.floor(value + 0.499999999999999d)) .shortValueExact(); } @FunctionType(functionName = "CINT", argumentTypes = { AccessType.YESNO }, returnType = AccessType.INTEGER) public static Short cint(boolean value) throws UcanaccessSQLException { return (short)(value?-1:0); } @FunctionType(functionName = "CLONG", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG) public static Integer clong(Double value) throws UcanaccessSQLException { return clng(value); } @FunctionType(functionName = "CLONG", argumentTypes = { AccessType.LONG }, returnType = AccessType.LONG) public static Integer clong(Integer value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CLNG", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG) public static Integer clng(Double value) throws UcanaccessSQLException { return (int) Math.floor(value + 0.5d); } @FunctionType(functionName = "CLNG", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG) public static Integer clng( String value) throws UcanaccessSQLException { return clng(Double.parseDouble(value)); } @FunctionType(functionName = "CLNG", argumentTypes = { AccessType.LONG }, returnType = AccessType.LONG) public static Integer clng(Integer value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CLONG", argumentTypes = { AccessType.YESNO }, returnType = AccessType.LONG) public static Integer clong(boolean value) throws UcanaccessSQLException { return value?-1:0; } @FunctionType(functionName = "CSIGN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.SINGLE) public static double csign(double value) { MathContext mc = new MathContext(7); return new BigDecimal(value, mc).doubleValue(); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.YESNO }, returnType = AccessType.MEMO) public static String cstr(Boolean value) throws UcanaccessSQLException { return cstr((Object) value); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.TEXT }, returnType = AccessType.MEMO) public static String cstr(String value) throws UcanaccessSQLException { return value; } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.MEMO) public static String cstr(double value) throws UcanaccessSQLException { return cstr((Object) value); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.LONG }, returnType = AccessType.MEMO) public static String cstr(int value) throws UcanaccessSQLException { return cstr((Object) value); } public static String cstr(Object value) throws UcanaccessSQLException { return value == null ? null : format(value.toString(), "",true); } @FunctionType(functionName = "CSTR", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.MEMO) public static String cstr(Timestamp value) throws UcanaccessSQLException { return value == null ? null : format(value, "general date"); } @FunctionType(functionName = "CVAR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.MEMO) public static String cvar(Double value) throws UcanaccessSQLException { return format(value, "general number"); } @FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Date dateAdd(String intv, int vl, Date dt) throws UcanaccessSQLException { if (dt == null || intv == null) return null; Calendar cl = Calendar.getInstance(); cl.setTime(dt); if (intv.equalsIgnoreCase("yyyy")) { cl.add(Calendar.YEAR, vl); } else if (intv.equalsIgnoreCase("q")) { cl.add(Calendar.MONTH, vl * 3); } else if (intv.equalsIgnoreCase("y") || intv.equalsIgnoreCase("d")) { cl.add(Calendar.DAY_OF_YEAR, vl); } else if (intv.equalsIgnoreCase("m")) { cl.add(Calendar.MONTH, vl); } else if (intv.equalsIgnoreCase("w")) { cl.add(Calendar.DAY_OF_WEEK, vl); } else if (intv.equalsIgnoreCase("ww")) { cl.add(Calendar.WEEK_OF_YEAR, vl); } else if (intv.equalsIgnoreCase("h")) { cl.add(Calendar.HOUR, vl); } else if (intv.equalsIgnoreCase("n")) { cl.add(Calendar.MINUTE, vl); } else if (intv.equalsIgnoreCase("s")) { cl.add(Calendar.SECOND, vl); } else throw new UcanaccessSQLException( ExceptionMessages.INVALID_INTERVAL_VALUE); return (dt instanceof Timestamp) ? new Timestamp(cl.getTimeInMillis()) : new java.sql.Date(cl.getTimeInMillis()); } @FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Timestamp dateAdd(String intv, int vl, Timestamp dt) throws UcanaccessSQLException { return (Timestamp) dateAdd(intv, vl, (Date) dt); } @FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.MEMO }, returnType = AccessType.DATETIME) public static Timestamp dateAdd(String intv, int vl, String dt) throws UcanaccessSQLException { return (Timestamp) dateAdd(intv, vl, (Date) dateValue(dt,false)); } @FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer dateDiff(String intv, String dt1, String dt2) throws UcanaccessSQLException{ return dateDiff(intv,dateValue(dt1,false),dateValue(dt2,false)); } @FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer dateDiff(String intv, String dt1, Timestamp dt2) throws UcanaccessSQLException{ return dateDiff(intv,dateValue(dt1,false),dt2); } @FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer dateDiff(String intv, Timestamp dt1, String dt2) throws UcanaccessSQLException{ return dateDiff(intv,dt1,dateValue(dt2,false)); } @FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer dateDiff(String intv, Timestamp dt1, Timestamp dt2) throws UcanaccessSQLException { if (dt1 == null || intv == null || dt2 == null) return null; Calendar clMin = Calendar.getInstance(); Calendar clMax = Calendar.getInstance(); int sign = dt1.after(dt2) ? -1 : 1; if (sign == 1) { clMax.setTime(dt2); clMin.setTime(dt1); } else { clMax.setTime(dt1); clMin.setTime(dt2); } clMin.set(Calendar.MILLISECOND, 0); clMax.set(Calendar.MILLISECOND, 0); Integer result; if (intv.equalsIgnoreCase("yyyy")) { result = clMax.get(Calendar.YEAR) - clMin.get(Calendar.YEAR); } else if (intv.equalsIgnoreCase("q")) { result = dateDiff("yyyy", dt1, dt2) * 4 + (clMax.get(Calendar.MONTH) - clMin.get(Calendar.MONTH)) / 3; } else if (intv.equalsIgnoreCase("y") || intv.equalsIgnoreCase("d")) { result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / (1000 * 60 * 60 * 24))); } else if (intv.equalsIgnoreCase("m")) { result = dateDiff("yyyy", dt1, dt2) * 12 + (clMax.get(Calendar.MONTH) - clMin.get(Calendar.MONTH)); } else if (intv.equalsIgnoreCase("w") || intv.equalsIgnoreCase("ww")) { result = (int) Math .floor(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / (1000 * 60 * 60 * 24 * 7))); } else if (intv.equalsIgnoreCase("h")) { result = (int) Math .round(((double) (clMax.getTime().getTime() - clMin .getTime().getTime())) / (1000d * 60 * 60)); } else if (intv.equalsIgnoreCase("n")) { result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / (1000 * 60))); } else if (intv.equalsIgnoreCase("s")) { result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin .getTimeInMillis()) / 1000)); } else throw new UcanaccessSQLException( ExceptionMessages.INVALID_INTERVAL_VALUE); return result * sign; } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer datePart(String intv, String dt, Integer firstDayOfWeek) throws UcanaccessSQLException { return datePart( intv, dateValue( dt,false), firstDayOfWeek); } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.LONG }, returnType = AccessType.LONG) public static Integer datePart(String intv, Timestamp dt, Integer firstDayOfWeek) throws UcanaccessSQLException { Integer ret = (intv.equalsIgnoreCase("ww")) ? datePart(intv, dt, firstDayOfWeek, 1) : datePart(intv, dt); if (intv.equalsIgnoreCase("w") && firstDayOfWeek > 1) { Calendar cl = Calendar.getInstance(); cl.setTime(dt); ret = cl.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek + 1; if (ret <= 0) ret = 7 + ret; } return ret; } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG, AccessType.LONG},returnType = AccessType.LONG) public static Integer datePart(String intv, String dt, Integer firstDayOfWeek, Integer firstWeekOfYear) throws UcanaccessSQLException { return datePart( intv, dateValue( dt,false), firstDayOfWeek, firstWeekOfYear); } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.DATETIME, AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG) public static Integer datePart(String intv, Timestamp dt, Integer firstDayOfWeek, Integer firstWeekOfYear) throws UcanaccessSQLException { Integer ret = datePart(intv, dt); if (intv.equalsIgnoreCase("ww") && (firstWeekOfYear > 1 || firstDayOfWeek > 1)) { Calendar cl = Calendar.getInstance(); cl.setTime(dt); cl.set(Calendar.MONTH, Calendar.JANUARY); cl.set(Calendar.DAY_OF_MONTH, 1); Calendar cl1 = Calendar.getInstance(); cl1.setTime(dt); if (firstDayOfWeek == 0) firstDayOfWeek = 1; int dow = cl.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek + 1; if (dow <= 0) { dow = 7 + dow; if (cl1.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek >= 0) ret++; } if (dow > 4 && firstWeekOfYear == 2) { ret } if (dow > 1 && firstWeekOfYear == 3) { ret } } return ret; } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer datePart(String intv, String dt) throws UcanaccessSQLException{ return datePart( intv, dateValue( dt,false)); } @FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = { AccessType.MEMO, AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer datePart(String intv, Timestamp dt) throws UcanaccessSQLException { if (dt == null || intv == null) return null; Calendar cl = Calendar.getInstance(Locale.US); cl.setTime(dt); if (intv.equalsIgnoreCase("yyyy")) { return cl.get(Calendar.YEAR); } else if (intv.equalsIgnoreCase("q")) { return (int) Math.ceil((cl.get(Calendar.MONTH) + 1) / 3d); } else if (intv.equalsIgnoreCase("d")) { return cl.get(Calendar.DAY_OF_MONTH); } else if (intv.equalsIgnoreCase("y")) { return cl.get(Calendar.DAY_OF_YEAR); } else if (intv.equalsIgnoreCase("m")) { return cl.get(Calendar.MONTH) + 1; } else if (intv.equalsIgnoreCase("ww")) { return cl.get(Calendar.WEEK_OF_YEAR); } else if (intv.equalsIgnoreCase("w")) { return cl.get(Calendar.DAY_OF_WEEK); } else if (intv.equalsIgnoreCase("h")) { return cl.get(Calendar.HOUR_OF_DAY); } else if (intv.equalsIgnoreCase("n")) { return cl.get(Calendar.MINUTE); } else if (intv.equalsIgnoreCase("s")) { return cl.get(Calendar.SECOND); } else throw new UcanaccessSQLException( ExceptionMessages.INVALID_INTERVAL_VALUE); } @FunctionType(functionName = "DATESERIAL", argumentTypes = { AccessType.LONG, AccessType.LONG, AccessType.LONG }, returnType = AccessType.DATETIME) public static Timestamp dateSerial(int year, int month, int day) { Calendar cl = Calendar.getInstance(); cl.setLenient(true); cl.set(Calendar.YEAR, year); cl.set(Calendar.MONTH, month - 1); cl.set(Calendar.DAY_OF_MONTH, day); cl.set(Calendar.HOUR_OF_DAY, 0); cl.set(Calendar.MINUTE, 0); cl.set(Calendar.SECOND, 0); cl.set(Calendar.MILLISECOND, 0); return new Timestamp(cl.getTime().getTime()); } @FunctionType(functionName = "DATEVALUE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DATETIME) public static Timestamp dateValue(String dt) { return dateValue( dt,true); } private static Timestamp dateValue(String dt, boolean onlyDate) { if(!"true".equalsIgnoreCase(reg.getRS())&&( !"PM".equalsIgnoreCase(reg.getPM())||!"AM".equalsIgnoreCase(reg.getAM()) )){ dt=dt.replaceAll("(?i)"+Pattern.quote(reg.getPM()), "PM").replaceAll("(?i)"+Pattern.quote(reg.getAM()),"AM"); } for (SimpleDateFormat sdf : LDF) try { Timestamp t= new Timestamp(sdf.parse(dt).getTime()); if(onlyDate)t=dateValue(t); if(LDFY.get(LDF.indexOf(sdf))){ Calendar cl = Calendar.getInstance(); int y=cl.get(Calendar.YEAR); cl.setTime(t); cl.set(Calendar.YEAR, y); t=new Timestamp(cl.getTime().getTime()); } return t; } catch (ParseException e) { } return null; } @FunctionType(functionName = "DATEVALUE", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Timestamp dateValue(Timestamp dt) { Calendar cl = Calendar.getInstance(); cl.setTime(dt); cl.set(Calendar.HOUR_OF_DAY, 0); cl.set(Calendar.MINUTE, 0); cl.set(Calendar.SECOND, 0); cl.set(Calendar.MILLISECOND, 0); return new Timestamp(cl.getTime().getTime()); } @FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.DOUBLE, AccessType.TEXT }, returnType = AccessType.TEXT) public static String format(double d, String par) throws UcanaccessSQLException { if ("percent".equalsIgnoreCase(par)) { DecimalFormat formatter = new DecimalFormat("0.00"); formatter.setRoundingMode(RoundingMode.HALF_UP); return (formatter.format(d * 100) + "%"); } if ("fixed".equalsIgnoreCase(par)) { DecimalFormat formatter = new DecimalFormat("0.00"); formatter.setRoundingMode(RoundingMode.HALF_UP); return formatter.format(d); } if ("standard".equalsIgnoreCase(par)) { DecimalFormat formatter = new DecimalFormat(" return formatter.format(d); } if ("general number".equalsIgnoreCase(par)) { DecimalFormat formatter = new DecimalFormat(); formatter.setGroupingUsed(false); return formatter.format(d); } if ("yes/no".equalsIgnoreCase(par)) { return d == 0 ? "No" : "Yes"; } if ("true/false".equalsIgnoreCase(par)) { return d == 0 ? "False" : "True"; } if ("On/Off".equalsIgnoreCase(par)) { return d == 0 ? "Off" : "On"; } if ("Scientific".equalsIgnoreCase(par)) { return String.format( "%6.2E", d); } try { DecimalFormat formatter = new DecimalFormat(par); formatter.setRoundingMode(RoundingMode.HALF_UP); return formatter.format(d); } catch (Exception e) { throw new UcanaccessSQLException(e); } } @FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.TEXT, AccessType.TEXT }, returnType = AccessType.TEXT) public static String format(String s, String par) throws UcanaccessSQLException { return format( s, par, false); } public static String format(String s, String par, boolean incl) throws UcanaccessSQLException { if (isNumeric(s)) { if(incl){ return format(Double.parseDouble(s), par); } DecimalFormat df=new DecimalFormat(); try { return format(df.parse(s).doubleValue(), par); } catch (ParseException e) { throw new UcanaccessSQLException(e); } } if (isDate(s)) { return format(dateValue(s,false), par); } return s; } private static String formatDate(Timestamp t,String pattern){ String ret= new SimpleDateFormat(pattern).format(t); if(!reg.getRS().equalsIgnoreCase("true")){ if(!reg.getAM().equals("AM")) ret=ret.replaceAll("AM", reg.getAM()); if(!reg.getPM().equals("PM")) ret=ret.replaceAll("PM",reg.getPM()); }else{ ret=ret.replaceAll( reg.getPM(),"PM"); ret=ret.replaceAll(reg.getAM(),"AM"); } return ret; } @FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.DATETIME, AccessType.TEXT }, returnType = AccessType.TEXT) public static String format(Timestamp t, String par) throws UcanaccessSQLException { if ("long date".equalsIgnoreCase(par)) { return formatDate(t,reg.getLongDatePattern()); } if ("medium date".equalsIgnoreCase(par)) { return formatDate(t,reg.getMediumDatePattern()); } if ("short date".equalsIgnoreCase(par)) { return formatDate(t,reg.getShortDatePattern()); } if ("general date".equalsIgnoreCase(par)) { return formatDate(t,reg.getGeneralPattern()); } if ("long time".equalsIgnoreCase(par)) { return formatDate(t,reg.getLongTimePattern()); } if ("medium time".equalsIgnoreCase(par)) { return formatDate(t,reg.getMediumTimePattern()); } if ("short time".equalsIgnoreCase(par)) { return formatDate(t,reg.getShortTimePattern()); } if ("q".equalsIgnoreCase(par)) { return String.valueOf(datePart(par, t)); } return new SimpleDateFormat(par.replaceAll("m", "M").replaceAll("n", "m").replaceAll("(?i)AM/PM|A/P|AMPM", "a").replaceAll("dddd", "EEEE")).format(t); } @FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO, AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.MEMO) public static String iif(boolean b, String o, String o1) { return (String)iif(b,(Object)o,(Object) o1); } @FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO, AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG) public static Integer iif(boolean b, Integer o, Integer o1) { return (Integer)iif(b,(Object)o,(Object) o1); } @FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO, AccessType.DOUBLE, AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double iif(boolean b, Double o, Double o1) { return (Double)iif(b,(Object)o,(Object) o1); } @FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO, AccessType.YESNO, AccessType.YESNO }, returnType = AccessType.YESNO) public static Boolean iif(Boolean b, Boolean o, Boolean o1) { return (Boolean)iif(b,(Object)o,(Object) o1); } @FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO, AccessType.DATETIME, AccessType.DATETIME }, returnType = AccessType.DATETIME) public static Timestamp iif(Boolean b, Timestamp o, Timestamp o1) { return (Timestamp)iif(b,(Object)o,(Object) o1); } private static Object iif(Boolean b, Object o, Object o1) { if(b==null) b=Boolean.FALSE; return b ? o : o1; } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.LONG, AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer instr(Integer start, String text, String search) { return instr(start, text, search, -1); } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.LONG, AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instr(Integer start, String text, String search, Integer compare) { start if (compare != 0) text = text.toLowerCase(); if (text.length() <= start) { return 0; } else text = text.substring(start); return text.indexOf(search) + start + 1; } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG) public static Integer instr(String text, String search) { return instr(1, text, search, -1); } @FunctionType(functionName = "INSTR", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instr(String text, String search, Integer compare) { return instr(1, text, search, compare); } @FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.TEXT, AccessType.TEXT }, returnType = AccessType.LONG) public static Integer instrrev(String text, String search) { return instrrev(text, search, -1, -1); } @FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instrrev(String text, String search, Integer start) { return instrrev(text, search, start, -1); } @FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.MEMO, AccessType.MEMO, AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG) public static Integer instrrev(String text, String search, Integer start, Integer compare) { if (compare != 0) text = text.toLowerCase(); if (text.length() <= start) { return 0; } else { if (start > 0) text = text.substring(0, start); return text.lastIndexOf(search) + 1; } } @FunctionType(functionName = "ISDATE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean isDate(String dt) { return dateValue(dt) != null; } @FunctionType(functionName = "ISDATE", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.YESNO) public static boolean isDate(Timestamp dt) { return true; } @FunctionType(namingConflict = true, functionName = "IsNull", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean isNull(String o) { return o == null; } @FunctionType(functionName = "ISNUMERIC", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.YESNO) public static boolean isNumeric(BigDecimal b) { return true; } @FunctionType(functionName = "ISNUMERIC", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO) public static boolean isNumeric(String s) { try { Currency cr=Currency.getInstance(Locale.getDefault()); if(s.startsWith(cr.getSymbol()))return isNumeric( s.substring(cr.getSymbol().length())); if(s.startsWith("+")||s.startsWith("-"))return isNumeric( s.substring(1)); DecimalFormatSymbols dfs=DecimalFormatSymbols.getInstance(); String sep=dfs.getDecimalSeparator()+""; String gs=dfs.getGroupingSeparator()+""; if(s.startsWith(gs))return false; if(s.startsWith(sep))return isNumeric( s.substring(1)); if(sep.equals(".")) s=s.replaceAll(gs,""); else s=s.replaceAll("\\.", "").replaceAll(sep,"."); new BigDecimal(s); return true; } catch (Exception e) { } return false; } @FunctionType(functionName = "LEN", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG) public static Integer len(String o) { if (o == null) return null; return new Integer(o.length()); } @FunctionType(functionName = "MID", argumentTypes = { AccessType.MEMO, AccessType.LONG }, returnType = AccessType.MEMO) public static String mid(String value, int start) { return mid(value, start, value.length()); } @FunctionType(functionName = "MID", argumentTypes = { AccessType.MEMO, AccessType.LONG, AccessType.LONG }, returnType = AccessType.MEMO) public static String mid(String value, int start, int length) { if (value == null) return null; int len = start - 1 + length; if (start < 1) throw new RuntimeException("Invalid function call"); if (len > value.length()) { len = value.length(); } return value.substring(start - 1, len); } @FunctionType(namingConflict = true, functionName = "MONTHNAME", argumentTypes = { AccessType.LONG }, returnType = AccessType.TEXT) public static String monthName(int i) throws UcanaccessSQLException { return monthName(i, false); } @FunctionType(namingConflict = true, functionName = "MONTHNAME", argumentTypes = { AccessType.LONG, AccessType.YESNO }, returnType = AccessType.TEXT) public static String monthName(int i, boolean abbr) throws UcanaccessSQLException { i if (i >= 0 && i <= 11) { DateFormatSymbols dfs = new DateFormatSymbols(); return abbr ? dfs.getShortMonths()[i] : dfs.getMonths()[i]; } throw new UcanaccessSQLException(ExceptionMessages.INVALID_MONTH_NUMBER); } @FunctionType(functionName = "DATE", argumentTypes = {}, returnType = AccessType.DATETIME) public static Timestamp date() { Calendar cl = Calendar.getInstance(); cl.set(Calendar.MILLISECOND, 0); cl.set(Calendar.SECOND, 0); cl.set(Calendar.MINUTE, 0); cl.set(Calendar.HOUR_OF_DAY, 0); return new Timestamp(cl.getTime().getTime()); } @FunctionType(namingConflict = true, functionName = "NOW", argumentTypes = {}, returnType = AccessType.DATETIME) public static Timestamp now() { Calendar cl = Calendar.getInstance(); cl.set(Calendar.MILLISECOND, 0); return new Timestamp(cl.getTime().getTime()); } private static Object nz(Object value, Object outher) { return value == null ? outher : value; } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.MEMO }, returnType = AccessType.MEMO) public static String nz(String value) { return value == null ? "" : value; } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.MEMO) public static String nz(String value, String outher) { return (String) nz((Object) value, (Object) outher); } @FunctionType(functionName = "SIGN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.INTEGER) public static short sign(double n) { return (short) (n == 0 ? 0 : (n > 0 ? 1 : -1)); } @FunctionType(functionName = "SPACE", argumentTypes = { AccessType.LONG }, returnType = AccessType.MEMO) public static String space(Integer nr) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < nr; ++i) sb.append(' '); return sb.toString(); } @FunctionType(functionName = "STR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.TEXT) public static String str(double d) { String pre = d > 0 ? " " : ""; return Math.round(d) == d ? pre + Math.round(d) : pre + d; } @FunctionType(functionName = "TIME", argumentTypes = {}, returnType = AccessType.DATETIME) public static Timestamp time() { Calendar cl = Calendar.getInstance(); cl.setTime(now()); cl.set(1899, 11, 30); return new java.sql.Timestamp(cl.getTimeInMillis()); } @FunctionType(functionName = "VAL", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.DOUBLE) public static Double val(BigDecimal val1) { return val((Object) val1); } private static Double val(Object val1) { if (val1 == null) return null; String val = val1.toString().trim(); int lp = val.lastIndexOf("."); char[] ca = val.toCharArray(); StringBuffer sb = new StringBuffer(); int minLength = 1; for (int i = 0; i < ca.length; i++) { char c = ca[i]; if (((c == '-') || (c == '+')) && (i == 0)) { ++minLength; sb.append(c); } else if (c == ' ') continue; else if (Character.isDigit(c)) { sb.append(c); } else if (c == '.' && i == lp) { sb.append(c); if (i == 0 || (i == 1 && minLength == 2)) { ++minLength; } } else break; } if (sb.length() < minLength) return 0.0d; else return Double.parseDouble(sb.toString()); } @FunctionType(functionName = "VAL", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DOUBLE) public static Double val(String val1) { return val((Object) val1); } @FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG }, returnType = AccessType.TEXT) public static String weekDayName(int i) { return weekDayName(i, false); } @FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG, AccessType.YESNO }, returnType = AccessType.TEXT) public static String weekDayName(int i, boolean abbr) { return weekDayName(i, abbr, 1); } @FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG, AccessType.YESNO, AccessType.LONG }, returnType = AccessType.TEXT) public static String weekDayName(int i, boolean abbr, int s) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_WEEK, i + s - 1); String pattern = abbr ? "%ta" : "%tA"; return String.format(pattern, cal, cal); } @FunctionType(functionName = "WEEKDAY", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.LONG) public static Integer weekDay(Timestamp dt) throws UcanaccessSQLException { return datePart("w", dt); } @FunctionType(functionName = "WEEKDAY", argumentTypes = { AccessType.DATETIME, AccessType.LONG }, returnType = AccessType.LONG) public static Integer weekDay(Timestamp dt, Integer firstDayOfWeek) throws UcanaccessSQLException { return datePart("w", dt, firstDayOfWeek); } @FunctionType(functionName = "STRING", argumentTypes = { AccessType.LONG, AccessType.MEMO }, returnType = AccessType.MEMO) public static String string(Integer nr, String str) throws UcanaccessSQLException { if (str == null) return null; String ret = ""; for (int i = 0; i < nr; ++i) { ret += str.charAt(0); } return ret; } @FunctionType(functionName = "TIMESERIAL", argumentTypes = { AccessType.LONG, AccessType.LONG, AccessType.LONG }, returnType = AccessType.DATETIME) public static Timestamp timeserial(Integer h, Integer m, Integer s) { Calendar cl = Calendar.getInstance(); cl.setTime(now()); cl.set(1899, 11, 30, h, m, s); return new java.sql.Timestamp(cl.getTimeInMillis()); } @FunctionType(functionName = "RND", argumentTypes = {}, returnType = AccessType.DOUBLE) public static Double rnd() { return rnd(null); } @FunctionType(functionName = "RND", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double rnd(Double d) { if (d == null) return lastRnd = Math.random(); if (d > 0) return lastRnd = Math.random(); if (d < 0) return rnd == null ? rnd = d : rnd; if (d == 0) return lastRnd == null ? lastRnd = Math.random() : lastRnd; return null; } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.NUMERIC, AccessType.NUMERIC }, returnType = AccessType.NUMERIC) public static BigDecimal nz(BigDecimal value, BigDecimal outher) { return (BigDecimal) nz((Object) value, (Object) outher); } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.DOUBLE, AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static Double nz(Double value, Double outher) { return (Double) nz((Object) value, (Object) outher); } @FunctionType(functionName = "NZ", argumentTypes = { AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG) public static Integer nz(Integer value, Integer outher) { return (Integer) nz((Object) value, (Object) outher); } @FunctionType(functionName = "STRREVERSE", argumentTypes = { AccessType.MEMO}, returnType = AccessType.MEMO) public static String strReverse(String value) { if(value==null)return null; return new StringBuffer(value).reverse().toString(); } @FunctionType(functionName = "STRCONV", argumentTypes = { AccessType.MEMO,AccessType.LONG}, returnType = AccessType.MEMO) public static String strConv(String value,int ul) { if(value==null)return null; if(ul==1)value= value.toUpperCase(); if(ul==2)value= value.toLowerCase(); return value; } @FunctionType(functionName = "STRCOMP", argumentTypes = { AccessType.MEMO,AccessType.MEMO,AccessType.LONG}, returnType = AccessType.LONG) public static Integer strComp(String value1,String value2, Integer type) throws UcanaccessSQLException { switch(type){ case 0: case -1: case 2: return value1.compareTo(value2); case 1: return value1.toUpperCase().compareTo(value2.toUpperCase()); default: throw new UcanaccessSQLException(ExceptionMessages.INVALID_PARAMETER); } } @FunctionType(functionName = "STRCOMP", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.LONG) public static Integer strComp(String value1,String value2) throws UcanaccessSQLException { return strComp( value1,value2, 0); } @FunctionType(functionName = "INT", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG) public static Integer mint(Double value) throws UcanaccessSQLException { return new BigDecimal((long) Math.floor(value )).intValueExact(); } @FunctionType(functionName = "INT", argumentTypes = { AccessType.YESNO }, returnType = AccessType.INTEGER) public static Short mint(boolean value) throws UcanaccessSQLException { return (short)(value?-1:0); } @FunctionType(functionName = "DDB", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ddb(double cost, double salvage, double life,double period ){ return ddb( cost, salvage,life, period ,2d); } @FunctionType(functionName = "DDB", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ddb(double cost, double salvage, double life, double period, double factor) { if (cost<0||((life == 2d) && (period > 1d)))return 0; if (life < 2d||((life == 2d) && (period <= 1d))) return (cost - salvage); if (period <= 1d) return Math.min(cost*factor/life, cost-salvage); double retk =Math.max( salvage -cost * Math.pow((life - factor) / life, period),0); return Math.max( ((factor * cost) / life) * Math.pow((life - factor) / life, period - 1d)-retk,0); } @FunctionType(functionName = "FV", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double fv(double rate,int periods,double payment){ return fv(rate, periods, payment,0,0); } @FunctionType(functionName = "FV", argumentTypes = { AccessType.DOUBLE,AccessType.LONG ,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double fv(double rate,int periods,double payment,double pv){ return fv(rate, periods, payment,pv,0); } @FunctionType(functionName = "FV", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double fv(double rate,int periods,double payment,double pv,double type){ type=(Math.abs(type)>=1)?1:0; double fv=pv*Math.pow(1+rate, periods); for(int i=0;i<periods;i++){ fv+=(payment)*Math.pow(1+rate, i+type); } return -fv; } @FunctionType(functionName = "PMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double pmt(double rate, double periods, double pv) { return pmt( rate, periods, pv,0,0); } @FunctionType(functionName = "PMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double pmt(double rate, double periods, double pv, double fv) { return pmt( rate, periods, pv,0,0); } @FunctionType(functionName = "PMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double pmt(double rate, double periods, double pv, double fv, double type) { type=(Math.abs(type)>=1)?1:0; if (rate == 0) { return -1*(fv+pv)/periods; } else { return ( fv + pv * Math.pow(1+rate , periods) ) * rate / ((type==1? 1+rate : 1) * (1 - Math.pow(1+rate, periods))); } } @FunctionType(functionName = "NPER", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double nper(double rate, double pmt, double pv) { return nper( rate, pmt, pv, 0, 0); } @FunctionType(functionName = "NPER", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double nper(double rate, double pmt, double pv, double fv) { return nper( rate, pmt, pv, fv, 0); } @FunctionType(functionName = "NPER", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double nper(double rate, double pmt, double pv, double fv,double type) { type=(Math.abs(type)>=1)?1:0; double nper = 0; if (rate == 0) { nper = -1 * (fv + pv) / pmt; } else { double cr = (type==1 ? 1+rate : 1) * pmt / rate; double val1 = ((cr - fv) < 0) ? Math.log(fv - cr) : Math.log(cr - fv); double val2 = ((cr - fv) < 0) ? Math.log(-pv - cr) : Math.log(pv + cr); double val3 = Math.log(1+ rate); nper = (val1 - val2) / val3; } return nper; } @FunctionType(functionName = "IPMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ipmt(double rate, double per, double nper, double pv) { return ipmt(rate, per, nper, pv, 0,0); } @FunctionType(functionName = "IPMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ipmt(double rate, double per, double nper, double pv, double fv) { return ipmt(rate, per, nper, pv, fv,0); } @FunctionType(functionName = "IPMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ipmt(double rate, double per, double nper, double pv, double fv, double type) { type=(Math.abs(type)>=1)?1:0; double ipmt = fv(rate, new Double(per).intValue() - 1, pmt(rate, nper, pv, fv, type), pv, type) * rate; if (type==1) ipmt =ipmt/ (1 + rate); return ipmt; } @FunctionType(functionName = "PV", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double pv(double rate, double nper, double pmt) { return pv( rate, nper, pmt,0,0); } @FunctionType(functionName = "PV", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double pv(double rate, double nper, double pmt, double fv) { return pv( rate, nper, pmt,fv,0); } @FunctionType(functionName = "PV", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double pv(double rate, double nper, double pmt, double fv, double type) { type=(Math.abs(type)>=1)?1:0; if (rate == 0) { return -1*((nper*pmt)+fv); } else { return (( ( 1 - Math.pow(1+rate, nper) ) / rate ) * (type==1 ? 1+rate : 1) * pmt - fv) / Math.pow(1+rate, nper); } } @FunctionType(functionName = "PPMT", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.LONG,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ppmt(double rate, int per, int nper, double pv) { return ppmt(rate,per, nper, pv, 0, 0) ; } @FunctionType(functionName = "PPMT", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.LONG,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ppmt(double rate, int per, int nper, double pv, double fv) { return ppmt(rate,per, nper, pv, fv, 0) ; } @FunctionType(functionName = "PPMT", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.LONG,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double ppmt(double rate, int per, int nper, double pv, double fv, double type) { return pmt(rate, nper, pv, fv, type) - ipmt(rate, per, nper, pv, fv, type); } @FunctionType(functionName = "SLN", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE) public static double sln(double cost, double salvage, double life) { return (cost-salvage)/life; } @FunctionType(functionName = "SYD", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double syd(double cost, double salvage, double life,double per) { return (cost-salvage)*(life-per+1)*2/(life*(life+1)); } @FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double rate(double nper, double pmt, double pv) { return rate(nper, pmt, pv, 0, 0, 0.1); } @FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double rate(double nper, double pmt, double pv, double fv) { return rate(nper, pmt, pv, fv, 0, 0.1); } @FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double rate(double nper, double pmt, double pv, double fv, double type) { return rate(nper, pmt, pv, fv, type, 0.1); } @FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double rate(double nper, double pmt, double pv, double fv, double type, double guess) { type=(Math.abs(type)>=1)?1:0; //the only change to the implementation Apache POI int FINANCIAL_MAX_ITERATIONS = 20;//Bet accuracy with 128 double FINANCIAL_PRECISION = 0.0000001;//1.0e-8 double y, y0, y1, x0, x1 = 0, f = 0, i = 0; double rate = guess; if (Math.abs(rate) < FINANCIAL_PRECISION) { y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv; } else { f = Math.exp(nper * Math.log(1 + rate)); y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv; } y0 = pv + pmt * nper + fv; y1 = pv * f + pmt * (1 / rate + type) * (f - 1) + fv; // find root by Newton secant method i = x0 = 0.0; x1 = rate; while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) { rate = (y1 * x0 - y0 * x1) / (y1 - y0); x0 = x1; x1 = rate; if (Math.abs(rate) < FINANCIAL_PRECISION) { y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv; } else { f = Math.exp(nper * Math.log(1 + rate)); y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv; } y0 = y1; y1 = y; ++i; } return rate; } @FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.DOUBLE) public static Double formulaToNumeric(Double res, String datatype){ return res; } @FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.DOUBLE) public static Double formulaToNumeric(Boolean res, String datatype){ if(res==null)return null; return res.booleanValue()?-1d:0d; } @FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.DOUBLE) public static Double formulaToNumeric(String res, String datatype){ if(res==null)return null; try{ DecimalFormatSymbols dfs=DecimalFormatSymbols.getInstance(); String sep=dfs.getDecimalSeparator()+""; String gs=dfs.getGroupingSeparator()+""; res=res.replaceAll(Pattern.quote(gs), ""); if(!sep.equalsIgnoreCase(".")) res=res.replaceAll(Pattern.quote(sep),"."); double d= val(res); DataType dt= DataType.valueOf(datatype); if(dt.equals( DataType.BYTE)||dt.equals( DataType.INT)||dt.equals( DataType.LONG)){ d=Math.rint(d+APPROX); } return d; }catch(Exception e){ return null; } } @FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.DOUBLE) public static Double formulaToNumeric(Timestamp res, String datatype) throws UcanaccessSQLException{ if(res==null)return null; Calendar clbb = Calendar.getInstance(); clbb.set(1899, 11, 30,0,0,0); return (double)dateDiff("y",new Timestamp(clbb.getTimeInMillis()),res ); } @FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.YESNO) public static Boolean formulaToBoolean(Boolean res, String datatype){ return res; } @FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.YESNO) public static Boolean formulaToBoolean(Double res, String datatype){ if(res==null)return null; return res!=0d; } @FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.YESNO) public static Boolean formulaToBoolean(Timestamp res, String datatype){ return null; } @FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.YESNO) public static Boolean formulaToBoolean(String res, String datatype){ if(res==null)return null; if(res.equals("-1"))return true; if(res.equals("0"))return false; return null; } @FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.MEMO) public static String formulaToText(String res, String datatype){ return res; } @FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.MEMO) public static String formulaToText(Double res, String datatype) throws UcanaccessSQLException{ if(res==null)return null; DecimalFormatSymbols dfs=DecimalFormatSymbols.getInstance(); DecimalFormat df = new DecimalFormat("#",dfs); df.setGroupingUsed(false); df.setMaximumFractionDigits(100); return df.format(res); } @FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.MEMO) public static String formulaToText(Boolean res, String datatype) throws UcanaccessSQLException{ if(res==null)return null; return res?"-1":"0"; } @FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.MEMO) public static String formulaToText(Timestamp res, String datatype) throws UcanaccessSQLException{ Calendar cl = Calendar.getInstance(); cl.setTimeInMillis(res.getTime()); if(cl.get(Calendar.HOUR)==0&&cl.get(Calendar.MINUTE)==0&&cl.get(Calendar.SECOND)==0) return format(res,"short date" ); else return format(res,"general date" ); } @FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.DATETIME) public static Timestamp formulaToDate(Timestamp res, String datatype){ return res; } @FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.DATETIME) public static Timestamp formulaToDate(String res, String datatype){ if(res==null)return null; try{ return dateValue(res,false); }catch(Exception e){ return null; } } @FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.DATETIME) public static Timestamp formulaToDate(Boolean res, String datatype) throws UcanaccessSQLException{ if(res==null)return null; Calendar clbb = Calendar.getInstance(); clbb.set(1899, 11, 30,0,0,0); clbb.set(Calendar.MILLISECOND, 0); return dateAdd("y", res?-1:0, new Timestamp(clbb.getTimeInMillis())); } @FunctionType(functionName = "orderNM", argumentTypes = { AccessType.MEMO}, returnType = AccessType.MEMO) public static String orderNM(String s) { return s.replaceAll("(\\w)\\-(\\w)", "$1$2"); } @FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.DATETIME) public static Timestamp formulaToDate(Double res, String datatype) throws UcanaccessSQLException{ if(res==null)return null; Calendar clbb = Calendar.getInstance(); clbb.set(1899, 11, 30,0,0,0); clbb.set(Calendar.MILLISECOND, 0); Double d=Math.floor(res); Timestamp tr= dateAdd("y", d.intValue(), new Timestamp(clbb.getTimeInMillis())); d=(res-res.intValue())*24; tr= dateAdd("H",d.intValue(), tr); d=(d-d.intValue())*60; tr= dateAdd("N",d.intValue(), tr); d=(d-d.intValue())*60; tr= dateAdd("S",new Double(Math.rint(d+APPROX)).intValue(), tr); return tr; } @FunctionType(namingConflict = true,functionName = "ROUND", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double round(double d, double p) { double f = Math.pow(10d, p); return Math.round(d * f) / f; } @FunctionType(namingConflict = true,functionName = "FIX", argumentTypes = { AccessType.DOUBLE}, returnType = AccessType.DOUBLE) public static double fix(double d) throws UcanaccessSQLException { return sign(d) * mint(Math.abs(d)); } @FunctionType(functionName = "PARTITION", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.MEMO) public static String partition(Double number,double start,double stop,double interval) throws UcanaccessSQLException { if(number==null)return null; number=Math.rint(number); interval=Math.rint(interval); String ul=String.valueOf(lrint(stop)+1); stop=lrint(stop); start=lrint(start); int h=ul.length(); if(number<start){ return padLeft(-1, h)+":"+padLeft(lrint(start)-1,h); } if(number>stop){ return ul+":"+padLeft(-1, h); } for(double d=start;d<=stop;d+=interval){ if((number>=d&&number<(d+interval))) { return padLeft(lceil(d),h)+":"+ padLeft(((d+interval)<=stop?lfloor(d+interval): lrint(stop)),h); } } return ""; } private static int lfloor(double d){ return new Double(Math.floor(d-APPROX)).intValue(); } private static int lceil(double d){ return new Double(Math.ceil(d-APPROX)).intValue(); } private static int lrint(double d){ return new Double(Math.rint(d-APPROX)).intValue(); } private static String padLeft(int ext, int n) { String tp=ext>0?String.valueOf(ext):""; return String.format("%1$" + n + "s", tp); } }
package nl.topicus.jdbc.statement; import java.util.Arrays; import java.util.List; import com.google.cloud.spanner.Mutation; class Mutations { private final List<Mutation> buffer; private final AbstractTablePartWorker worker; /** * Single mutation * * @param mutation */ Mutations(Mutation mutation) { this.buffer = Arrays.asList(mutation); this.worker = null; } Mutations(List<Mutation> mutations) { this.buffer = mutations; this.worker = null; } Mutations(AbstractTablePartWorker worker) { this.buffer = null; this.worker = worker; } List<Mutation> getMutations() { if (isWorker()) throw new IllegalStateException( "Cannot call getMutations() on a Mutations-object that returns its results as a worker"); return buffer; } AbstractTablePartWorker getWorker() { return worker; } boolean isWorker() { return worker != null; } long getNumberOfResults() { if (isWorker()) return worker.getRecordCount(); return buffer.size(); } }
package org.agmip.ui.quadui; import java.io.File; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.ArrayList; import java.util.HashMap; import org.agmip.core.types.TranslatorOutput; import org.apache.pivot.util.concurrent.Task; import org.apache.pivot.util.concurrent.TaskExecutionException; import org.agmip.translators.apsim.ApsimOutput; import org.agmip.translators.dssat.DssatControllerOutput; import org.agmip.translators.dssat.DssatWeatherOutput; import org.agmip.util.AcmoUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.agmip.util.JSONAdapter.toJSON; public class TranslateToTask extends Task<String> { private HashMap data; private ArrayList<String> translateList; private ArrayList<String> weatherList, soilList; private String destDirectory; private static Logger LOG = LoggerFactory.getLogger(TranslateToTask.class); public TranslateToTask(ArrayList<String> translateList, HashMap data, String destDirectory) { this.data = data; this.destDirectory = destDirectory; this.translateList = new ArrayList<String>(); this.weatherList = new ArrayList<String>(); this.soilList = new ArrayList<String>(); for (String trType : translateList) { if (!trType.equals("JSON")) { this.translateList.add(trType); } } if (data.containsKey("weathers")) { for (HashMap<String, Object> stations : (ArrayList<HashMap>) data.get("weathers")) { weatherList.add((String) stations.get("wst_id")); } } if (data.containsKey("soils")) { for (HashMap<String, Object> soils : (ArrayList<HashMap>) data.get("soils")) { soilList.add((String) soils.get("soil_id")); } } } @Override public String execute() throws TaskExecutionException { ExecutorService executor = Executors.newFixedThreadPool(64); try { for (String tr : translateList) { // Generate the ACMO here (pre-generation) so we know what // we should get out of everything. AcmoUtil.writeAcmo(destDirectory+File.separator+tr.toUpperCase(), data, tr.toLowerCase()); if (tr.equals("DSSAT")) { if (data.size() == 1 && data.containsKey("weather")) { LOG.info("Running in weather only mode"); submitTask(executor,tr,data,true); } else { submitTask(executor, tr, data, false); } } else { // Handle translators that do not support the multi-experiment // format. if (data.containsKey("experiments")) { for (HashMap<String, Object> experiment : (ArrayList<HashMap>) data.get("experiments")) { HashMap<String, Object> temp = new HashMap<String, Object>(experiment); int wKey, sKey; if (temp.containsKey("wst_id")) { if ((wKey = weatherList.indexOf((String) temp.get("wst_id"))) != -1) { temp.put("weather", ((ArrayList<HashMap<String, Object>>) data.get("weathers")).get(wKey)); } } if (temp.containsKey("soil_id")) { if ((sKey = soilList.indexOf((String) temp.get("soil_id"))) != -1) { temp.put("soil", ((ArrayList<HashMap<String, Object>>) data.get("soils")).get(sKey)); } } LOG.debug("JSON of temp:"+toJSON(temp)); // need to re-implement properly for threading apsim //submitTask(executor, tr, temp); if(tr.equals("APSIM")) { ApsimOutput translator = new ApsimOutput(); translator.writeFile(destDirectory+File.separator+"APSIM", temp); } } } else { boolean wthOnly = false; if ( data.size() == 1 && data.containsKey("weather") ) { wthOnly = true; } //Assume this is a single complete experiment submitTask(executor, tr, data, wthOnly); } } } executor.shutdown(); while (!executor.isTerminated()) { } executor = null; //this.data = null; } catch (Exception ex) { throw new TaskExecutionException(ex); } return null; } /** * Submit a task to an executor to start translation. * * @param executor The <code>ExecutorService</code> to execute this thread on. * @param trType The model name to translate to (used to instantiate the * proper <code>TranslatorOutput</code> * @param data The data to translate */ private void submitTask(ExecutorService executor, String trType, HashMap<String, Object> data, boolean wthOnly) { TranslatorOutput translator = null; String destination = ""; if (trType.equals("DSSAT")) { if (wthOnly) { translator = new DssatWeatherOutput(); } else { translator = new DssatControllerOutput(); } } else if (trType.equals("APSIM")) { translator = new ApsimOutput(); } destination = destDirectory + File.separator + trType; LOG.debug("Translating with :"+translator.getClass().getName()); Runnable thread = new TranslateRunner(translator, data, destination); executor.execute(thread); } }
package org.apdplat.word.vector; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author */ public class ExtractText { private static final Logger LOGGER = LoggerFactory.getLogger(ExtractText.class); private static final AtomicInteger WORD_COUNT = new AtomicInteger(); private static final AtomicInteger CHAR_COUNT = new AtomicInteger(); public static void main(String[] args){ String output = "target/word.txt"; String separator = " "; if(args.length == 1){ output = args[0]; } if(args.length == 2){ output = args[0]; separator = args[1]; } extractFromCorpus(output, separator); } /** * * @param output * @param separator */ public static void extractFromCorpus(String output, String separator){ String zipFile = "src/main/resources/corpus/corpora.zip"; LOGGER.info(""); long start = System.currentTimeMillis(); try{ analyzeCorpus(zipFile, output, separator); } catch (IOException ex) { LOGGER.info(""+ex.getMessage()); } long cost = System.currentTimeMillis() - start; LOGGER.info(""+cost+""); LOGGER.info(""+CHAR_COUNT.get()+""+WORD_COUNT.get()); } /** * * @param zipFile * @throws IOException */ private static void analyzeCorpus(String zipFile, String output, final String separator) throws IOException{ try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), ExtractText.class.getClassLoader()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"utf-8"));) { for(Path path : fs.getRootDirectories()){ LOGGER.info(""+path); Files.walkFileTree(path, new SimpleFileVisitor<Path>(){ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { LOGGER.info(""+file); Path temp = Paths.get("target/corpus-"+System.currentTimeMillis()+".txt"); Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING); extractText(temp, writer, separator); return FileVisitResult.CONTINUE; } }); } } } /** * * @param file * @param writer */ private static void extractText(Path file, BufferedWriter writer, String separator){ try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.toFile()),"utf-8"));){ String line; while( (line = reader.readLine()) != null ){ line = line.trim(); if(!"".equals(line)){ String[] words = line.split("\\s+"); if(words == null){ continue; } StringBuilder phrase = new StringBuilder(); int phraseCount=0; boolean find=false; for(String word : words){ String[] attr = word.split("/"); if(attr == null || attr.length < 1){ continue; } if(attr[0].trim().startsWith("[")){ find = true; } String item = attr[0].replace("[", "").replace("]", "").trim(); writer.write(item+separator); if(find){ phrase.append(item); phraseCount++; } if(phraseCount > 10){ find = false; phraseCount = 0; phrase.setLength(0); } if(find && attr.length > 1 && attr[1].trim().endsWith("]")){ find = false; writer.write(phrase.toString()+separator); phrase.setLength(0); } WORD_COUNT.incrementAndGet(); CHAR_COUNT.addAndGet(item.length()); } writer.write("\n"); } } }catch(Exception e){ LOGGER.info(" "+file+" ", e); } } }
package org.basex.api.xqj; import static org.basex.api.xqj.BXQText.*; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.util.GregorianCalendar; import java.util.TimeZone; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.Source; import javax.xml.xquery.XQCancelledException; import javax.xml.xquery.XQConstants; import javax.xml.xquery.XQDynamicContext; import javax.xml.xquery.XQException; import javax.xml.xquery.XQItem; import javax.xml.xquery.XQItemType; import javax.xml.xquery.XQQueryException; import javax.xml.xquery.XQSequence; import org.basex.core.ProgressException; import org.basex.io.IOContent; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.item.Atm; import org.basex.query.item.Bln; import org.basex.query.item.Dbl; import org.basex.query.item.Dec; import org.basex.query.item.Flt; import org.basex.query.item.Item; import org.basex.query.item.Itr; import org.basex.query.item.QNm; import org.basex.query.item.Str; import org.basex.query.item.Type; import org.basex.query.iter.Iter; import org.basex.query.iter.SeqIter; import org.basex.query.util.Var; import org.basex.util.Performance; import org.basex.util.Token; import org.w3c.dom.Node; abstract class BXQDynamicContext extends BXQAbstract implements XQDynamicContext { /** Context. */ protected final BXQStaticContext sc; /** Query processor. */ protected QueryProcessor query; /** Time zone. */ private TimeZone zone; /** * Constructor. * @param s static context * @param qu query * @param c closer */ protected BXQDynamicContext(final String qu, final BXQStaticContext s, final BXQConnection c) { super(c); sc = s; query = new QueryProcessor(qu, s.context); query.ctx.copy(sc.ctx); } public void bindAtomicValue(final QName qn, final String v, final XQItemType t) throws XQException { valid(t, XQItemType.class); bind(qn, new Atm(Token.token(valid(v, String.class).toString())), t); } public void bindBoolean(final QName qn, final boolean v, final XQItemType it) throws XQException { bind(qn, Bln.get(v), it); } public void bindByte(final QName qn, final byte v, final XQItemType t) throws XQException { bind(qn, new Itr(v, Type.BYT), t); } public void bindDocument(final QName qn, final InputStream is, final String base, final XQItemType t) throws XQException { bind(qn, createDB(is), t); } public void bindDocument(final QName qn, final Reader r, final String base, final XQItemType t) throws XQException { bind(qn, createDB(r), t); } public void bindDocument(final QName qn, final Source s, final XQItemType t) throws XQException { bind(qn, createDB(s, t), t); } public void bindDocument(final QName qn, final String v, final String base, final XQItemType t) throws XQException { valid(v, String.class); bind(qn, createDB(new IOContent(Token.token(v))), t); } public void bindDocument(final QName qn, final XMLStreamReader sr, final XQItemType t) throws XQException { bind(qn, createDB(sr), t); } public void bindDouble(final QName qn, final double v, final XQItemType t) throws XQException { bind(qn, Dbl.get(v), t); } public void bindFloat(final QName qn, final float v, final XQItemType t) throws XQException { bind(qn, Flt.get(v), t); } public void bindInt(final QName qn, final int v, final XQItemType t) throws XQException { bind(qn, Itr.get(v), t); } public void bindItem(final QName qn, final XQItem t) throws XQException { valid(t, XQItem.class); bind(qn, ((BXQItem) t).it, null); } public void bindLong(final QName qn, final long v, final XQItemType t) throws XQException { bind(qn, new Dec(new BigDecimal(v), Type.LNG), t); } public void bindNode(final QName qn, final Node n, final XQItemType t) throws XQException { bind(qn, create(n, null), t); } public void bindObject(final QName qn, final Object v, final XQItemType t) throws XQException { bind(qn, create(v, null), t); } public void bindSequence(final QName qn, final XQSequence s) throws XQException { valid(s, XQSequence.class); try { bind(qn, ((BXQSequence) s).result.finish(), null); } catch(final QueryException ex) { throw new BXQException(ex); } } public void bindShort(final QName qn, final short v, final XQItemType t) throws XQException { bind(qn, new Itr(v, Type.SHR), t); } public void bindString(final QName qn, final String v, final XQItemType t) throws XQException { bind(qn, Str.get(valid(v, String.class)), t); } public TimeZone getImplicitTimeZone() throws XQException { opened(); return zone != null ? zone : new GregorianCalendar().getTimeZone(); } public void setImplicitTimeZone(final TimeZone tz) throws XQException { opened(); zone = tz; } /** * Binds an item to the specified variable. * @param var variable name * @param it item to be bound * @param t target type * @throws XQException query exception */ private void bind(final QName var, final Item it, final XQItemType t) throws XQException { opened(); valid(var, QName.class); final Type tt = check(it.type, t); Item i = it; if(tt != it.type) { try { i = tt.e(it, null); } catch(final QueryException ex) { throw new BXQException(ex); } } if(var == XQConstants.CONTEXT_ITEM) { query.ctx.item = i; } else { final QNm name = new QNm(Token.token(var.getLocalPart())); Var v = new Var(name, true); if(this instanceof BXQPreparedExpression) { v = query.ctx.vars.get(v); if(v == null) throw new BXQException(VAR, var); } else { query.ctx.vars.addGlobal(v); } try { v.bind(i, null); } catch(final QueryException ex) { throw new BXQException(ex); } } } /** * Executes the specified query and returns the result iterator. * @return result sequence * @throws XQException exception */ protected BXQSequence execute() throws XQException { opened(); final QueryContext qctx = query.ctx; qctx.ns = sc.ctx.ns; try { if(sc.timeout != 0) { new Thread() { @Override public void run() { Performance.sleep(sc.timeout * 1000); qctx.stop(); } }.start(); } query.parse(); qctx.compile(); Iter iter = qctx.iter(); if(sc.scrollable) iter = SeqIter.get(iter); return new BXQSequence(iter, this, (BXQConnection) par); } catch(final QueryException ex) { throw new XQQueryException(ex.getMessage(), new QName(ex.code()), ex.line(), ex.col(), -1); } catch(final ProgressException ex) { throw new XQCancelledException(TIMEOUT, null, null, -1, -1, -1, null, null, null); } } @Override public final void close() throws XQException { try { if(!closed) query.close(); } catch(final IOException ex) { throw new XQQueryException(ex.getMessage()); } super.close(); } }
package org.cpic.haplotype; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; /** * Read in haplotype definition files. * * @author Mark Woon */ public class DefinitionReader { private ListMultimap<String, Variant> m_haplotypePositions = ArrayListMultimap.create(); private ListMultimap<String, Haplotype> m_haplotypes = ArrayListMultimap.create(); private Map<String, TSVfile> m_files = new HashMap<>(); public Map<String, TSVfile> getFiles() { return m_files; } public ListMultimap<String, Variant> getHaplotypePositions() { return m_haplotypePositions; } public ListMultimap<String, Haplotype> getHaplotypes() { return m_haplotypes; } public void read(Path path) throws IOException { if (Files.isDirectory(path)) { Files.list(path) .filter(f -> f.toString().endsWith(".tsv")) .forEach(this::readFile); } else { readFile(path); } } private void readFile(@Nonnull Path file) { Preconditions.checkNotNull(file); Preconditions.checkArgument(Files.isRegularFile(file)); System.out.println(file); try (BufferedReader bufferedReader = Files.newBufferedReader(file)) { TSVfile inProccessFile = new TSVfile(file.toString()); ArrayList<Variant> variants = new ArrayList<>(); ArrayList<Haplotype> haplotypes = new ArrayList<>(); String line; boolean NormalFunctionAllele = true; while((line = bufferedReader.readLine()) != null) { //System.out.println(line); String[] fields = line.split("\t"); for (int i = 0; i < fields.length; i++){ fields[i] = fields[i].trim(); } if (fields[0].equals("FormatVersion")){ if (fields.length>1){ inProccessFile.setFormatVersion(fields[1]); }else{ inProccessFile.setFormatVersion(""); } } else if (fields[0].equals("GeneName")){ if (fields.length>1){ inProccessFile.setGeneName(fields[1]); }else{ inProccessFile.setGeneName(""); } inProccessFile.setGeneName(fields[1]); } else if (fields[0].equals("GeneRefSeq")){ inProccessFile.setGeneID(fields[1]); } else if (fields[0].equals("GeneOrientation")){ if (fields.length>1){ inProccessFile.setGeneOrientation(fields[1]); }else{ inProccessFile.setGeneOrientation(""); } } else if (fields[0].equals("ContentDate")){ if (fields.length>1){ inProccessFile.setContentDate(fields[1]); }else{ inProccessFile.setContentDate(""); } } else if (fields[0].equals("ContentVersion")){ if (fields.length>1){ inProccessFile.setContentVersion(fields[1]); }else{ inProccessFile.setContentVersion(""); } } else if (fields[0].equals("GenomeBuild")){ if (fields.length>0){ inProccessFile.setGenomeBuild(fields[1]); }else{ inProccessFile.setGenomeBuild(""); } } else if (fields[0].equals("ChrName")){ if (fields.length>0){ inProccessFile.setChromosome(fields[1]); }else{ inProccessFile.setChromosome(""); } } else if (fields[0].equals("ChrRefSeq")){ if (fields.length>0){ inProccessFile.setChromosomeID(fields[1]); }else{ inProccessFile.setChromosomeID(""); } } else if (fields[0].equals("ProteinRefSeq")){ if (fields.length>0){ inProccessFile.setProteinID(fields[1]); }else{ inProccessFile.setProteinID(""); } } else if (fields[0].equals("ResourceNote")){ for (int i = 4; i < fields.length; i++){ Variant newVariant = new Variant(inProccessFile.getChromosome(),inProccessFile.getGeneName(),fields[i]); variants.add(newVariant); } } else if (fields[0].equals("ProteinNote")){ for (int i = 4; i < fields.length; i++){ variants.get(i-4).addProteingEffect(fields[i]); } } else if (fields[0].equals("ChrPosition")){ for (int i = 4; i < fields.length; i++){ variants.get(i-4).addProteingEffect(fields[i]); variants.get(i-4).setStartPOS(); } } else if (fields[0].equals("GenePosition")){ for (int i = 4; i < fields.length; i++){ variants.get(i-4).addProteingEffect(fields[i]); } } else if (fields[0].equals("rsID")){ for (int i = 4; i < fields.length; i++){ variants.get(i-4).set_rsID(fields[i]); } } else if (fields[0].equals("Allele")){ ArrayList <String> alleles = new ArrayList<>(); ArrayList <Variant> hapVariants = new ArrayList<>(); int forLength = variants.size()+4; if (forLength>fields.length){ forLength=fields.length; } for (int i = 4; i < forLength; i++){ if (NormalFunctionAllele){ variants.get(i-4).setREF(fields[i]); alleles.add(fields[i]); hapVariants.add(variants.get(i-4)); } else{ if (!fields[i].trim().equals("")){ variants.get(i-4).addALT(fields[i]); alleles.add(fields[i]); hapVariants.add(variants.get(i-4)); } } } NormalFunctionAllele=false; haplotypes.add(new Haplotype(hapVariants,fields[1],fields[2],fields[3],alleles)); } } for (int i = 0; i < haplotypes.size(); i++){ m_haplotypes.put(inProccessFile.getGeneName(),haplotypes.get(i)); } for (int i = 0; i < variants.size(); i++){ m_haplotypePositions.put(inProccessFile.getGeneName(),variants.get(i)); } m_files.put(inProccessFile.getGeneName(), inProccessFile); } catch (Exception ex) { throw new RuntimeException("Failed to parse " + file, ex); } } public static void main(String[] args) { try { Path path = Paths.get(args[0]); DefinitionReader r = new DefinitionReader(); r.read(path); } catch (Exception ex) { ex.printStackTrace(); } } }
package org.dita.dost.module; import static org.dita.dost.util.Constants.*; import static org.dita.dost.util.URLUtils.*; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import org.apache.tools.ant.util.FileUtils; import org.dita.dost.util.CatalogUtils; import org.dita.dost.util.Configuration; import org.dita.dost.util.XMLUtils; import org.w3c.dom.Element; import org.dita.dost.exception.DITAOTException; import org.dita.dost.pipeline.AbstractPipelineInput; import org.dita.dost.pipeline.AbstractPipelineOutput; import org.dita.dost.reader.MapMetaReader; import org.dita.dost.util.Job.FileInfo; import org.dita.dost.writer.DitaMapMetaWriter; import org.dita.dost.writer.DitaMetaWriter; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; /** * Cascades metadata from maps to topics and then from topics to maps. * * MoveMetaModule implement the move meta step in preprocess. It cascades metadata * in maps and collects metadata for topics. The collected metadata is then inserted * into maps and topics. * * @author Zhang, Yuan Peng */ final class MoveMetaModule extends AbstractPipelineModuleImpl { /** * Entry point of MoveMetaModule. * * @param input Input parameters and resources. * @return null * @throws DITAOTException exception */ @Override public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { final Collection<FileInfo> fis = new ArrayList<>(); //for (final FileInfo f: job.getFileInfo()) { // if (ATTR_FORMAT_VALUE_DITAMAP.equals(f.format)) { // fis.add(f); fis.add(job.getFileInfo(job.getInputMap())); if (!fis.isEmpty()) { final Map<URI, Map<String, Element>> mapSet = getMapMetadata(fis); pushMetadata(mapSet); pullTopicMetadata(input, fis); } return null; } /** * Pull metadata from topics and push to maps. */ private void pullTopicMetadata(final AbstractPipelineInput input, final Collection<FileInfo> fis) throws DITAOTException { // Pull metadata (such as navtitle) into the map from the referenced topics final File styleFile = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_STYLE)); for (final FileInfo f : fis) { final File inputFile = new File(job.tempDir, f.file.getPath()); final File tmp = new File(inputFile.getAbsolutePath() + ".tmp" + Long.toString(System.currentTimeMillis())); if (!tmp.getParentFile().exists() && !tmp.getParentFile().mkdirs()) { throw new DITAOTException("Failed to create directory " + tmp.getParent()); } logger.info("Processing " + inputFile.toURI()); logger.debug("Processing " + inputFile.toURI() + " to " + tmp.toURI()); final Source source = new StreamSource(inputFile.toURI().toString()); final Result result = new StreamResult(tmp); try { logger.info("Loading stylesheet " + styleFile); final TransformerFactory tf = TransformerFactory.newInstance(); tf.setURIResolver(CatalogUtils.getCatalogResolver()); final Transformer t = tf.newTransformer(new StreamSource(styleFile)); if (Configuration.DEBUG) { t.setURIResolver(new XMLUtils.DebugURIResolver(tf.getURIResolver())); } for (Entry<String, String> e : input.getAttributes().entrySet()) { logger.debug("Set parameter " + e.getKey() + " to '" + e.getValue() + "'"); t.setParameter(e.getKey(), e.getValue()); } t.transform(source, result); } catch (final TransformerConfigurationException e) { throw new RuntimeException("Failed to compile stylesheet '" + styleFile.toURI() + "': " + e.getMessage(), e); } catch (final Exception e) { throw new DITAOTException("Failed to transform document: " + e.getMessage(), e); } finally { try { XMLUtils.close(source); } catch (final IOException e) { // NOOP } try { XMLUtils.close(result); } catch (final IOException e) { // NOOP } } try { logger.debug("Moving " + tmp.toURI() + " to " + inputFile.toURI()); if (!inputFile.delete()) { throw new IOException("Failed to to delete input file " + inputFile.toURI()); } if (!tmp.renameTo(inputFile)) { throw new IOException("Failed to to replace input file " + inputFile.toURI()); } } catch (final IOException e) { throw new DITAOTException("Failed to replace document: " + e.getMessage(), e); } finally { logger.debug("Remove " + tmp.toURI()); FileUtils.delete(tmp); } } } /** * Push information from topicmeta in the map into the corresponding topics and maps. */ private void pushMetadata(final Map<URI, Map<String, Element>> mapSet) { if (!mapSet.isEmpty()) { //process map first final DitaMapMetaWriter mapInserter = new DitaMapMetaWriter(); mapInserter.setLogger(logger); mapInserter.setJob(job); for (final Entry<URI, Map<String, Element>> entry : mapSet.entrySet()) { final URI key = entry.getKey(); final FileInfo fi = job.getFileInfo(key); if (fi == null) { logger.error("File " + new File(job.tempDir, key.getPath()) + " was not found."); continue; } final URI targetFileName = job.tempDir.toURI().resolve(fi.uri); assert targetFileName.isAbsolute(); if (fi.format.equals(ATTR_FORMAT_VALUE_DITAMAP)) { mapInserter.setMetaTable(entry.getValue()); if (toFile(targetFileName).exists()) { logger.info("Processing " + targetFileName); mapInserter.read(toFile(targetFileName)); } else { logger.error("File " + targetFileName + " does not exist"); } } } //process topic final DitaMetaWriter topicInserter = new DitaMetaWriter(); topicInserter.setLogger(logger); topicInserter.setJob(job); for (final Entry<URI, Map<String, Element>> entry : mapSet.entrySet()) { final URI key = entry.getKey(); final FileInfo fi = job.getFileInfo(key); if (fi == null) { logger.error("File " + new File(job.tempDir, key.getPath()) + " was not found."); continue; } final URI targetFileName = job.tempDir.toURI().resolve(fi.uri); assert targetFileName.isAbsolute(); if (fi.format.equals(ATTR_FORMAT_VALUE_DITA)) { topicInserter.setMetaTable(entry.getValue()); if (toFile(targetFileName).exists()) { logger.info("Processing " + targetFileName); topicInserter.read(toFile(targetFileName)); } else { logger.error("File " + targetFileName + " does not exist"); } } } } } /** * Read metadata from topicmeta elements in maps. */ private Map<URI, Map<String, Element>> getMapMetadata(final Collection<FileInfo> fis) { final MapMetaReader metaReader = new MapMetaReader(); metaReader.setLogger(logger); metaReader.setJob(job); for (final FileInfo f : fis) { final File mapFile = new File(job.tempDir, f.file.getPath()); logger.info("Processing " + mapFile.toURI()); //FIXME: this reader gets the parent path of input file metaReader.read(mapFile); } return metaReader.getMapping(); } }
package org.dstadler.commoncrawl; /** * Which extensions we are interested in. * * @author dominik.stadler */ public class Extensions { private static final String[] EXTENSIONS = new String[] { // Excel ".xls", ".xlsx", ".xlsm", ".xltx", ".xlsb", // Word ".doc", ".docx", ".dotx", ".docm", ".ooxml", // Powerpoint ".ppt", ".pot", ".pptx", ".pptm", ".ppsm", ".ppsx", ".thmx", ".potx", // Outlook ".msg", // Publisher ".pub", // Visio - binary ".vsd", ".vss", ".vst", ".vsw", // Visio - ooxml (currently unsupported) ".vsdm", ".vsdx", ".vssm", ".vssx", ".vstm", ".vstx", // POIFS ".ole2", // Microsoft Admin Template? ".adm", // Microsoft TNEF // ".dat", new HMEFFileHandler()); }; public static boolean matches(String url) { for(String ext : EXTENSIONS) { if(url.endsWith(ext)) { return true; } } return false; } }
package org.g_node.micro.commons; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter; import com.hp.hpl.jena.rdf.model.Model; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RDFFormat; import org.apache.log4j.Logger; /** * Main service class for opening data from and saving data to an RDF file. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public final class RDFService { /** * Map returning the RDF formats supported by this service. */ public static final Map<String, RDFFormat> RDF_FORMAT_MAP = Collections.unmodifiableMap(new HashMap<String, RDFFormat>(3) { { put("TTL", RDFFormat.TURTLE_PRETTY); put("RDF/XML", RDFFormat.RDFXML); put("NTRIPLES", RDFFormat.NTRIPLES); put("JSON-LD", RDFFormat.JSONLD); } }); /** * Map RDF formats to the correct file ending. */ public static final Map<String, String> RDF_FORMAT_EXTENSION = Collections.unmodifiableMap(new HashMap<String, String>(3) { { put("TTL", "ttl"); put("RDF/XML", "rdf"); put("NTRIPLES", "nt"); put("JSON-LD", "jsonld"); } }); /** * Query results of this RDFService can be saved to these file formats. * Map keys should always be upper case. * Map values correspond to the file extensions that will be used to save the query results. */ public static final Map<String, String> QUERY_RESULT_FILE_FORMATS = Collections.unmodifiableMap(new HashMap<String, String>(0) { { put("CSV", "csv"); } }); /** * Access to the main LOGGER. */ private static final Logger LOGGER = Logger.getLogger(RDFService.class.getName()); /** * Open an RDF file, load the data and return the RDF model. Method will not check, * if the file is actually a valid RDF file or if the file extension matches * the content of the file. * @param fileName Path and filename of a valid RDF file. * @return Model created from the data within the provided RDF file. */ public static Model openModelFromFile(final String fileName) { return RDFDataMgr.loadModel(fileName); } /** * Write an RDF model to an output file using an RDF file format supported by this tool, specified * in {@link RDFService#RDF_FORMAT_MAP}. * This method will overwrite any files with the same path and filename. * @param fileName Path and filename of the output file. * @param model RDF model that's supposed to be written to the file. * @param format Output format of the RDF file. */ public static void saveModelToFile(final String fileName, final Model model, final String format) { final File file = new File(fileName); try { final FileOutputStream fos = new FileOutputStream(file); RDFService.LOGGER.info( String.join( "", "Writing data to RDF file '", fileName, "' using format '", format, "'" ) ); if (RDFService.RDF_FORMAT_MAP.containsKey(format)) { try { RDFDataMgr.write(fos, model, RDFService.RDF_FORMAT_MAP.get(format)); fos.close(); } catch (IOException ioExc) { RDFService.LOGGER.error("Error closing file stream."); } } else { RDFService.LOGGER.error( String.join("", "Error when saving output file: output format '", format, "' is not supported.") ); } } catch (FileNotFoundException exc) { RDFService.LOGGER.error(String.join("", "Could not open output file ", fileName)); } } /** * Helper method saving an RDF model to a file in a specified RDF format. * This method will overwrite any files with the same path and filename. * @param m Model that's supposed to be saved. * @param fileName Path and Name of the output file. * @param format Specified {@link RDFFormat} of the output file. */ public static void plainSaveModelToFile(final Model m, final String fileName, final RDFFormat format) { final File file = new File(fileName); try { final FileOutputStream fos = new FileOutputStream(file); try { RDFDataMgr.write(fos, m, format); fos.close(); } catch (IOException ioExc) { ioExc.printStackTrace(); } } catch (FileNotFoundException exc) { exc.printStackTrace(); } } /** * Helper method saving an RDF result set to a CSV file. * @param result RDF result set that will be saved to a CSV file. * @param fileName String containing Path and Name of the file the results are written to. */ public static void saveResultsToCsv(final ResultSet result, final String fileName) { String outFile = fileName; if (!FileService.checkFileExtension(outFile, "CSV")) { outFile = String.join("", outFile, ".csv"); } try { RDFService.LOGGER.info(String.join("", "Write query to file...\t\t(", outFile, ")")); final File file = new File(outFile); if (!file.exists()) { file.createNewFile(); } final FileOutputStream fop = new FileOutputStream(file); ResultSetFormatter.outputAsCSV(fop, result); fop.flush(); fop.close(); } catch (IOException e) { e.printStackTrace(); } } }
package org.lantern.http; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.lantern.Censored; import org.lantern.ConnectivityChangedEvent; import org.lantern.JsonUtils; import org.lantern.LanternClientConstants; import org.lantern.LanternUtils; import org.lantern.LogglyHelper; import org.lantern.MessageKey; import org.lantern.Messages; import org.lantern.SecurityUtils; import org.lantern.event.Events; import org.lantern.event.ResetEvent; import org.lantern.oauth.RefreshToken; import org.lantern.state.Connectivity; import org.lantern.state.FriendsHandler; import org.lantern.state.InternalState; import org.lantern.state.JsonModelModifier; import org.lantern.state.LocationChangedEvent; import org.lantern.state.Modal; import org.lantern.state.Mode; import org.lantern.state.Model; import org.lantern.state.ModelIo; import org.lantern.state.ModelService; import org.lantern.state.Settings; import org.lantern.state.SyncPath; import org.lantern.util.Desktop; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class InteractionServlet extends HttpServlet { private final InternalState internalState; // XXX DRY: these are also defined in lantern-ui/app/js/constants.js private enum Interaction { GET, GIVE, CONTINUE, SETTINGS, CLOSE, RESET, SET, PROXIEDSITES, CANCEL, LANTERNFRIENDS, RETRY, REQUESTINVITE, CONTACT, ABOUT, SPONSOR, ACCEPT, UNEXPECTEDSTATERESET, UNEXPECTEDSTATEREFRESH, URL, EXCEPTION, FRIEND, UPDATEAVAILABLE, CHANGELANG, REJECT } // modals the user can switch to from other modals private static final Set<Modal> switchModals = new HashSet<Modal>(); static { switchModals.add(Modal.about); switchModals.add(Modal.sponsor); switchModals.add(Modal.contact); switchModals.add(Modal.settings); switchModals.add(Modal.proxiedSites); switchModals.add(Modal.lanternFriends); switchModals.add(Modal.updateAvailable); } private final Logger log = LoggerFactory.getLogger(getClass()); /** * Generated serialization ID. */ private static final long serialVersionUID = -8820179746803371322L; private final ModelService modelService; private final Model model; private final ModelIo modelIo; private final Censored censored; private final LogglyHelper logglyHelper; private final FriendsHandler friender; private final Messages msgs; private RefreshToken refreshToken; @Inject public InteractionServlet(final Model model, final ModelService modelService, final InternalState internalState, final ModelIo modelIo, final Censored censored, final LogglyHelper logglyHelper, final FriendsHandler friender, final Messages msgs, final RefreshToken refreshToken) { this.model = model; this.modelService = modelService; this.internalState = internalState; this.modelIo = modelIo; this.censored = censored; this.logglyHelper = logglyHelper; this.friender = friender; this.msgs = msgs; this.refreshToken = refreshToken; Events.register(this); } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } protected void processRequest(final HttpServletRequest req, final HttpServletResponse resp) { LanternUtils.addCSPHeader(resp); final String uri = req.getRequestURI(); log.debug("Received URI: {}", uri); final String interactionStr = StringUtils.substringAfterLast(uri, "/"); if (StringUtils.isBlank(interactionStr)) { log.debug("blank interaction"); HttpUtils.sendClientError(resp, "blank interaction"); return; } log.debug("Headers: "+HttpUtils.getRequestHeaders(req)); if (!"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) { log.debug("invalid X-Requested-With"); HttpUtils.sendClientError(resp, "invalid X-Requested-With"); return; } if (!SecurityUtils.constantTimeEquals(model.getXsrfToken(), req.getHeader("X-XSRF-TOKEN"))) { log.debug("X-XSRF-TOKEN wrong: got {} expected {}", req.getHeader("X-XSRF-TOKEN"), model.getXsrfToken()); HttpUtils.sendClientError(resp, "invalid X-XSRF-TOKEN"); return; } final int cl = req.getContentLength(); String json = ""; if (cl > 0) { try { json = IOUtils.toString(req.getInputStream()); } catch (final IOException e) { log.error("Could not parse json?"); } } log.debug("Body: '"+json+"'"); final Interaction inter = Interaction.valueOf(interactionStr.toUpperCase()); if (inter == Interaction.CLOSE) { if (handleClose(json)) { return; } } if (inter == Interaction.URL) { final String url = JsonUtils.getValueFromJson("url", json); if (!StringUtils.startsWith(url, "http: !StringUtils.startsWith(url, "https: log.error("http(s) url expected, got {}", url); HttpUtils.sendClientError(resp, "http(s) urls only"); return; } try { new URL(url); } catch (MalformedURLException e) { log.error("invalid url: {}", url); HttpUtils.sendClientError(resp, "invalid url"); return; } final String cmd; if (SystemUtils.IS_OS_MAC_OSX) { cmd = "open"; } else if (SystemUtils.IS_OS_LINUX) { cmd = "gnome-open"; } else if (SystemUtils.IS_OS_WINDOWS) { cmd = "start"; } else { log.error("unsupported OS"); HttpUtils.sendClientError(resp, "unsupported OS"); return; } try { if (SystemUtils.IS_OS_WINDOWS) { // On Windows, we have to quote the url to allow for // e.g. ? and & characters in query string params. // To quote the url, we supply a dummy first argument, // since otherwise start treats the first argument as a // title for the new console window when it's quoted. LanternUtils.runCommand(cmd, "\"\"", "\""+url+"\""); } else { // on OS X and Linux, special characters in the url make // it through this call without our having to quote them. LanternUtils.runCommand(cmd, url); } } catch (IOException e) { log.error("open url failed"); HttpUtils.sendClientError(resp, "open url failed"); return; } return; } final Modal modal = this.model.getModal(); log.debug("processRequest: modal = {}, inter = {}, mode = {}", modal, inter, this.model.getSettings().getMode()); if (handleExceptionInteractions(modal, inter, json)) { return; } Modal switchTo = null; try { // XXX a map would make this more robust switchTo = Modal.valueOf(interactionStr); } catch (IllegalArgumentException e) { } if (switchTo != null && switchModals.contains(switchTo)) { if (!switchTo.equals(modal)) { if (!switchModals.contains(modal)) { this.internalState.setLastModal(modal); } Events.syncModal(model, switchTo); } return; } switch (modal) { case welcome: this.model.getSettings().setMode(Mode.unknown); switch (inter) { case GET: log.debug("Setting get mode"); handleSetModeWelcome(Mode.get); break; case GIVE: log.debug("Setting give mode"); handleSetModeWelcome(Mode.give); break; } break; case authorize: log.debug("Processing authorize modal..."); this.internalState.setModalCompleted(Modal.authorize); this.internalState.advanceModal(null); break; case finished: this.internalState.setCompletedTo(Modal.finished); switch (inter) { case CONTINUE: log.debug("Processing continue"); this.model.setShowVis(true); Events.sync(SyncPath.SHOWVIS, true); this.internalState.setModalCompleted(Modal.finished); this.internalState.advanceModal(null); break; case SET: log.debug("Processing set in finished modal...applying JSON\n{}", json); applyJson(json); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); break; } break; case firstInviteReceived: log.error("Processing invite received..."); break; case lanternFriends: this.internalState.setCompletedTo(Modal.lanternFriends); switch (inter) { case FRIEND: this.friender.addFriend(email(json)); break; case REJECT: this.friender.removeFriend(email(json)); break; case CONTINUE: // This dialog always passes continue as of this writing and // not close. case CLOSE: log.debug("Processing continue/close for friends dialog"); if (this.model.isSetupComplete()) { Events.syncModal(model, Modal.none); } else { this.internalState.setModalCompleted(Modal.lanternFriends); this.internalState.advanceModal(null); } break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); break; } break; case none: break; case notInvited: switch (inter) { case RETRY: log.debug("Switching to authorize modal"); // We need to kill all the existing oauth tokens. resetOauth(); Events.syncModal(model, Modal.authorize); break; // not currently implemented: //case REQUESTINVITE: // Events.syncModal(model, Modal.requestInvite); // break; default: log.error("Unexpected interaction: " + inter); break; } break; case proxiedSites: this.internalState.setCompletedTo(Modal.proxiedSites); switch (inter) { case CONTINUE: if (this.model.isSetupComplete()) { Events.syncModal(model, Modal.none); } else { this.internalState.setModalCompleted(Modal.proxiedSites); this.internalState.advanceModal(null); } break; case LANTERNFRIENDS: log.debug("Processing lanternFriends from proxiedSites"); Events.syncModal(model, Modal.lanternFriends); break; case SET: if (!model.getSettings().isSystemProxy()) { this.msgs.info(MessageKey.MANUAL_PROXY); } applyJson(json); break; case SETTINGS: log.debug("Processing settings from proxiedSites"); Events.syncModal(model, Modal.settings); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "unexpected interaction for proxied sites"); break; } break; case requestInvite: log.info("Processing request invite"); switch (inter) { case CANCEL: this.internalState.setModalCompleted(Modal.requestInvite); this.internalState.advanceModal(Modal.notInvited); break; case CONTINUE: applyJson(json); this.internalState.setModalCompleted(Modal.proxiedSites); //TODO: need to do something here this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "unexpected interaction for request invite"); break; } break; case requestSent: log.debug("Process request sent"); break; case settings: switch (inter) { case GET: log.debug("Setting get mode"); // Only deal with a mode change if the mode has changed! if (modelService.getMode() == Mode.give) { // Break this out because it's set in the subsequent // setMode call final boolean everGet = model.isEverGetMode(); this.modelService.setMode(Mode.get); if (!everGet) { // need to do more setup to switch to get mode from // give mode model.setSetupComplete(false); model.setModal(Modal.proxiedSites); Events.syncModel(model); } else { // This primarily just triggers a setup complete event, // which triggers connecting to proxies, setting up // the local system proxy, etc. model.setSetupComplete(true); } } break; case GIVE: log.debug("Setting give mode"); this.modelService.setMode(Mode.give); break; case CLOSE: log.debug("Processing settings close"); Events.syncModal(model, Modal.none); break; case SET: log.debug("Processing set in setting...applying JSON\n{}", json); applyJson(json); break; case RESET: log.debug("Processing reset"); Events.syncModal(model, Modal.confirmReset); break; case PROXIEDSITES: log.debug("Processing proxied sites in settings"); Events.syncModal(model, Modal.proxiedSites); break; case LANTERNFRIENDS: log.debug("Processing friends in settings"); Events.syncModal(model, Modal.lanternFriends); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); break; } break; case settingsLoadFailure: switch (inter) { case RETRY: maybeSubmitToLoggly(json); if (!modelIo.reload()) { this.msgs.error(MessageKey.LOAD_SETTINGS_ERROR); } Events.syncModal(model, model.getModal()); break; case RESET: maybeSubmitToLoggly(json); backupSettings(); Events.syncModal(model, Modal.welcome); break; default: maybeSubmitToLoggly(json); log.error("Did not handle interaction {} for modal {}", inter, modal); break; } break; case systemProxy: this.internalState.setCompletedTo(Modal.systemProxy); switch (inter) { case CONTINUE: log.debug("Processing continue in systemProxy", json); applyJson(json); Events.sync(SyncPath.SYSTEMPROXY, model.getSettings().isSystemProxy()); this.internalState.setModalCompleted(Modal.systemProxy); this.internalState.advanceModal(null); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "error setting system proxy pref"); break; } break; case updateAvailable: switch (inter) { case CLOSE: Events.syncModal(model, this.internalState.getLastModal()); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); break; } break; case authorizeLater: log.error("Did not handle interaction {} for modal {}", inter, modal); break; case confirmReset: log.debug("Handling confirm reset interaction"); switch (inter) { case CANCEL: log.debug("Processing cancel"); Events.syncModal(model, Modal.settings); break; case RESET: handleReset(); Events.syncModel(this.model); break; default: log.error("Did not handle interaction {} for modal {}", inter, modal); HttpUtils.sendClientError(resp, "Interaction not handled for modal: "+modal+ " and interaction: "+inter); } break; case about: // fall through on purpose case sponsor: switch (inter) { case CLOSE: Events.syncModal(model, this.internalState.getLastModal()); break; default: HttpUtils.sendClientError(resp, "invalid interaction "+inter); } break; case contact: switch(inter) { case CONTINUE: maybeSubmitToLoggly(json, true); // fall through because this should be done in both cases: case CANCEL: Events.syncModal(model, this.internalState.getLastModal()); break; default: maybeSubmitToLoggly(json, true); HttpUtils.sendClientError(resp, "invalid interaction "+inter); } break; case giveModeForbidden: if (inter == Interaction.CONTINUE) { // need to do more setup to switch to get mode from give mode model.getSettings().setMode(Mode.get); model.setSetupComplete(false); this.internalState.advanceModal(null); Events.syncModal(model, Modal.proxiedSites); Events.sync(SyncPath.SETUPCOMPLETE, false); } break; default: log.error("No matching modal for {}", modal); } this.modelIo.write(); } private void resetOauth() { log.debug("Resetting oauth..."); this.refreshToken.reset(); this.model.getSettings().setRefreshToken(""); this.model.getSettings().setAccessToken(""); this.model.getSettings().setExpiryTime(0L); } private String email(final String json) { return JsonUtils.getValueFromJson("email", json).toLowerCase(); } private void backupSettings() { try { File backup = new File(Desktop.getDesktopPath(), "lantern-model-backup"); FileUtils.copyFile(LanternClientConstants.DEFAULT_MODEL_FILE, backup); } catch (final IOException e) { log.warn("Could not backup model file."); } } private boolean handleExceptionInteractions( final Modal modal, final Interaction inter, final String json) { boolean handled = false; switch(inter) { case EXCEPTION: handleException(json); handled = true; break; case UNEXPECTEDSTATERESET: log.debug("Handling unexpected state reset."); backupSettings(); handleReset(); Events.syncModel(this.model); // fall through because this should be done in both cases: case UNEXPECTEDSTATEREFRESH: log.debug("Handling unexpected state refresh."); maybeSubmitToLoggly(json); handled = true; break; } return handled; } /** * Used to submit user feedback from contact form as well as bug reports * during e.g. settingsLoadFailure or unexpectedState describing what * happened * * @param json JSON with user's message + contextual information. If blank * (can happen when user chooses not to notify developers) we do nothing. * @param showNotification whether to show a success or failure notification * upon submit */ private void maybeSubmitToLoggly(String json, boolean showNotification) { if (StringUtils.isBlank(json)) return; try { logglyHelper.submit(json); if (showNotification) { this.msgs.info(MessageKey.CONTACT_THANK_YOU); } } catch(Exception e) { if (showNotification) { this.msgs.error(MessageKey.CONTACT_ERROR, e); } log.error("Could not submit: {}\n {}", e.getMessage(), json); } } private void maybeSubmitToLoggly(String json) { maybeSubmitToLoggly(json, false); } private void handleException(final String json) { log.error("Exception from UI:\n{}", json); } private boolean handleClose(String json) { if (StringUtils.isBlank(json)) { return false; } Map<String, Object> map; try { map = JsonUtils.OBJECT_MAPPER.readValue(json, Map.class); final String notification = (String) map.get("notification"); model.closeNotification(Integer.parseInt(notification)); Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications()); return true; } catch (JsonParseException e) { log.warn("Exception closing notifications {}", e); } catch (JsonMappingException e) { log.warn("Exception closing notifications {}", e); } catch (IOException e) { log.warn("Exception closing notifications {}", e); } return false; } private void handleSetModeWelcome(final Mode mode) { this.model.setModal(Modal.authorize); this.internalState.setModalCompleted(Modal.welcome); this.modelService.setMode(mode); Events.syncModal(model); } private void applyJson(final String json) { final JsonModelModifier mod = new JsonModelModifier(modelService); mod.applyJson(json); } private void handleReset() { // This posts the reset event to any classes that need to take action, // avoiding coupling this class to those classes. Events.eventBus().post(new ResetEvent()); if (LanternClientConstants.DEFAULT_MODEL_FILE.isFile()) { try { FileUtils.forceDelete(LanternClientConstants.DEFAULT_MODEL_FILE); } catch (final IOException e) { log.warn("Could not delete model file?"); } } resetOauth(); final Model base = new Model(model.getCountryService()); model.setEverGetMode(false); model.setLaunchd(base.isLaunchd()); model.setModal(base.getModal()); model.setNodeId(base.getNodeId()); model.setProfile(base.getProfile()); model.setNproxiedSitesMax(base.getNproxiedSitesMax()); //we need to keep clientID and clientSecret, because they are application-level settings String clientID = model.getSettings().getClientID(); String clientSecret = model.getSettings().getClientSecret(); model.setSettings(base.getSettings()); model.getSettings().setClientID(clientID); model.getSettings().setClientSecret(clientSecret); model.setSetupComplete(base.isSetupComplete()); model.setShowVis(base.isShowVis()); //model.setFriends(base.getFriends()); model.clearNotifications(); modelIo.write(); } @Subscribe public void onLocationChanged(final LocationChangedEvent e) { Events.sync(SyncPath.LOCATION, e.getNewLocation()); if (censored.isCountryCodeCensored(e.getNewCountry())) { if (!censored.isCountryCodeCensored(e.getOldCountry())) { //moving from uncensored to censored if (model.getSettings().getMode() == Mode.give) { Events.syncModal(model, Modal.giveModeForbidden); } } } } @Subscribe public void onConnectivityChanged(final ConnectivityChangedEvent e) { Connectivity connectivity = model.getConnectivity(); if (!e.isConnected()) { connectivity.setInternet(false); Events.sync(SyncPath.CONNECTIVITY_INTERNET, false); return; } InetAddress ip = e.getNewIp(); connectivity.setIp(ip.getHostAddress()); connectivity.setInternet(true); Events.sync(SyncPath.CONNECTIVITY, model.getConnectivity()); Settings set = model.getSettings(); if (set.getMode() == null || set.getMode() == Mode.unknown) { if (censored.isCensored()) { set.setMode(Mode.get); } } else if (set.getMode() == Mode.give && censored.isCensored()) { // want to set the mode to get now so that we don't mistakenly // proxy any more than necessary set.setMode(Mode.get); log.info("Disconnected; setting giveModeForbidden"); Events.syncModal(model, Modal.giveModeForbidden); } } }
package org.lightmare.jndi; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import javax.naming.NamingException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.transaction.UserTransaction; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.TransactionContainer; import org.lightmare.ejb.EjbConnector; import org.lightmare.jpa.JpaManager; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.NamingUtils; import org.lightmare.utils.ObjectUtils; import org.osjava.sj.memory.MemoryContext; /** * Implementation of simple JNDI {@link MemoryContext} for EJB bean interface, * {@link UserTransaction} and {@link EntityManager} caching and retrieving * * @author levan * */ public class LightmareContext extends MemoryContext { // Caches EntityManager instances got from lookup method to clear after private Collection<WeakReference<EntityManager>> ems = new ArrayList<WeakReference<EntityManager>>(); public LightmareContext(Hashtable<?, ?> env) { super(env); } /** * Caches resources to close them after {@link LightmareContext#close()} * method is called * * @param resource */ private void cacheResource(Object resource) { if (ObjectUtils.notNull(resource) && resource instanceof EntityManager) { EntityManager em = ObjectUtils.cast(resource, EntityManager.class); WeakReference<EntityManager> ref = new WeakReference<EntityManager>( em); ems.add(ref); } } @Override public Object lookup(String jndiName) throws NamingException { Object value; String name; if (jndiName.equals(NamingUtils.USER_TRANSACTION_NAME)) { UserTransaction transaction = TransactionContainer.getTransaction(); value = transaction; } else if (jndiName.startsWith(NamingUtils.JPA_NAME_PREF)) { // Checks if it is request for entity manager name = NamingUtils.formatJpaJndiName(jndiName); // Checks if connection is in progress and waits for finish ConnectionContainer.isInProgress(name); // Gets EntityManagerFactory from parent Object candidate = super.lookup(jndiName); if (candidate == null) { value = candidate; } else if (candidate instanceof EntityManagerFactory) { EntityManagerFactory emf = ObjectUtils.cast(candidate, EntityManagerFactory.class); EntityManager em = emf.createEntityManager(); value = em; } else { value = candidate; } } else if (jndiName.startsWith(NamingUtils.EJB_NAME_PREF)) { NamingUtils.BeanDescriptor descriptor = NamingUtils .parseEjbJndiName(jndiName); EjbConnector ejbConnection = new EjbConnector(); try { String beanName = descriptor.getBeanName(); String interfaceName = descriptor.getInterfaceName(); value = ejbConnection.connectToBean(beanName, interfaceName); } catch (IOException ex) { throw new NamingException(ex.getMessage()); } } else { value = super.lookup(jndiName); } // Saves value to clear after close method is called cacheResource(value); return value; } /** * Clears and closes all cached resources */ private void clearResources() { if (CollectionUtils.valid(ems)) { try { EntityManager em; for (WeakReference<EntityManager> ref : ems) { em = ref.get(); JpaManager.closeEntityManager(em); } } finally { ems.clear(); } } } @Override public void close() throws NamingException { clearResources(); // TODO: Must check is needed super.close() method call // super.close(); } }
package org.lightmare.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utility class to work with {@link Collection} instances * * @author Levan * */ public class CollectionUtils { /** * Creates new {@link Set} from passed {@link Collection} instance * * @param collection * @return {@link Set}<code><T></code> */ public static <T> Set<T> translateToSet(Collection<T> collection) { Set<T> set; if (ObjectUtils.available(collection)) { set = new HashSet<T>(collection); } else { set = Collections.emptySet(); } return set; } /** * Creates new {@link Set} from passed array instance * * @param array * @return {@link Set}<code><T></code> */ public static <T> Set<T> translateToSet(T[] array) { List<T> collection; if (ObjectUtils.available(array)) { collection = Arrays.asList(array); } else { collection = null; } return translateToSet(collection); } /** * Creates new {@link List} from passed {@link Collection} instance * * @param collection * @return {@link List}<code><T></code> */ public static <T> List<T> translateToList(Collection<T> collection) { List<T> list; if (ObjectUtils.available(collection)) { list = new ArrayList<T>(collection); } else { list = Collections.emptyList(); } return list; } }
package org.minimalj.frontend.editor; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.minimalj.application.DevMode; import org.minimalj.frontend.Frontend; import org.minimalj.frontend.action.Action; import org.minimalj.frontend.form.Form; import org.minimalj.frontend.page.IDialog; import org.minimalj.model.properties.PropertyInterface; import org.minimalj.model.validation.Validation; import org.minimalj.model.validation.ValidationMessage; import org.minimalj.util.CloneHelper; import org.minimalj.util.ExceptionUtils; import org.minimalj.util.mock.Mocking; public abstract class Editor<T, RESULT> extends Action { private static final Logger logger = Logger.getLogger(Editor.class.getName()); private T object; private Form<T> form; private final List<ValidationMessage> validationMessages = new ArrayList<>(); private SaveAction saveAction; private IDialog dialog; public Editor() { super(); } public Editor(String actionName) { super(actionName); } public String getTitle() { return getName(); } @Override public void action() { object = createObject(); form = createForm(); saveAction = new SaveAction(); validate(); form.setChangeListener(new EditorChangeListener()); form.setObject(object); dialog = Frontend.getBrowser().showDialog(getTitle(), form.getContent(), saveAction, new CancelAction(), createActions()); } private Action[] createActions() { List<Action> additionalActions = createAdditionalActions(); Action[] actions = new Action[additionalActions.size() + 2]; int index; for (index = 0; index<additionalActions.size(); index++) { actions[index] = additionalActions.get(index); } actions[index++] = new CancelAction(); actions[index++] = saveAction; return actions; } protected List<Action> createAdditionalActions() { List<Action> actions = new ArrayList<Action>(); if (DevMode.isActive()) { actions.add(new FillWithDemoDataAction()); } return actions; } protected abstract T createObject(); protected T getObject() { return object; } protected abstract Form<T> createForm(); private void validate() { validationMessages.clear(); if (object instanceof Validation) { ((Validation) object).validate(validationMessages); } ObjectValidator.validateForEmpty(object, validationMessages, form.getProperties()); ObjectValidator.validateForInvalid(object, validationMessages, form.getProperties()); ObjectValidator.validatePropertyValues(object, validationMessages, form.getProperties()); validate(object, validationMessages); form.indicate(validationMessages); saveAction.setValidationMessages(validationMessages); } protected void validate(T object, List<ValidationMessage> validationMessages) { } private void save() { try { RESULT result = save(object); dialog.closeDialog(); finished(result); } catch (Exception x) { ExceptionUtils.logReducedStackTrace(logger, x); Frontend.getBrowser().showError(x.getLocalizedMessage()); return; } } protected abstract RESULT save(T object); protected void finished(RESULT result) { } private class EditorChangeListener implements Form.FormChangeListener<T> { @Override public void changed(PropertyInterface property, Object newValue) { validate(); } @Override public void commit() { if (isSaveable()) { save(); } } } private boolean isSaveable() { return validationMessages.isEmpty(); } protected final class SaveAction extends Action { private String description; private boolean valid = false; @Override public void action() { save(); } public void setValidationMessages(List<ValidationMessage> validationMessages) { valid = validationMessages == null || validationMessages.isEmpty(); if (valid) { description = "Eingaben speichern"; } else { description = ValidationMessage.formatHtml(validationMessages); } fireChange(); } @Override public boolean isEnabled() { return valid; } @Override public String getDescription() { return description; } } private class CancelAction extends Action { @Override public void action() { cancel(); } } public void cancel() { dialog.closeDialog(); } private class FillWithDemoDataAction extends Action { @Override public void action() { fillWithDemoData(); validate(); } } protected void fillWithDemoData() { if (object instanceof Mocking) { ((Mocking) object).mock(); form.setObject(object); } else { form.mock(); } } public static abstract class SimpleEditor<T> extends Editor<T, T> { public SimpleEditor() { } public SimpleEditor(String actionName) { super(actionName); } @Override protected T save(T changedObject) { return changedObject; } } public static abstract class NewObjectEditor<T> extends Editor<T, Object> { public NewObjectEditor() { } public NewObjectEditor(String actionName) { super(actionName); } @Override protected T createObject() { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) org.minimalj.util.GenericUtils.getGenericClass(NewObjectEditor.this.getClass()); T newInstance = CloneHelper.newInstance(clazz); return newInstance; } } }
package org.myrobotlab.oculus; import static com.oculusvr.capi.OvrLibrary.OVR_DEFAULT_IPD; import static com.oculusvr.capi.OvrLibrary.ovrProjectionModifier.ovrProjection_ClipRangeOpenGL; import static org.lwjgl.opengl.GL11.GL_BACK; import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_CULL_FACE; import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST; import static org.lwjgl.opengl.GL11.GL_FRONT; import static org.lwjgl.opengl.GL11.GL_LINEAR_MIPMAP_NEAREST; import static org.lwjgl.opengl.GL11.GL_NEAREST; import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MAG_FILTER; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MIN_FILTER; import static org.lwjgl.opengl.GL11.GL_TRIANGLE_STRIP; import static org.lwjgl.opengl.GL11.glBindTexture; import static org.lwjgl.opengl.GL11.glClear; import static org.lwjgl.opengl.GL11.glClearColor; import static org.lwjgl.opengl.GL11.glCullFace; import static org.lwjgl.opengl.GL11.glDeleteTextures; import static org.lwjgl.opengl.GL11.glDisable; import static org.lwjgl.opengl.GL11.glDrawArrays; import static org.lwjgl.opengl.GL11.glEnable; import static org.lwjgl.opengl.GL11.glGetError; import static org.lwjgl.opengl.GL11.glScissor; import static org.lwjgl.opengl.GL11.glViewport; import static org.lwjgl.opengl.GL30.GL_COLOR_ATTACHMENT0; import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER; import static org.lwjgl.opengl.GL30.glFramebufferTexture2D; import static org.lwjgl.opengl.GL30.glGenerateMipmap; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import static org.lwjgl.glfw.GLFW.*; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWFramebufferSizeCallback; import org.lwjgl.glfw.GLFWKeyCallback; import org.lwjgl.glfw.GLFWMouseButtonCallback; import org.lwjgl.glfw.GLFWVidMode; import org.lwjgl.opengl.GL; import org.myrobotlab.image.SerializableImage; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.OculusRift; import org.myrobotlab.service.OculusRift.RiftFrame; import org.myrobotlab.service.data.Orientation; import org.saintandreas.gl.FrameBuffer; import org.saintandreas.gl.IndexedGeometry; import org.saintandreas.gl.MatrixStack; import org.saintandreas.gl.OpenGL; import org.saintandreas.gl.buffers.VertexArray; import org.saintandreas.gl.shaders.Program; import org.saintandreas.gl.textures.Texture; import org.saintandreas.math.Matrix4f; import org.saintandreas.math.Quaternion; import org.saintandreas.math.Vector2f; import org.saintandreas.math.Vector3f; import org.saintandreas.resources.Resource; import static org.saintandreas.ExampleResource.IMAGES_SKY_CITY_XNEG_PNG; import static org.saintandreas.ExampleResource.IMAGES_SKY_CITY_XPOS_PNG; import static org.saintandreas.ExampleResource.IMAGES_SKY_CITY_YNEG_PNG; import static org.saintandreas.ExampleResource.IMAGES_SKY_CITY_YPOS_PNG; import static org.saintandreas.ExampleResource.IMAGES_SKY_CITY_ZNEG_PNG; import static org.saintandreas.ExampleResource.IMAGES_SKY_CITY_ZPOS_PNG; import org.slf4j.Logger; import com.oculusvr.capi.EyeRenderDesc; import com.oculusvr.capi.FovPort; import com.oculusvr.capi.Hmd; import com.oculusvr.capi.HmdDesc; import com.oculusvr.capi.LayerEyeFov; import com.oculusvr.capi.MirrorTexture; import com.oculusvr.capi.MirrorTextureDesc; import com.oculusvr.capi.OvrLibrary; import com.oculusvr.capi.OvrMatrix4f; import com.oculusvr.capi.OvrQuaternionf; import com.oculusvr.capi.OvrRecti; import com.oculusvr.capi.OvrSizei; import com.oculusvr.capi.OvrVector2i; import com.oculusvr.capi.OvrVector3f; import com.oculusvr.capi.Posef; import com.oculusvr.capi.TextureSwapChain; import com.oculusvr.capi.TextureSwapChainDesc; import com.oculusvr.capi.ViewScaleDesc; public class OculusDisplay implements Runnable { public final static Logger log = LoggerFactory.getLogger(OculusDisplay.class); // handle to the glfw window private long window = 0; // lwjgl3 callback private GLFWErrorCallback errorCallback; // A reference to the framebuffer size callback. private GLFWFramebufferSizeCallback framebufferSizeCallback; // operate the display on a thread so we don't block transient Thread displayThread = null; // the oculus service transient public OculusRift oculus; private int width; private int height; private float ipd; private float eyeHeight; transient protected Hmd hmd; transient protected HmdDesc hmdDesc; private final FovPort[] fovPorts = FovPort.buildPair(); protected final Posef[] poses = Posef.buildPair(); private final Matrix4f[] projections = new Matrix4f[2]; private final OvrVector3f[] eyeOffsets = OvrVector3f.buildPair(); private final OvrSizei[] textureSizes = new OvrSizei[2]; private final ViewScaleDesc viewScaleDesc = new ViewScaleDesc(); private FrameBuffer frameBuffer = null; // keep track of how many frames we have submitted to the display. private int frameCount = -1; private TextureSwapChain swapChain = null; // a texture to mirror what is displayed on the rift. private MirrorTexture mirrorTexture = null; // this is what gets submitted to the rift for display. private LayerEyeFov layer = new LayerEyeFov(); // The last image captured from the OpenCV services (left&right) private RiftFrame currentFrame; private static Program unitQuadProgram; private static VertexArray unitQuadVao; private static final String UNIT_QUAD_VS; private static final String UNIT_QUAD_FS; private static final String SHADERS_TEXTURED_VS; private static final String SHADERS_TEXTURED_FS; private static final String SHADERS_CUBEMAP_VS; private static final String SHADERS_CUBEMAP_FS; private static IndexedGeometry screenGeometry; private static Program screenProgram; private static IndexedGeometry cubeGeometry; private static Program skyboxProgram; private static Texture skyboxTexture; private volatile boolean newFrame = true; private float screenSize = 1.0f; public volatile boolean trackHead = true; static { UNIT_QUAD_VS = FileIO.resourceToString("OculusRift" + File.separator + "unitQuad.vs"); UNIT_QUAD_FS = FileIO.resourceToString("OculusRift" + File.separator + "unitQuad.fs"); SHADERS_TEXTURED_FS = FileIO.resourceToString("OculusRift" + File.separator + "Textured.fs"); SHADERS_TEXTURED_VS = FileIO.resourceToString("OculusRift" + File.separator + "Textured.vs"); SHADERS_CUBEMAP_VS = FileIO.resourceToString("OculusRift" + File.separator + "CubeMap.vs"); SHADERS_CUBEMAP_FS = FileIO.resourceToString("OculusRift" + File.separator + "CubeMap.fs"); } private static final Resource SKYBOX[] = { IMAGES_SKY_CITY_XPOS_PNG, IMAGES_SKY_CITY_XNEG_PNG, IMAGES_SKY_CITY_YPOS_PNG, IMAGES_SKY_CITY_YNEG_PNG, IMAGES_SKY_CITY_ZPOS_PNG, IMAGES_SKY_CITY_ZNEG_PNG, }; public Orientation orientationInfo; // textures for the screen one for the left eye, one for the right eye. private Texture leftTexture; private Texture rightTexture; public OculusDisplay() { } private void recenterView() { org.saintandreas.math.Vector3f center = org.saintandreas.math.Vector3f.UNIT_Y.mult(eyeHeight); org.saintandreas.math.Vector3f eye = new org.saintandreas.math.Vector3f(0, eyeHeight, ipd * 10.0f); MatrixStack.MODELVIEW.lookat(eye, center, org.saintandreas.math.Vector3f.UNIT_Y); hmd.recenterPose(); } public void updateOrientation(Orientation orientation) { // TODO: we can probably remove this , the orientation info is known when // we're rendering. this.orientationInfo = orientation; } // sets up the opengl display for rendering the mirror texture. protected final long setupDisplay() { // our size. / resolution? is this configurable? maybe not? width = hmdDesc.Resolution.w / 4; height = hmdDesc.Resolution.h / 4; // TODO: these were to specify where the glfw window would be placed on the monitor.. // int left = 100; // int right = 100; // try { // Display.setDisplayMode(new DisplayMode(width, height)); // } catch (LWJGLException e) { // throw new RuntimeException(e); // Display.setTitle("MRL Oculus Rift Viewer"); // TODO: which one?? long monitor = 0; long window = glfwCreateWindow(width, height, "MRL Oculus Rift Viewer", monitor, 0); if(window == 0) { throw new RuntimeException("Failed to create window"); } // Make this window's context the current on this thread. glfwMakeContextCurrent(window); // Let LWJGL know to use this current context. GL.createCapabilities(); //Setup the framebuffer resize callback. glfwSetFramebufferSizeCallback(window, (framebufferSizeCallback = new GLFWFramebufferSizeCallback() { @Override public void invoke(long window, int width, int height) { onResize(width, height); } })); // TODO: set location and vsync?! Do we need to update these for lwjgl3? // Display.setLocation(left, right); // TODO: vsync enabled? // Display.setVSyncEnabled(true); onResize(width, height); log.info("Setup Oculus Diplsay with resolution " + width + "x" + height); return window; } // if the window is resized. protected void onResize(int width, int height) { this.width = width; this.height = height; } // initialize the oculus hmd private void internalInit() { // start up hmd libs initHmd(); // initialize the opengl rendering context initGl(); // look ahead recenterView(); } // oculus device initialization, assumes that oculus runtime is up and running // on the server. private void initHmd() { if (hmd == null) { Hmd.initialize(); try { Thread.sleep(400); } catch (InterruptedException e) { throw new IllegalStateException(e); } // create it (this should be owned by the Oculus service i think? and // passed in with setHmd(hmd) hmd = Hmd.create(); } if (null == hmd) { throw new IllegalStateException("Unable to initialize HMD"); } // grab the description of the device. hmdDesc = hmd.getDesc(); // hmd.recenterPose(); for (int eye = 0; eye < 2; ++eye) { fovPorts[eye] = hmdDesc.DefaultEyeFov[eye]; OvrMatrix4f m = Hmd.getPerspectiveProjection(fovPorts[eye], 0.1f, 1000000f, ovrProjection_ClipRangeOpenGL); projections[eye] = toMatrix4f(m); textureSizes[eye] = hmd.getFovTextureSize(eye, fovPorts[eye], 1.0f); } // TODO: maybe ipd and eyeHeight go away? ipd = hmd.getFloat(OvrLibrary.OVR_KEY_IPD, OVR_DEFAULT_IPD); // eyeHeight = hmd.getFloat(OvrLibrary.OVR_KEY_EYE_HEIGHT, OVR_DEFAULT_EYE_HEIGHT); eyeHeight = 0; } // Main rendering loop for running the oculus display. public void run() { internalInit(); // Load the screen in the scene i guess first. while (!glfwWindowShouldClose(window)) { //while (!Display.isCloseRequested()) { // TODO: resize testing.. make sure it's handle via the other callback? or something // if (Display.wasResized()) { // onResize(Display.getWidth(), Display.getHeight()); update(); drawFrame(); finishFrame(); } onDestroy(); // Display.destroy(); glfwDestroyWindow(window); } public final void drawFrame() { // System.out.println("Draw Frame called."); if (currentFrame == null) { return; } if (currentFrame.left == null || currentFrame.right == null) { return; } // load new textures if a new rift frame has arrived. if (newFrame) { loadRiftFrameTextures(); newFrame = false; } width = hmdDesc.Resolution.w / 4; height = hmdDesc.Resolution.h / 4; ++frameCount; Posef eyePoses[] = hmd.getEyePoses(frameCount, eyeOffsets); frameBuffer.activate(); MatrixStack pr = MatrixStack.PROJECTION; MatrixStack mv = MatrixStack.MODELVIEW; int textureId = swapChain.getTextureId(swapChain.getCurrentIndex()); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0); for (int eye = 0; eye < 2; ++eye) { OvrRecti vp = layer.Viewport[eye]; glScissor(vp.Pos.x, vp.Pos.y, vp.Size.w, vp.Size.h); glViewport(vp.Pos.x, vp.Pos.y, vp.Size.w, vp.Size.h); pr.set(projections[eye]); Posef pose = eyePoses[eye]; // This doesn't work as it breaks the contiguous nature of the array // FIXME there has to be a better way to do this poses[eye].Orientation = pose.Orientation; poses[eye].Position = pose.Position; if (trackHead) mv.push().preTranslate(toVector3f(poses[eye].Position).mult(-1)).preRotate(toQuaternion(poses[eye].Orientation).inverse()); // TODO: is there a way to render both of these are the same time? if (eye == 0 && currentFrame.left != null) { renderScreen(leftTexture, orientationInfo); } else if (eye == 1 && currentFrame.right != null) { renderScreen(rightTexture, orientationInfo); } if (trackHead) { mv.pop(); } } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); frameBuffer.deactivate(); swapChain.commit(); hmd.submitFrame(frameCount, layer); // FIXME Copy the layer to the main window using a mirror texture glScissor(0, 0, width, height); glViewport(0, 0, width, height); glClearColor(0.5f, 0.5f, System.currentTimeMillis() % 1000 / 1000.0f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render the quad with our images/textures on it, one for the left eye, one for the right eye. renderTexturedQuad(mirrorTexture.getTextureId()); } private void loadRiftFrameTextures() { // if the left & right texture are already loaded, let's delete them if (leftTexture != null) glDeleteTextures(leftTexture.id); if (rightTexture != null) glDeleteTextures(rightTexture.id); // here we can just update the textures that we're using leftTexture = Texture.loadImage(currentFrame.left.getImage()); rightTexture = Texture.loadImage(currentFrame.right.getImage()); leftTexture.bind(); leftTexture.parameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST); leftTexture.parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glGenerateMipmap(GL_TEXTURE_2D); leftTexture.unbind(); rightTexture.bind(); rightTexture.parameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST); rightTexture.parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glGenerateMipmap(GL_TEXTURE_2D); rightTexture.unbind(); } protected void finishFrame() { // Display update combines both input processing and // buffer swapping. We want only the input processing // so we have to call processMessages. // Display.processMessages(); // Display.update(); glfwPollEvents(); glfwSwapBuffers(window); } protected void initGl() { // Upgrade via the documentation here: // ContextAttribs contextAttributes; // PixelFormat pixelFormat = new PixelFormat(); // GLContext glContext = new GLContext(); //Initialize GLFW. glfwInit(); //Setup an error callback to print GLFW errors to the console. glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err)); // contextAttributes = new ContextAttribs(4, 1).withProfileCore(true).withDebug(true); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // TODO: what about withDebug? glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // try { window = setupDisplay(); // presumably this is called in setupDisplay now? // Display.create(pixelFormat, contextAttributes); // This supresses a strange error where when using // the Oculus Rift in direct mode on Windows, // there is an OpenGL GL_INVALID_FRAMEBUFFER_OPERATION // error present immediately after the context has been created. @SuppressWarnings("unused") int err = glGetError(); // GLContext.useContext(glContext, false); // TODO: maybe get rid of these? // Mouse.create(); // Keyboard.create(); //} catch (LWJGLException e) { // throw new RuntimeException(e); // TODO: vSyncEnabled in lwjgl3 // Display.setVSyncEnabled(false); TextureSwapChainDesc desc = new TextureSwapChainDesc(); desc.Type = OvrLibrary.ovrTextureType.ovrTexture_2D; desc.ArraySize = 1; desc.Width = textureSizes[0].w + textureSizes[1].w; desc.Height = textureSizes[0].h; desc.MipLevels = 1; desc.Format = OvrLibrary.ovrTextureFormat.OVR_FORMAT_R8G8B8A8_UNORM_SRGB; desc.SampleCount = 1; desc.StaticImage = false; swapChain = hmd.createSwapTextureChain(desc); MirrorTextureDesc mirrorDesc = new MirrorTextureDesc(); mirrorDesc.Format = OvrLibrary.ovrTextureFormat.OVR_FORMAT_R8G8B8A8_UNORM; mirrorDesc.Width = width; mirrorDesc.Height = height; mirrorTexture = hmd.createMirrorTexture(mirrorDesc); layer.Header.Type = OvrLibrary.ovrLayerType.ovrLayerType_EyeFov; layer.ColorTexure[0] = swapChain; layer.Fov = fovPorts; layer.RenderPose = poses; for (int eye = 0; eye < 2; ++eye) { layer.Viewport[eye].Size = textureSizes[eye]; layer.Viewport[eye].Pos = new OvrVector2i(0, 0); } layer.Viewport[1].Pos.x = layer.Viewport[1].Size.w; frameBuffer = new FrameBuffer(desc.Width, desc.Height); for (int eye = 0; eye < 2; ++eye) { EyeRenderDesc eyeRenderDesc = hmd.getRenderDesc(eye, fovPorts[eye]); this.eyeOffsets[eye].x = eyeRenderDesc.HmdToEyeViewOffset.x; this.eyeOffsets[eye].y = eyeRenderDesc.HmdToEyeViewOffset.y; this.eyeOffsets[eye].z = eyeRenderDesc.HmdToEyeViewOffset.z; } viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f; } protected void onDestroy() { hmd.destroy(); Hmd.shutdown(); } protected void update() { // TODO: some sort of update logic for the game? // while (Keyboard.next()) { // onKeyboardEvent(); // while (Mouse.next()) { // onMouseEvent(); // TODO : nothing? // Here we could update our projection matrix based on HMD info } // TODO: synchronize access to the current frame? public synchronized RiftFrame getCurrentFrame() { return currentFrame; } // TODO: do i need to synchronize this? public synchronized void setCurrentFrame(RiftFrame currentFrame) { this.currentFrame = currentFrame; newFrame = true; } public static void renderTexturedQuad(int texture) { if (null == unitQuadProgram) { unitQuadProgram = new Program(UNIT_QUAD_VS, UNIT_QUAD_FS); unitQuadProgram.link(); } if (null == unitQuadVao) { unitQuadVao = new VertexArray(); } unitQuadProgram.use(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); unitQuadVao.bind(); glBindTexture(GL_TEXTURE_2D, texture); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); Texture.unbind(GL_TEXTURE_2D); Program.clear(); VertexArray.unbind(); } public static void renderSkybox() { if (null == cubeGeometry) { cubeGeometry = OpenGL.makeColorCube(); } if (null == skyboxProgram) { skyboxProgram = new Program(SHADERS_CUBEMAP_VS, SHADERS_CUBEMAP_FS); skyboxProgram.link(); } if (null == skyboxTexture) { skyboxTexture = OpenGL.getCubemapTextures(SKYBOX); } MatrixStack mv = MatrixStack.MODELVIEW; cubeGeometry.bindVertexArray(); mv.push(); Quaternion q = mv.getRotation(); mv.identity().rotate(q); skyboxProgram.use(); OpenGL.bindAll(skyboxProgram); glCullFace(GL_FRONT); skyboxTexture.bind(); glDisable(GL_DEPTH_TEST); cubeGeometry.draw(); glEnable(GL_DEPTH_TEST); skyboxTexture.unbind(); glCullFace(GL_BACK); mv.pop(); } /* * helper function to render an image on the current bound texture. */ public void renderScreen(Texture screenTexture, Orientation orientation) { // clean up glClear(GL_DEPTH_BUFFER_BIT); renderSkybox(); // TODO: don't lazy create this. if (null == screenGeometry) { screenGeometry = OpenGL.makeTexturedQuad(new Vector2f(-screenSize, -screenSize), new Vector2f(screenSize, screenSize)); } if (null == screenProgram) { screenProgram = new Program(SHADERS_TEXTURED_VS, SHADERS_TEXTURED_FS); screenProgram.link(); } screenProgram.use(); OpenGL.bindAll(screenProgram); screenTexture.bind(); screenGeometry.bindVertexArray(); screenGeometry.draw(); Texture.unbind(GL_TEXTURE_2D); Program.clear(); VertexArray.unbind(); } public int getWidth() { return width; } public int getHeight() { return height; } public void start() { log.info("Starting oculus display thread."); if (displayThread != null) { log.info("Oculus Display thread already started."); return; } // create a thread to run the main render loop displayThread = new Thread(this, String.format("%s_oculusDisplayThread", "oculus")); displayThread.start(); } public Hmd getHmd() { return hmd; } public void setHmd(Hmd hmd) { this.hmd = hmd; } // The following methods are taken from the joculur-examples public static Vector3f toVector3f(OvrVector3f v) { return new Vector3f(v.x, v.y, v.z); } public static Quaternion toQuaternion(OvrQuaternionf q) { return new Quaternion(q.x, q.y, q.z, q.w); } public static Matrix4f toMatrix4f(Posef p) { return new Matrix4f().rotate(toQuaternion(p.Orientation)).mult(new Matrix4f().translate(toVector3f(p.Position))); } public static Matrix4f toMatrix4f(OvrMatrix4f m) { if (null == m) { return new Matrix4f(); } return new Matrix4f(m.M).transpose(); } // End methods from saintandreas public static void main(String[] args) throws IOException { System.out.println("Hello world."); OculusDisplay display = new OculusDisplay(); display.start(); RiftFrame frame = new RiftFrame(); File imageFile = new File("src/main/resources/resource/mrl_logo.jpg"); BufferedImage lbi = ImageIO.read(imageFile); BufferedImage rbi = ImageIO.read(imageFile); SerializableImage lsi = new SerializableImage(lbi,"left"); SerializableImage rsi = new SerializableImage(rbi, "right"); frame.left = lsi; frame.right = rsi; display.start(); display.setCurrentFrame(frame); } }
package org.myrobotlab.service; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.File; import java.net.URL; import java.util.List; import java.util.Map; //import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.net.Http; import org.myrobotlab.service.config.ImageDisplayConfig; import org.myrobotlab.service.config.ImageDisplayConfig.Display; import org.myrobotlab.service.config.ServiceConfig; import org.myrobotlab.service.data.ImageData; import org.myrobotlab.service.interfaces.ImageListener; import org.myrobotlab.service.interfaces.ImagePublisher; import org.slf4j.Logger; public class ImageDisplay extends Service implements ImageListener, MouseListener, ActionListener, MouseMotionListener { final static Logger log = LoggerFactory.getLogger(ImageDisplay.class); private static final long serialVersionUID = 1L; Integer absLastMouseX = null; Integer absLastMouseY = null; Integer absMouseX = null; Integer absMouseY = null; String cacheDir = getDataDir() + fs + "cache"; String currentDisplay = null; transient GraphicsEnvironment ge = null; transient GraphicsDevice[] gs = null; Integer offsetX = null; Integer offsetY = null; transient ImageDisplay self = null; public ImageDisplay(String name, String inId) { super(name, inId); File file = new File(cacheDir); file.mkdirs(); self = this; } @Override public void actionPerformed(ActionEvent arg0) { } @Override public ServiceConfig apply(ServiceConfig c) { ImageDisplayConfig config = (ImageDisplayConfig) c; for (String displayName : config.displays.keySet()) { close(displayName); displayInternal(displayName); } return config; } public void attach(Attachable attachable) { if (attachable instanceof ImagePublisher) { attachImagePublisher(attachable.getName()); } else { error("don't know how to attach a %s", attachable.getName()); } } public String close() { return close(currentDisplay); } public String close(String name) { Map<String, ImageDisplayConfig.Display> displays = ((ImageDisplayConfig) config).displays; Display display = displays.get(name); if (display != null) { if (display.frame != null) { display.frame.setVisible(false); display.frame.dispose(); display.frame = null; } // displays.remove(src); return name; } return null; } public void closeAll() { Map<String, ImageDisplayConfig.Display> displays = ((ImageDisplayConfig) config).displays; for (Display display : displays.values()) { close(display.name); } currentDisplay = null; displays.clear(); } public void reset() { closeAll(); config = new ImageDisplayConfig(); } public void disable() { ImageDisplayConfig c = (ImageDisplayConfig) config; c.enabled = false; } public Display display(String src) { Display display = getDisplay(null); display.src = src; displayInternal(display.name); return display; } public void display(String src, float opacity) { Display display = getDisplay(null); display.src = src; display.fullscreen = false; display.opacity = opacity; displayInternal(display.name); } public String display(String name, String src) { Display display = getDisplay(name); display.src = src; displayInternal(display.name); return name; } @Deprecated /* no longer supported */ public void displayFadeIn(String src) { display(src); } public String displayFullScreen(String src) { Display display = getDisplay(null); display.src = src; display.fullscreen = true; displayInternal(display.name); return display.name; } public void displayFullScreen(String src, float opacity) { Display display = getDisplay(null); display.src = src; display.fullscreen = true; display.opacity = opacity; displayInternal(display.name); } public String displayFullScreen(String name, String src) { Display display = getDisplay(name); display.name = name; display.src = src; display.fullscreen = true; displayInternal(display.name); return display.name; } private String displayInternal(final String name) { ImageDisplayConfig c = (ImageDisplayConfig) config; if (!c.displays.containsKey(name)) { error("could not find %s display", name); return name; } if (!c.enabled) { log.info("not currently enabled"); return name; } if (GraphicsEnvironment.isHeadless()) { log.warn("in headless mode - %s will not display images", getName()); return name; } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { if (gs == null) { ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); gs = ge.getScreenDevices(); } Display display = c.displays.get(name); if (display == null) { error("null display for %s", name); return; } // creating the swing components if necessary if (display.frame == null) { initFrame(display); } int displayWidth = display.gd.getDisplayMode().getWidth(); int displayHeight = display.gd.getDisplayMode().getHeight(); log.info("display screen {} displaying {}", display.screen, display.name); log.info("Loading image: "); // get final uri/url for file URL imageUrl = null; if (display.src == null) { error("could not display null image"); display.src = getResourceDir() + fs + "mrl_logo.jpg"; } if (display.src.startsWith("http: String cacheFile = cacheDir + fs + display.src.replace("/", "_"); File check = new File(cacheFile); if (!check.exists()) { byte[] bytes = Http.get(display.src); if (bytes != null) { // save cache FileIO.toFile(cacheFile, bytes); } else { error("could not download %s", display.src); check = new File(getResourceDir() + fs + "mrl_logo.jpg"); } } imageUrl = check.toURI().toURL(); } else { File check = new File(display.src); if (!check.exists()) { error("%s does not exist", display.src); display.src = getResourceDir() + fs + "mrl_logo.jpg"; } imageUrl = new File(display.src).toURI().toURL(); } display.imageIcon = new ImageIcon(imageUrl); display.label.setIcon(display.imageIcon); // display.label.setIcon(new ImageIcon(image)); // TODO - make better / don't use setImageAutoSize (very bad // algorithm) if (SystemTray.isSupported()) { log.info("SystemTray is supported"); SystemTray tray = SystemTray.getSystemTray(); // Dimension trayIconSize = tray.getTrayIconSize(); TrayIcon trayIcon = new TrayIcon(display.imageIcon.getImage()); trayIcon.setImageAutoSize(true); tray.add(trayIcon); } if (display.bgColor != null) { Color color = Color.decode(display.bgColor); display.label.setOpaque(true); display.label.setBackground(color); display.panel.setBackground(color); // <- this one is the important // one display.frame.getContentPane().setBackground(color); } if (display.alwaysOnTop != null && display.alwaysOnTop) { display.frame.setAlwaysOnTop(true); } if (display.fullscreen != null && display.fullscreen) { // auto scale image float wRatio = (float) displayWidth / display.imageIcon.getIconWidth(); float hRatio = (float) displayHeight / display.imageIcon.getIconHeight(); float ratio = (c.autoscaleExtendsMax) ? (wRatio < hRatio) ? hRatio : wRatio : (wRatio > hRatio) ? hRatio : wRatio; int resizedWidth = (int) (ratio * display.imageIcon.getIconWidth()); int resizedHeight = (int) (ratio * display.imageIcon.getIconHeight()); Image image = display.imageIcon.getImage().getScaledInstance(resizedWidth, resizedHeight, Image.SCALE_DEFAULT); display.imageIcon.setImage(image); // center it display.frame.setLocation(displayWidth / 2 - resizedWidth / 2, displayHeight / 2 - resizedHeight / 2); // makes a difference on fullscreen display.frame.pack(); // gd.setFullScreenWindow(frame); display.frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // frame.setLocationRelativeTo(null); } else if ((display.width != null && display.width != null) || display.scale != null) { // FIXME - "IF" SCALED THEN SETICON(ICON) !!! Integer resizedWidth = null; Integer resizedHeight = null; if (display.scale != null) { // FIXME - check this resizedWidth = (int) (display.scale * display.imageIcon.getIconWidth()); resizedHeight = (int) (display.scale * display.imageIcon.getIconHeight()); } else if (display.width != null && display.height != null) { resizedWidth = display.width; resizedHeight = display.height; } display.imageIcon.getImage().getScaledInstance(resizedWidth, resizedHeight, Image.SCALE_DEFAULT); } int imgX = (display.x != null) ? display.x : displayWidth / 2 - display.imageIcon.getIconWidth() / 2; int imgY = (display.y != null) ? display.y : displayHeight / 2 - display.imageIcon.getIconHeight() / 2; display.frame.setLocation(imgX, imgY); // makes a difference on fullscreen display.frame.pack(); if (display.opacity != null) { display.label.setOpaque(false); display.panel.setOpaque(false); display.frame.setOpacity(display.opacity); display.frame.setBackground(new Color(0, 0, 0, display.opacity)); } display.frame.setVisible(true); } catch (Exception e) { error("display error %s", e.getMessage()); log.error("display threw", e); } } }); return name; } public String displayScaled(String src, float scale) { Display display = getDisplay(null); display.src = src; display.scale = scale; displayInternal(display.name); return display.name; } public void displayScaled(String src, float opacity, float scale) { Display display = getDisplay(null); display.src = src; display.opacity = opacity; display.scale = scale; displayInternal(display.name); } public void enable() { ImageDisplayConfig c = (ImageDisplayConfig) config; c.enabled = true; } // no longer interested in managing BufferedImages :( // private BufferedImage resize(BufferedImage before, int width, int height) { // int w = before.getWidth(); // int h = before.getHeight(); // BufferedImage after = new BufferedImage(width, height, // BufferedImage.TYPE_INT_ARGB); // AffineTransform at = new AffineTransform(); // at.scale((float) width / w, (float) height / h); // AffineTransformOp scaleOp = new AffineTransformOp(at, // AffineTransformOp.TYPE_BILINEAR); // after = scaleOp.filter(before, after); // return after; @Deprecated public void exitFS() { exitFullScreen(null); } public void exitFullScreen() { exitFullScreen(null); } public void exitFullScreen(String name) { Map<String, ImageDisplayConfig.Display> displays = ((ImageDisplayConfig) config).displays; if (name == null) { name = currentDisplay; } Display display = displays.get(name); if (display != null) { display.frame.dispose(); } displays.remove(name); display(name); } @Override public ServiceConfig getConfig() { ImageDisplayConfig c = (ImageDisplayConfig) config; // don't need to do anything return c; } /** * if the display currently get it, if it doesn't create one with default * values specified in config * * @return */ private Display getDisplay(String name) { if (name == null) { name = "default"; } ImageDisplayConfig c = (ImageDisplayConfig) config; if (c.displays.containsKey(name)) { return c.displays.get(name); } // create a default display from config Display display = new Display(); display.name = name; display.src = c.src; display.x = c.x; display.y = c.y; display.width = c.width; display.height = c.height; display.fullscreen = c.fullscreen; display.alwaysOnTop = c.alwaysOnTop; display.autoscaleExtendsMax = c.autoscaleExtendsMax; display.bgColor = c.bgColor; display.screen = c.screen; display.opacity = c.opacity; display.scale = c.scale; display.visible = c.visible; c.displays.put(display.name, display); return display; } private void initFrame(Display display) { if (display.frame != null) { display.frame.setVisible(false); display.frame.dispose(); } if (display.screen != null && display.screen <= gs.length) { display.gd = gs[display.screen]; } else { display.gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); } display.frame = new JFrame(display.gd.getDefaultConfiguration()); display.frame.setName(display.name); // display.panel = new JPanel(new BorderLayout()); display.panel = new JPanel(); FlowLayout fl = (FlowLayout) display.panel.getLayout(); fl.setVgap(0); fl.setHgap(0); display.panel.setName("panel"); display.label = new JLabel(); display.label.setName("label"); // display.panel.add(display.label, BorderLayout.CENTER); display.panel.add(display.label); display.frame.getContentPane().add(display.panel); display.frame.setUndecorated(true); display.frame.addMouseListener(self); display.frame.addMouseMotionListener(self); } @Override public void mouseClicked(MouseEvent e) { // log.info("mouseClicked {}", e); if (SwingUtilities.isRightMouseButton(e)) { JFrame frame = (JFrame) e.getSource(); // TODO options on hiding or disposing or // creating a popup menu etc.. frame.setVisible(false); frame.dispose(); } } @Override public void mouseDragged(MouseEvent e) { JFrame frame = (JFrame) e.getSource(); // log.debug("mouseDragged {}", frame.getName()); if (absMouseX == null) { absMouseX = e.getXOnScreen(); offsetX = e.getX(); } if (absMouseY == null) { absMouseY = e.getYOnScreen(); offsetY = e.getY(); } absLastMouseX = absMouseX; absLastMouseY = absMouseY; absMouseX = e.getXOnScreen(); absMouseY = e.getYOnScreen(); frame.setLocation(absMouseX - offsetX, absMouseY - offsetY); frame.repaint(); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mouseMoved(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } public void move(String name, int x, int y) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Map<String, ImageDisplayConfig.Display> displays = ((ImageDisplayConfig) config).displays; if (displays.containsKey(name)) { Display display = displays.get(name); display.frame.setLocation(x, y); display.x = x; display.y = y; } } }); } @Override public void onImage(ImageData img) { display(img.name, img.src); } public void resize(String name, int width, int height) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Map<String, ImageDisplayConfig.Display> displays = ((ImageDisplayConfig) config).displays; if (displays.containsKey(name)) { Display display = displays.get(name); initFrame(display); Image image = display.imageIcon.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT); display.label.setIcon(new ImageIcon(image)); display.frame.pack(); display.width = width; display.height = height; if (display.x != null && display.y != null) { display.frame.setLocation(display.x, display.y); } display.frame.setVisible(true); } } }); } public void setAlwaysOnTop(boolean b) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.alwaysOnTop = b; } public boolean setAutoscaleExtendsMax(boolean b) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.autoscaleExtendsMax = b; return b; } public void setColor(String color) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.bgColor = color; } public void setDimension(Integer width, Integer height) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.width = width; c.height = height; } public void setFullScreen(boolean b) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.fullscreen = b; } public void setLocation(Integer x, Integer y) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.x = x; c.y = y; } public Integer setScreen(Integer screen) { ImageDisplayConfig c = (ImageDisplayConfig) config; c.screen = screen; return screen; } public void setTransparent() { ImageDisplayConfig c = (ImageDisplayConfig) config; c.bgColor = null; } public void setVisible(String name, boolean b) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Map<String, ImageDisplayConfig.Display> displays = ((ImageDisplayConfig) config).displays; if (displays.containsKey(name)) { Display display = displays.get(name); display.frame.setVisible(b); } } }); } @Override public void startService() { super.startService(); if (GraphicsEnvironment.isHeadless()) { log.warn("in headless mode - %s will not display images", getName()); return; } } public static void main(String[] args) { LoggingFactory.init(Level.INFO); try { // Runtime.setConfig("default"); // your all purpose image display service ImageDisplay display = (ImageDisplay) Runtime.start("display", "ImageDisplay"); // Default Values // setting these are setting default values // so that any new display is created they will // have the following properties automatically set accordingly // the display will always be on top // display.setAlwaysOnTop(true); // when a picture is told to go fullscreen // and is not the same ratio as the screen dimensions // this tells whether to scale and extend to the min // or max extension // display.setAutoscaleExtendsMax(true); // if there is a background while fullscreen - set the color rgb // display.setColor("#000000"); // if true will resize image (depending on setAutoscaleExtendsMax) // display.setFullScreen(false); // set which screen device to be displayed on // display.setScreen(0); // set the default location for images to display // null values will mean image will be positioned in the center of the // screen // display.setLocation(null, null); // set the default dimensions for images to display // null values will be the dimensions of the original image // display.setDimension(null, null); // most basic display - an image file, can be relative or absolute file // path // displays are named - if you don't name them - they're name will be // "default" // this creates a display named default and display a snake.jpg display.display("snake.jpg"); sleep(1000); // this creates a new display called "beetle" and loads it with beetle.jpg // "default" display is still snake.jpg display.display("beetle", "beetle.jpg"); sleep(1000); // the image display service can also display images from the web // just supply the full url - they can be named as well - this one // replaces the snake image // since a name was not specified - its loaded into "default" display.display("https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/InMoov_Wheel_1.jpg/220px-InMoov_Wheel_1.jpg"); sleep(1000); // animated gifs can be displayed as well - this is the earth // in fullscreen mode display.displayFullScreen("earth", "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/300px-Rotating_earth_%28large%29.gif"); sleep(1000); // we can resize a picture display.resize("earth", 600, 600); sleep(1000); // and re-position it display.move("earth", 800, 800); // make another picture go fullscreen display.displayFullScreen("robot", "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/FANUC_6-axis_welding_robots.jpg/1280px-FANUC_6-axis_welding_robots.jpg"); sleep(1000); display.display("monkeys", "https://upload.wikimedia.org/wikipedia/commons/e/e8/Gabriel_Cornelius_von_Max%2C_1840-1915%2C_Monkeys_as_Judges_of_Art%2C_1889.jpg"); sleep(1000); display.displayFullScreen("robot", "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/FANUC_6-axis_welding_robots.jpg/1280px-FANUC_6-axis_welding_robots.jpg"); sleep(1000); display.display("inmoov", "https://upload.wikimedia.org/wikipedia/commons/thumb/8/87/InMoov_Wheel_1.jpg/220px-InMoov_Wheel_1.jpg"); sleep(1000); display.display("mrl", "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/VirtualInMoov.jpg/220px-VirtualInMoov.jpg"); sleep(1000); for (int i = 0; i < 100; ++i) { display.move("monkeys", 20 + i, 20 + i); sleep(50); } display.resize("monkeys", 200, 200); sleep(1000); display.move("monkeys", 20, 20); sleep(1000); // now we can close some of the displays display.close("monkeys"); sleep(1000); display.close("robot"); int x0 = 500, y0 = 500; int r = 300; double x, y = 0; // move the inmoov image in a circle on the screen for (double t = 0; t < 4 * Math.PI; t += 1) { x = r * Math.cos(t) + x0; y = r * Math.sin(t) + y0; display.move("inmoov", (int) x, (int) y); sleep(100); } // in this example we will search for images and display them // start a google search and get the images back, then display them GoogleSearch google = (GoogleSearch) Runtime.start("google", "GoogleSearch"); List<String> images = google.imageSearch("monkey"); for (String img : images) { display.displayFullScreen(img); // display.display(img); sleep(1000); } display.setFullScreen(true); display.setAutoscaleExtendsMax(true); // another example we'll use wikipedia service to search // and attach the wikipedia to the display service // it will automagically display when an image is found Wikipedia wikipedia = (Wikipedia) Runtime.start("wikipedia", "Wikipedia"); wikipedia.attach(display); // display.attach(wikipedia); images = wikipedia.imageSearch("bear"); sleep(2000); display.setFullScreen(false); display.setAutoscaleExtendsMax(false); display.displayFullScreen("https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Noto_Emoji_Pie_1f4e2.svg/512px-Noto_Emoji_Pie_1f4e2.svg.png?20190227024729"); sleep(1000); display.display("data/Emoji/512px/U+1F47D.png"); sleep(1000); display.display("https://raw.githubusercontent.com/googlefonts/noto-emoji/main/png/512/emoji_u1f62c.png"); sleep(1000); display.displayFullScreen("https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Noto_Emoji_Pie_1f4e2.svg/512px-Noto_Emoji_Pie_1f4e2.svg.png?20190227024729"); sleep(1000); display.display("https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Noto_Emoji_Pie_1f995.svg/512px-Noto_Emoji_Pie_1f995.svg.png?20190227143252"); sleep(1000); display.save(); log.info("done"); } catch (Exception e) { log.error("main threw", e); } } }
package org.oucs.gaboto.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Iterator; import org.oucs.gaboto.GabotoConfiguration; import org.oucs.gaboto.GabotoLibrary; import org.oucs.gaboto.exceptions.GabotoException; import org.oucs.gaboto.model.events.GabotoEvent; import org.oucs.gaboto.model.events.GabotoInsertionEvent; import org.oucs.gaboto.model.events.GabotoRemovalEvent; import org.oucs.gaboto.model.listener.UpdateListener; import org.oucs.gaboto.timedim.index.SimpleTimeDimensionIndexer; import org.oucs.gaboto.util.Performance; import org.oucs.gaboto.vocabulary.RDFCON; import com.hp.hpl.jena.db.DBConnection; import com.hp.hpl.jena.db.IDBConnection; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ModelMaker; import com.hp.hpl.jena.vocabulary.RDF; import de.fuberlin.wiwiss.ng4j.NamedGraph; import de.fuberlin.wiwiss.ng4j.NamedGraphSet; import de.fuberlin.wiwiss.ng4j.Quad; import de.fuberlin.wiwiss.ng4j.db.NamedGraphSetDB; import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl; /** * Factory class to create Gaboto objects. * * * @author Arno Mittelbach * @version 0.1 */ public class GabotoFactory { private static Gaboto persistentGaboto = null; private static Gaboto inMemoryGaboto = null; /* Context Dependent Graph */ private static Model cdg = null; /** * Creates an empty in memory Gaboto model that is not linked to any persistent data store. * * <p> * A time dimension indexer is set. * </p> * * @return A new Gaboto object. */ public static Gaboto getEmptyInMemoryGaboto(){ // Create a new graphset and copy graphs NamedGraphSet graphset = new NamedGraphSetImpl(); // create none db backed up cdg cdg = ModelFactory.createDefaultModel(); // get config GabotoConfiguration config = GabotoLibrary.getConfig(); // if graphset is empty, create special graphs if(! graphset.containsGraph(config.getGKG())) createGKG(graphset); Gaboto test = new Gaboto(cdg, graphset, new SimpleTimeDimensionIndexer()); return test; } /** * Creates a new in-memory Gaboto system that is kept in sync with the persistent Gaboto object. * * <p> * A time dimension indexer is set. * </p> * * <p> * In memory objects should only be used for querying data. * </p> * * @return An Gaboto object with an in-memory store. * @throws GabotoException * * @see #getPersistentGaboto() */ @SuppressWarnings("unchecked") public static Gaboto getInMemoryGaboto() { if(inMemoryGaboto != null) return inMemoryGaboto; Gaboto po = getPersistentGaboto(); // Create a new graphset and copy graphs NamedGraphSet graphset = new NamedGraphSetImpl(); Iterator graphIt = po.getNamedGraphSet().listGraphs(); while(graphIt.hasNext()) graphset.createGraph(((NamedGraph)graphIt.next()).getGraphName()); System.err.println("getInMemoryGaboto: have created graphs"); Iterator it = po.getNamedGraphSet().findQuads(Node.ANY, Node.ANY, Node.ANY, Node.ANY); while(it.hasNext()) graphset.addQuad((Quad)it.next()); System.err.println("getInMemoryGaboto: have added quads"); inMemoryGaboto = new Gaboto(createCDG(), graphset, new SimpleTimeDimensionIndexer()); System.err.println("getInMemoryGaboto: returning"); return inMemoryGaboto; } /** * Creates a new Gaboto model with a persistent data store. * * <p> * The connection to the database is configured in the {@link GabotoConfiguration}. * </p> * * <p> * A time dimension indexer is NOT set. * </p> * * <p> * The Persistent Gaboto object should only be used to add and change data. For * querying the data, an in-memory Gaboto should be used. * </p> * * @return A new persistent Gaboto * @throws GabotoException * @see #getInMemoryGaboto() * @see GabotoConfiguration */ public static Gaboto getPersistentGaboto() { // does it already exist? if(persistentGaboto != null) return persistentGaboto; // get config GabotoConfiguration config = GabotoLibrary.getConfig(); // create persistent gaboto String URL = config.getDbURL(); String USER = config.getDbUser(); String PW = config.getDbPassword(); try { Class.forName(config.getDbDriver()); } catch (ClassNotFoundException e1) { throw new RuntimeException(e1); } Connection connection = null; System.err.println("URL:"+URL + " USER:"+USER+ " PWD:"+PW); try { connection = DriverManager.getConnection(URL, USER, PW); } catch (SQLException e) { throw new RuntimeException(e); } // Create a new graphset Performance.start("GabotoFactory new NamedGraphSetDB"); NamedGraphSet graphset = new NamedGraphSetDB(connection); Performance.stop(); // if graphset is empty, create special graphs if(! graphset.containsGraph(config.getGKG())) createGKG(graphset); // create object Performance.start("GabotoFactory new Gaboto"); persistentGaboto = new Gaboto(createCDG(), graphset, new SimpleTimeDimensionIndexer()); Performance.stop(); Performance.start("GabotoFactory update listener"); // attach update listener persistentGaboto.attachUpdateListener(new UpdateListener(){ public void updateOccured(GabotoEvent e) { if(inMemoryGaboto instanceof Gaboto){ // try to cast event to insertion if(e instanceof GabotoInsertionEvent){ GabotoInsertionEvent event = (GabotoInsertionEvent) e; if(event.getTimespan() != null) inMemoryGaboto.add(event.getTimespan(), event.getTriple()); else inMemoryGaboto.add(event.getTriple()); } // try to cast event to removal else if(e instanceof GabotoRemovalEvent){ GabotoRemovalEvent event = (GabotoRemovalEvent) e; if(event.getQuad() != null) inMemoryGaboto.remove(event.getQuad()); else if(event.getTimespan() != null && event.getTriple() != null ) inMemoryGaboto.remove(event.getTimespan(), event.getTriple()); else if(event.getTriple() != null) inMemoryGaboto.remove(event.getTriple()); } } } }); Performance.stop(); return persistentGaboto; } /** * Adds the cdg to the graphset. */ private static Model createCDG() { if(cdg != null) return cdg; // get config GabotoConfiguration config = GabotoLibrary.getConfig(); String M_DB_URL = config.getDbURL(); String M_DB_USER = config.getDbUser(); String M_DB_PASSWD = config.getDbPassword(); String M_DB = config.getDbEngineName(); String M_DBDRIVER_CLASS = config.getDbDriver(); // load the the driver class try { Class.forName(M_DBDRIVER_CLASS); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } // create a database connection IDBConnection conn = new DBConnection(M_DB_URL, M_DB_USER, M_DB_PASSWD, M_DB); // create a model maker with the given connection parameters ModelMaker maker = ModelFactory.createModelRDBMaker(conn); // create cdg if(maker.hasModel("cdg")) cdg = maker.openModel("cdg"); else cdg = maker.createModel("cdg"); return cdg; } /** * adds the gkgg to the graphset * @param graphset */ private static void createGKG(NamedGraphSet graphset) { // get config GabotoConfiguration config = GabotoLibrary.getConfig(); if(graphset.containsGraph(config.getGKG())) throw new IllegalStateException("GKG already exists."); // Create gkg graphset.createGraph(config.getGKG()); // add gkg to cdg createCDG().getGraph().add(new Triple( Node.createURI(config.getGKG()), Node.createURI(RDF.type.getURI()), Node.createURI(RDFCON.GlobalKnowledgeGraph.getURI()) )); } }
package org.oucs.gaboto.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Iterator; import org.oucs.gaboto.GabotoConfiguration; import org.oucs.gaboto.GabotoLibrary; import org.oucs.gaboto.exceptions.GabotoException; import org.oucs.gaboto.model.events.GabotoEvent; import org.oucs.gaboto.model.events.GabotoInsertionEvent; import org.oucs.gaboto.model.events.GabotoRemovalEvent; import org.oucs.gaboto.model.listener.UpdateListener; import org.oucs.gaboto.timedim.index.SimpleTimeDimensionIndexer; import org.oucs.gaboto.util.Performance; import org.oucs.gaboto.vocabulary.RDFCON; import com.hp.hpl.jena.db.DBConnection; import com.hp.hpl.jena.db.IDBConnection; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.ModelMaker; import com.hp.hpl.jena.vocabulary.RDF; import de.fuberlin.wiwiss.ng4j.NamedGraph; import de.fuberlin.wiwiss.ng4j.NamedGraphSet; import de.fuberlin.wiwiss.ng4j.Quad; import de.fuberlin.wiwiss.ng4j.db.NamedGraphSetDB; import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl; /** * Factory class to create Gaboto objects. * * * @author Arno Mittelbach * @version 0.1 */ public class GabotoFactory { private static Gaboto persistentGaboto = null; private static Gaboto inMemoryGaboto = null; private static Model cdg = null; /** * Creates an empty in memory Gaboto model that is not linked to any persistent data store. * * <p> * A time dimension indexer is set. * </p> * * @return A new Gaboto object. */ public static Gaboto getEmptyInMemoryGaboto(){ // Create a new graphset and copy graphs NamedGraphSet graphset = new NamedGraphSetImpl(); // create none db backed up cdg cdg = ModelFactory.createDefaultModel(); // get config GabotoConfiguration config = GabotoLibrary.getConfig(); // if graphset is empty, create special graphs if(! graphset.containsGraph(config.getGKG())) createGKG(graphset); Gaboto test = new Gaboto(cdg, graphset, new SimpleTimeDimensionIndexer()); return test; } /** * Creates a new in-memory Gaboto system that is kept in sync with the persistent Gaboto object. * * <p> * A time dimension indexer is set. * </p> * * <p> * In memory objects should only be used for querying data. * </p> * * @return An Gaboto object with an in-memory store. * @throws GabotoException * * @see #getPersistentGaboto() */ @SuppressWarnings("unchecked") public static Gaboto getInMemoryGaboto() { if(null != inMemoryGaboto) return inMemoryGaboto; Gaboto po = getPersistentGaboto(); // Create a new graphset and copy graphs NamedGraphSet graphset = new NamedGraphSetImpl(); Iterator graphIt = po.getNamedGraphSet().listGraphs(); while(graphIt.hasNext()) graphset.createGraph(((NamedGraph)graphIt.next()).getGraphName()); Iterator it = po.getNamedGraphSet().findQuads(Node.ANY, Node.ANY, Node.ANY, Node.ANY); while(it.hasNext()) graphset.addQuad((Quad)it.next()); inMemoryGaboto = new Gaboto(createCDG(), graphset, new SimpleTimeDimensionIndexer()); return inMemoryGaboto; } /** * Creates a new Gaboto model with a persistent data store. * * <p> * The connection to the database is configured in the {@link GabotoConfiguration}. * </p> * * <p> * A time dimension indexer is NOT set. * </p> * * <p> * The Persistent Gaboto object should only be used to add and change data. For * querying the data, an in-memory Gaboto should be used. * </p> * * @return A new persistent Gaboto * @throws GabotoException * @see #getInMemoryGaboto() * @see GabotoConfiguration */ public static Gaboto getPersistentGaboto() { // does it alreay exist? if(persistentGaboto instanceof Gaboto) return persistentGaboto; // get config GabotoConfiguration config = GabotoLibrary.getConfig(); // create persistent gaboto String URL = config.getDbURL(); String USER = config.getDbUser(); String PW = config.getDbPassword(); try { Class.forName(config.getDbDriver()); } catch (ClassNotFoundException e1) { throw new RuntimeException(e1); } Connection connection = null; try { connection = DriverManager.getConnection(URL, USER, PW); } catch (SQLException e) { throw new RuntimeException(e); } // Create a new graphset Performance.start("load"); NamedGraphSet graphset = new NamedGraphSetDB(connection); Performance.stop(); // if graphset is empty, create special graphs if(! graphset.containsGraph(config.getGKG())) createGKG(graphset); // create object persistentGaboto = new Gaboto(createCDG(), graphset, new SimpleTimeDimensionIndexer()); // attach update listener persistentGaboto.attachUpdateListener(new UpdateListener(){ public void updateOccured(GabotoEvent e) { if(inMemoryGaboto instanceof Gaboto){ // try to cast event to insertion if(e instanceof GabotoInsertionEvent){ GabotoInsertionEvent event = (GabotoInsertionEvent) e; if(null != event.getTimespan()) inMemoryGaboto.add(event.getTimespan(), event.getTriple()); else inMemoryGaboto.add(event.getTriple()); } // try to cast event to removal else if(e instanceof GabotoRemovalEvent){ GabotoRemovalEvent event = (GabotoRemovalEvent) e; if(null != event.getQuad()) inMemoryGaboto.remove(event.getQuad()); else if(null != event.getTimespan() && null != event.getTriple()) inMemoryGaboto.remove(event.getTimespan(), event.getTriple()); else if(null != event.getTriple()) inMemoryGaboto.remove(event.getTriple()); } } } }); return persistentGaboto; } /** * adds the cdg to the graphset * @param graphset */ private static Model createCDG() { if(null != cdg) return cdg; // get config GabotoConfiguration config = GabotoLibrary.getConfig(); String M_DB_URL = config.getDbURL(); String M_DB_USER = config.getDbUser(); String M_DB_PASSWD = config.getDbPassword(); String M_DB = config.getDbEngineName(); String M_DBDRIVER_CLASS = config.getDbDriver(); // load the the driver class try { Class.forName(M_DBDRIVER_CLASS); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } // create a database connection IDBConnection conn = new DBConnection(M_DB_URL, M_DB_USER, M_DB_PASSWD, M_DB); // create a model maker with the given connection parameters ModelMaker maker = ModelFactory.createModelRDBMaker(conn); // create cdg if(maker.hasModel("cdg")) cdg = maker.openModel("cdg"); else cdg = maker.createModel("cdg"); return cdg; } /** * adds the gkgg to the graphset * @param graphset */ private static void createGKG(NamedGraphSet graphset) { // get config GabotoConfiguration config = GabotoLibrary.getConfig(); if(graphset.containsGraph(config.getGKG())) throw new IllegalStateException("GKG already exists."); // Create gkg graphset.createGraph(config.getGKG()); // add gkg to cdg createCDG().getGraph().add(new Triple( Node.createURI(config.getGKG()), Node.createURI(RDF.type.getURI()), Node.createURI(RDFCON.GlobalKnowledgeGraph.getURI()) )); } }
package org.railwaystations.rsapi; import org.railwaystations.rsapi.writer.PhotographersTxtWriter; import org.railwaystations.rsapi.writer.StationsGpxWriter; import org.railwaystations.rsapi.writer.StationsTxtWriter; import org.railwaystations.rsapi.writer.StatisticTxtWriter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.*; import java.util.ArrayList; import java.util.List; @EnableWebMvc @Configuration @ComponentScan("org.railwaystations.rsapi") public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) { converters.add(new PhotographersTxtWriter()); converters.add(new StationsGpxWriter()); converters.add(new StationsTxtWriter()); converters.add(new StatisticTxtWriter()); converters.add(new MappingJackson2HttpMessageConverter()); converters.add(byteArrayHttpMessageConverter()); } @Override public void addCorsMappings(final CorsRegistry registry) { registry
package org.sonar.plugins.stash; import org.apache.commons.collections.ListUtils; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.api.PropertyType; import org.sonar.api.SonarPlugin; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import org.sonar.api.rule.Severity; import java.util.Arrays; import java.util.List; @Properties({ @Property(key = StashPlugin.STASH_NOTIFICATION, name = "Stash Notification", defaultValue = "false", description = "Analysis result will be issued in Stash pull request", global = false), @Property(key = StashPlugin.STASH_PROJECT, name = "Stash Project", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_REPOSITORY, name = "Stash Repository", description = "Stash project of current pull-request", global = false), @Property(key = StashPlugin.STASH_PULL_REQUEST_ID, name = "Stash Pull-request Id", description = "Stash pull-request Id", global = false) }) public class StashPlugin extends SonarPlugin { private static final String DEFAULT_STASH_TIMEOUT_VALUE = "10000"; private static final String DEFAULT_STASH_THRESHOLD_VALUE = "100"; private static final String CONFIG_PAGE_SUB_CATEGORY_STASH = "Stash"; public static final String SEVERITY_NONE = "NONE"; // INFO, MINOR, MAJOR, CRITICAL, BLOCKER protected static final List<String> SEVERITY_LIST = Severity.ALL; public static final String CONTEXT_ISSUE_TYPE = "CONTEXT"; public static final String REMOVED_ISSUE_TYPE = "REMOVED"; public static final String ADDED_ISSUE_TYPE = "ADDED"; public static final String STASH_NOTIFICATION = "sonar.stash.notification"; public static final String STASH_PROJECT = "sonar.stash.project"; public static final String STASH_REPOSITORY = "sonar.stash.repository"; public static final String STASH_PULL_REQUEST_ID = "sonar.stash.pullrequest.id"; public static final String STASH_RESET_COMMENTS = "sonar.stash.comments.reset"; public static final String STASH_URL = "sonar.stash.url"; public static final String STASH_LOGIN = "sonar.stash.login"; public static final String STASH_PASSWORD = "sonar.stash.password"; public static final String STASH_REVIEWER_APPROVAL = "sonar.stash.reviewer.approval"; public static final String STASH_ISSUE_THRESHOLD = "sonar.stash.issue.threshold"; public static final String STASH_TIMEOUT = "sonar.stash.timeout"; public static final String SONARQUBE_URL = "sonar.host.url"; public static final String STASH_TASK_SEVERITY_THRESHOLD = "sonar.stash.task.issue.severity.threshold"; public static final String STASH_CODE_COVERAGE_SEVERITY = "sonar.stash.coverage.severity.threshold"; @Override public List getExtensions() { return Arrays.asList( StashIssueReportingPostJob.class, StashPluginConfiguration.class, InputFileCache.class, InputFileCacheSensor.class, StashProjectBuilder.class, StashRequestFacade.class, PropertyDefinition.builder(STASH_URL) .name("Stash base URL") .description("HTTP URL of Stash instance, such as http://yourhost.yourdomain/stash") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_LOGIN) .name("Stash base User") .description("User to push data on Stash instance") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_PASSWORD) .name("Stash base Password") .description("Password for Stash base User " + "(Do NOT use in production, passwords are public for everyone with UNAUTHENTICATED HTTP access to SonarQube") .type(PropertyType.PASSWORD) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT).build(), PropertyDefinition.builder(STASH_TIMEOUT) .name("Stash issue Timeout") .description("Timeout when pushing a new issue to Stash (in ms)") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(DEFAULT_STASH_TIMEOUT_VALUE).build(), PropertyDefinition.builder(STASH_REVIEWER_APPROVAL) .name("Stash reviewer approval") .description("Does SonarQube approve the pull-request if there is no new issues?") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .type(PropertyType.BOOLEAN) .defaultValue("false").build(), PropertyDefinition.builder(STASH_ISSUE_THRESHOLD) .name("Stash issue Threshold") .description("Threshold to limit the number of issues pushed to Stash server") .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(DEFAULT_STASH_THRESHOLD_VALUE).build(), PropertyDefinition.builder(STASH_CODE_COVERAGE_SEVERITY) .name("Stash code coverage severity") .description("Severity to be associated with Code Coverage issues") .options(ListUtils.sum(Arrays.asList(SEVERITY_NONE), SEVERITY_LIST)).build(), PropertyDefinition.builder(STASH_TASK_SEVERITY_THRESHOLD) .name("Stash tasks severity threshold") .description("Only create tasks for issues with the same or higher severity") .type(PropertyType.SINGLE_SELECT_LIST) .subCategory(CONFIG_PAGE_SUB_CATEGORY_STASH) .onQualifiers(Qualifiers.PROJECT) .defaultValue(SEVERITY_NONE) .options(ListUtils.sum(Arrays.asList(SEVERITY_NONE), SEVERITY_LIST)).build()); } }
package org.telegram.telegrambots; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.time.LocalDateTime; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Ruben Bermudez * @version 2.0 * @brief Logger to file * @date 21/01/15 */ public class BotLogger { private static final Object lockToWrite = new Object(); private static final String pathToLogs = "./"; private static final Logger logger = Logger.getLogger("Telegram Bots Api"); private static final ConcurrentLinkedQueue<String> logsToFile = new ConcurrentLinkedQueue<>(); private static volatile PrintWriter logginFile; private static volatile String currentFileName; private static volatile LocalDateTime lastFileDate; private static LoggerThread loggerThread = new LoggerThread(); static { logger.setLevel(Level.OFF); loggerThread.start(); lastFileDate = LocalDateTime.now(); if ((currentFileName == null) || (currentFileName.compareTo("") == 0)) { currentFileName = pathToLogs + dateFormatterForFileName(lastFileDate) + ".log"; try { final File file = new File(currentFileName); if (file.exists()) { logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); } else { final boolean created = file.createNewFile(); if (created) { logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); } else { throw new NullPointerException("File for logging error"); } } } catch (IOException ignored) { } } } public static void setLevel(Level level) { logger.setLevel(level); } public static void registerLogger(Handler handler) { logger.addHandler(handler); } public static void log(Level level, String tag, String msg) { logger.log(level, String.format("[%s] %s", tag, msg)); logToFile(level, tag, msg); } public static void severe(String tag, String msg) { logger.severe(String.format("[%s] %s", tag, msg)); logToFile(Level.SEVERE, tag, msg); } public static void warn(String tag, String msg) { warning(tag, msg); } public static void debug(String tag, String msg) { fine(tag, msg); } public static void error(String tag, String msg) { severe(tag, msg); } public static void trace(String tag, String msg) { finer(tag, msg); } public static void warning(String tag, String msg) { logger.warning(String.format("[%s] %s", tag, msg)); logToFile(Level.WARNING, tag, msg); } public static void info(String tag, String msg) { logger.info(String.format("[%s] %s", tag, msg)); logToFile(Level.INFO, tag, msg); } public static void config(String tag, String msg) { logger.config(String.format("[%s] %s", tag, msg)); logToFile(Level.CONFIG, tag, msg); } public static void fine(String tag, String msg) { logger.fine(String.format("[%s] %s", tag, msg)); logToFile(Level.FINE, tag, msg); } public static void finer(String tag, String msg) { logger.finer(String.format("[%s] %s", tag, msg)); logToFile(Level.FINER, tag, msg); } public static void finest(String tag, String msg) { logger.finest(String.format("[%s] %s", tag, msg)); logToFile(Level.FINEST, tag, msg); } public static void log(Level level, String tag, Throwable throwable) { logger.log(level, String.format("[%s] Exception", tag), throwable); logToFile(level, tag, throwable); } public static void log(Level level, String tag, String msg, Throwable thrown) { logger.log(level, msg, thrown); logToFile(level, msg, thrown); } public static void severe(String tag, Throwable throwable) { logger.log(Level.SEVERE, tag, throwable); logToFile(Level.SEVERE, tag, throwable); } public static void warning(String tag, Throwable throwable) { logger.log(Level.WARNING, tag, throwable); logToFile(Level.WARNING, tag, throwable); } public static void info(String tag, Throwable throwable) { logger.log(Level.INFO, tag, throwable); logToFile(Level.INFO, tag, throwable); } public static void config(String tag, Throwable throwable) { logger.log(Level.CONFIG, tag, throwable); logToFile(Level.CONFIG, tag, throwable); } public static void fine(String tag, Throwable throwable) { logger.log(Level.FINE, tag, throwable); logToFile(Level.FINE, tag, throwable); } public static void finer(String tag, Throwable throwable) { logger.log(Level.FINER, tag, throwable); logToFile(Level.FINER, tag, throwable); } public static void finest(String tag, Throwable throwable) { logger.log(Level.FINEST, tag, throwable); logToFile(Level.FINEST, tag, throwable); } public static void warn(String tag, Throwable throwable) { warning(tag, throwable); } public static void debug(String tag, Throwable throwable) { fine(tag, throwable); } public static void error(String tag, Throwable throwable) { severe(tag, throwable); } public static void trace(String tag, Throwable throwable) { finer(tag, throwable); } public static void severe(String msg, String tag, Throwable throwable) { log(Level.SEVERE, tag, msg, throwable); } public static void warning(String msg, String tag, Throwable throwable) { log(Level.WARNING, tag, msg, throwable); } public static void info(String msg, String tag, Throwable throwable) { log(Level.INFO, tag, msg, throwable); } public static void config(String msg, String tag, Throwable throwable) { log(Level.CONFIG, tag, msg, throwable); } public static void fine(String msg, String tag, Throwable throwable) { log(Level.FINE, tag, msg, throwable); } public static void finer(String msg, String tag, Throwable throwable) { log(Level.FINER, tag, msg, throwable); } public static void finest(String msg, String tag, Throwable throwable) { log(Level.FINEST, msg, throwable); } public static void warn(String msg, String tag, Throwable throwable) { log(Level.WARNING, tag, msg, throwable); } public static void debug(String msg, String tag, Throwable throwable) { log(Level.FINE, tag, msg, throwable); } public static void error(String msg, String tag, Throwable throwable) { log(Level.SEVERE, tag, msg, throwable); } public static void trace(String msg, String tag, Throwable throwable) { log(Level.FINER, tag, msg, throwable); } private static boolean isCurrentDate(LocalDateTime dateTime) { return dateTime.toLocalDate().isEqual(lastFileDate.toLocalDate()); } private static String dateFormatterForFileName(LocalDateTime dateTime) { String dateString = ""; dateString += dateTime.getDayOfMonth(); dateString += dateTime.getMonthValue(); dateString += dateTime.getYear(); return dateString; } private static String dateFormatterForLogs(LocalDateTime dateTime) { String dateString = "["; dateString += dateTime.getDayOfMonth() + "_"; dateString += dateTime.getMonthValue() + "_"; dateString += dateTime.getYear() + "_"; dateString += dateTime.getHour() + ":"; dateString += dateTime.getMinute() + ":"; dateString += dateTime.getSecond(); dateString += "] "; return dateString; } private static void updateAndCreateFile(LocalDateTime dateTime) { if (!isCurrentDate(dateTime)) { lastFileDate = LocalDateTime.now(); currentFileName = pathToLogs + dateFormatterForFileName(lastFileDate) + ".log"; try { logginFile.flush(); logginFile.close(); final File file = new File(currentFileName); if (file.exists()) { logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); } else { final boolean created = file.createNewFile(); if (created) { logginFile = new PrintWriter(new BufferedWriter(new FileWriter(currentFileName, true))); } else { throw new NullPointerException("Error updating log file"); } } } catch (IOException ignored) { } } } private static void logToFile(Level level, String tag, Throwable throwable) { if (isLoggable(level)) { synchronized (lockToWrite) { final LocalDateTime currentDate = LocalDateTime.now(); final String dateForLog = dateFormatterForLogs(currentDate); updateAndCreateFile(currentDate); logThrowableToFile(level, tag, throwable, dateForLog); } } } private static void logToFile(Level level, String tag, String msg) { if (isLoggable(level)) { synchronized (lockToWrite) { final LocalDateTime currentDate = LocalDateTime.now(); updateAndCreateFile(currentDate); final String dateForLog = dateFormatterForLogs(currentDate); logMsgToFile(level, tag, msg, dateForLog); } } } private static void logToFile(Level level, String tag, String msg, Throwable throwable) { if (isLoggable(level)) { synchronized (lockToWrite) { final LocalDateTime currentDate = LocalDateTime.now(); updateAndCreateFile(currentDate); final String dateForLog = dateFormatterForLogs(currentDate); logMsgToFile(level, tag, msg, dateForLog); logThrowableToFile(level, tag, throwable, dateForLog); } } } private static void logMsgToFile(Level level, String tag, String msg, String dateForLog) { final String logMessage = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, msg); logsToFile.add(logMessage); synchronized (logsToFile) { logsToFile.notifyAll(); } } private static void logThrowableToFile(Level level, String tag, Throwable throwable, String dateForLog) { String throwableLog = String.format("%s{%s} %s - %s", dateForLog, level.toString(), tag, throwable.toString()); for (StackTraceElement element : throwable.getStackTrace()) { throwableLog += "\tat " + element + "\n"; } logsToFile.add(throwableLog); synchronized (logsToFile) { logsToFile.notifyAll(); } } private static boolean isLoggable(Level level) { return logger.isLoggable(level); } private static class LoggerThread extends Thread { @Override public void run() { while (true) { final ConcurrentLinkedQueue<String> stringsToLog = new ConcurrentLinkedQueue<>(); synchronized (logsToFile) { if (logsToFile.isEmpty()) { try { logsToFile.wait(); } catch (InterruptedException e) { return; } if (logsToFile.isEmpty()) { continue; } } stringsToLog.addAll(logsToFile); logsToFile.clear(); } stringsToLog.stream().forEach(logginFile::println); logginFile.flush(); } } } }
package ccw.builder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import ccw.CCWPlugin; import ccw.launching.ClojureLaunchDelegate; import ccw.repl.REPLView; /* * gaetan.morice: * " * Note that this code is just a prototype and there is still lots of problems to fix. Among then : * Incremental build : I only implement full build. * Synchronization with JDT build : as clojure and java files could depend on each others, the two builders * need to be launch several time to resolve all the dependencies. */ public class ClojureBuilder extends IncrementalProjectBuilder { public static final String CLOJURE_COMPILER_PROBLEM_MARKER_TYPE = "ccw.markers.problemmarkers.compilation"; static public final String BUILDER_ID = "ccw.builder"; @SuppressWarnings("unchecked") @Override protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { // System.out.println("clojure build required"); if (getProject()==null) { return null; } if (kind == AUTO_BUILD || kind == INCREMENTAL_BUILD) { if (onlyClassesOrOutputFolderRelatedDelta() && !onlyProjectTouched() ) { // System.out.println("nothing to build (onlyClassesOrOutputFolderRelatedDelta()=" + onlyClassesOrOutputFolderRelatedDelta() // + ", !onlyProjectTouched()=" + !onlyProjectTouched()); return null; } } fullBuild(getProject(), monitor); return null; } /** Only project touch is treated similarly to a full build request */ private boolean onlyProjectTouched() { IResourceDelta delta = getDelta(getProject()); return delta.getResource().equals(getProject()) && delta.getAffectedChildren().length == 0; } private boolean onlyClassesOrOutputFolderRelatedDelta() throws CoreException { if (getDelta(getProject()) == null) { return false; } List<IPath> folders = new ArrayList<IPath>(); folders.add(getClassesFolder(getProject()).getFullPath()); for (IFolder outputPath: getSrcFolders(getProject()).values()) { folders.add(outputPath.getFullPath()); } folders.add(getProject().getFolder(".settings").getFullPath()); delta_loop: for (IResourceDelta d: getDelta(getProject()).getAffectedChildren()) { for (IPath folder: folders) { if (folder.isPrefixOf(d.getFullPath())) { continue delta_loop; } } // System.out.println("affected children for build:" + d.getFullPath()); return false; } return true; } protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) { // TODO Auto-generated method stub } public static void fullBuild(IProject project, IProgressMonitor monitor) throws CoreException{ if(monitor == null) { monitor = new NullProgressMonitor(); } createClassesFolder(project, monitor); // Issue #203 is probably related to the following way of getting a REPLView. // A race condition between the builder and the Eclipse machinery creating the views, etc. // We will probably have to refactor stuff to separate things a little bit more, but for the time // being, as an experiment and hopefully a temporary patch for the problem, I'll just add a little bit // delay in the build: // TODO see if we can do something more clever than having to use the UI thread and get a View object ... REPLView repl = CCWPlugin.getDefault().getProjectREPL(project); if (repl == null) { // Another chance, to fight with a hack, temporarily at least, the race condition try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } repl = CCWPlugin.getDefault().getProjectREPL(project); } if (repl == null || repl.isDisposed() || !ClojureLaunchDelegate.isAutoReloadEnabled(repl.getLaunch())) { // System.out.println("REPL not found, or disposed, or autoReloadEnabled not found on launch configuration"); return; } deleteMarkers(project); ClojureVisitor visitor = new ClojureVisitor(repl.getToolingConnection()); visitor.visit(getSrcFolders(project)); getClassesFolder(project).refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 0)); } private static IFolder getClassesFolder(IProject project) { return project.getFolder("classes"); } private static Map<IFolder, IFolder> getSrcFolders(IProject project) throws CoreException { Map<IFolder, IFolder> srcFolders = new HashMap<IFolder, IFolder>(); IJavaProject jProject = JavaCore.create(project); IClasspathEntry[] entries = jProject.getResolvedClasspath(true); IPath defaultOutputFolder = jProject.getOutputLocation(); for(IClasspathEntry entry : entries){ switch (entry.getEntryKind()) { case IClasspathEntry.CPE_SOURCE: IFolder folder = project.getWorkspace().getRoot().getFolder(entry.getPath()); IFolder outputFolder = project.getWorkspace().getRoot().getFolder( (entry.getOutputLocation()==null) ? defaultOutputFolder : entry.getOutputLocation()); if (folder.exists()) srcFolders.put(folder, outputFolder); break; case IClasspathEntry.CPE_LIBRARY: break; case IClasspathEntry.CPE_PROJECT: // TODO should compile here ? break; case IClasspathEntry.CPE_CONTAINER: case IClasspathEntry.CPE_VARIABLE: // Impossible cases, since entries are resolved default: break; } } return srcFolders; } private static void createClassesFolder(IProject project, IProgressMonitor monitor) throws CoreException { if (!getClassesFolder(project).exists()) { getClassesFolder(project).create(true, true, monitor); } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { if (monitor==null) { monitor = new NullProgressMonitor(); } try { getClassesFolder(getProject()).delete(true, monitor); createClassesFolder(getProject(), monitor); getClassesFolder(getProject()).refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 0)); getClassesFolder(getProject()).setDerived(true); //, monitor); removed monitor argument, probably a 3.5/3.6 only stuff } catch (CoreException e) { CCWPlugin.logError("Unable to correctly clean classes folder", e); } deleteMarkers(getProject()); } private static void deleteMarkers(IProject project) throws CoreException { for (IFolder srcFolder: getSrcFolders(project).keySet()) { srcFolder.deleteMarkers(CLOJURE_COMPILER_PROBLEM_MARKER_TYPE, true, IFile.DEPTH_INFINITE); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.wiztools.restclient.xml; import org.wiztools.restclient.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author rsubramanian */ public final class XMLUtil { public static Document request2XML(final RequestBean bean) throws ParserConfigurationException { Document xmldoc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); Element e = null; Element request = null; Node n = null; Element subChild = null; Node node = null; xmldoc = impl.createDocument(null, "rest-client", null); Element root = xmldoc.getDocumentElement(); request = xmldoc.createElementNS(null, "request"); // creating the URL child element e = xmldoc.createElementNS(null, "URL"); n = xmldoc.createTextNode(bean.getUrl().toString()); e.appendChild(n); request.appendChild(e); // creating the method child element e = xmldoc.createElementNS(null, "method"); n = xmldoc.createTextNode(bean.getMethod()); e.appendChild(n); request.appendChild(e); // creating the auth-methods child element List<String> authMethods = bean.getAuthMethods(); if (authMethods != null || authMethods.size() > 0) { e = xmldoc.createElementNS(null, "auth-methods"); String methods = ""; for (String authMethod : authMethods) { methods = methods + authMethod + ","; } String authenticationMethod = methods.substring(0, methods.length() - 1); n = xmldoc.createTextNode(authenticationMethod); e.appendChild(n); request.appendChild(e); } // creating the auth-preemptive child element Boolean authPreemptive = bean.isAuthPreemptive(); if (authPreemptive != null) { e = xmldoc.createElementNS(null, "auth-preemptive"); n = xmldoc.createTextNode(authPreemptive.toString()); e.appendChild(n); request.appendChild(e); } // creating the auth-host child element String authHost = bean.getAuthHost(); if (authHost != null) { e = xmldoc.createElementNS(null, "auth-host"); n = xmldoc.createTextNode(authHost); e.appendChild(n); request.appendChild(e); } // creating the auth-realm child element String authRealm = bean.getAuthRealm(); if (authRealm != null) { e = xmldoc.createElementNS(null, "auth-realm"); n = xmldoc.createTextNode(authRealm); e.appendChild(n); request.appendChild(e); } // creating the auth-username child element String authUsername = bean.getAuthUsername(); if (authUsername != null) { e = xmldoc.createElementNS(null, "auth-username"); n = xmldoc.createTextNode(authUsername); e.appendChild(n); request.appendChild(e); } // creating the auth-password child element String authPassword = bean.getAuthPassword().toString(); if (authPassword != null) { e = xmldoc.createElementNS(null, "auth-password"); n = xmldoc.createTextNode(authPassword); e.appendChild(n); request.appendChild(e); } // creating the headers child element Map<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { e = xmldoc.createElementNS(null, "headers"); for (String key : headers.keySet()) { String value = headers.get(key); subChild = xmldoc.createElementNS(null, "header"); subChild.setAttributeNS(null, "key", key); subChild.setAttributeNS(null, "value", value); e.appendChild(subChild); } request.appendChild(e); } // creating the body child element ReqEntityBean rBean = bean.getBody(); if (rBean.getBody() != null) { e = xmldoc.createElementNS(null, "body"); String contentType = rBean.getContentType(); String charSet = rBean.getCharSet(); String body = rBean.getBody(); e.setAttributeNS(null, "content-type", contentType); e.setAttributeNS(null, "charset", charSet); n = xmldoc.createTextNode(body); e.appendChild(n); request.appendChild(e); } root.appendChild(request); return xmldoc; } public static RequestBean xml2Request(final Document doc) throws MalformedURLException { RequestBean requestBean = new RequestBean(); NodeList elements = null; Node node = null; //get url elements = doc.getElementsByTagName("URL"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); URL url = new URL(node.getTextContent()); requestBean.setUrl(url); } //get method elements = doc.getElementsByTagName("method"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); requestBean.setMethod(node.getTextContent()); } //get auth-methods elements = doc.getElementsByTagName("auth-methods"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); String[] authenticationMethods = node.getTextContent().split(","); for (int j = 0; j < authenticationMethods.length; j++) { requestBean.addAuthMethod(authenticationMethods[j]); } } //get auth-preemptive elements = doc.getElementsByTagName("auth-preemptive"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); if (node.getTextContent().equals("true")) { requestBean.setAuthPreemptive(true); } else{ requestBean.setAuthPreemptive(false); } } //get auth-host elements = doc.getElementsByTagName("auth-host"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); requestBean.setAuthHost(node.getTextContent()); } //get auth-realm elements = doc.getElementsByTagName("auth-realm"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); requestBean.setAuthRealm(node.getTextContent()); } //get auth-username elements = doc.getElementsByTagName("auth-username"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); requestBean.setAuthUsername(node.getTextContent()); } //get password elements = doc.getElementsByTagName("auth-password"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); requestBean.setAuthPassword(node.getTextContent().toCharArray()); } //get headers elements = doc.getElementsByTagName("header"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); NamedNodeMap nodeMap = node.getAttributes(); Node key = nodeMap.getNamedItem("key"); Node value = nodeMap.getNamedItem("value"); requestBean.addHeader(key.getNodeValue(), value.getNodeValue()); } //get body elements = doc.getElementsByTagName("body"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); NamedNodeMap nodeMap = node.getAttributes(); Node contentType = nodeMap.getNamedItem("content-type"); Node charSet = nodeMap.getNamedItem("charset"); requestBean.setBody(new ReqEntityBean(node.getTextContent(), contentType.getNodeValue(), charSet.getNodeValue())); } return requestBean; } public static Document response2XML(final ResponseBean bean) throws ParserConfigurationException { Document xmldoc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); Element e = null; Node n = null; Element response = null; Element subChild = null; xmldoc = impl.createDocument(null, "rest-client", null); Element root = xmldoc.getDocumentElement(); response = xmldoc.createElementNS(null, "response"); // creating the status child element e = xmldoc.createElementNS(null, "status"); e.setAttributeNS(null, "code", String.valueOf(bean.getStatusCode())); n = xmldoc.createTextNode(bean.getStatusLine()); e.appendChild(n); response.appendChild(e); // creating the headers child element Map<String, String> headers = bean.getHeaders(); if (!headers.isEmpty()) { e = xmldoc.createElementNS(null, "headers"); for (String key : headers.keySet()) { String value = headers.get(key); subChild = xmldoc.createElementNS(null, "header"); subChild.setAttributeNS(null, "key", key); subChild.setAttributeNS(null, "value", value); e.appendChild(subChild); } response.appendChild(e); } //creating the body child element String responseBody = bean.getResponseBody(); if (responseBody != null) { e = xmldoc.createElementNS(null, "body"); n = xmldoc.createTextNode(responseBody); e.appendChild(n); response.appendChild(e); } root.appendChild(response); return xmldoc; } public static ResponseBean xml2Response(final Document doc) { ResponseBean responseBean = new ResponseBean(); NodeList elements = null; Node node = null; //get status line and status code elements = doc.getElementsByTagName("status"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); responseBean.setStatusLine(node.getTextContent()); NamedNodeMap nodeMap = node.getAttributes(); Node n = nodeMap.getNamedItem("code"); responseBean.setStatusCode(Integer.parseInt(n.getNodeValue())); } //get headers elements = doc.getElementsByTagName("header"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); NamedNodeMap nodeMap = node.getAttributes(); Node key = nodeMap.getNamedItem("key"); Node value = nodeMap.getNamedItem("value"); responseBean.addHeader(key.getNodeValue(), value.getNodeValue()); } //get body elements = doc.getElementsByTagName("body"); for (int i = 0; i < elements.getLength(); i++) { node = elements.item(i); System.out.println("body content" + node.getTextContent()); responseBean.setResponseBody(node.getTextContent()); } return responseBean; } public static void writeXML(final Document doc, final File f) throws IOException, TransformerConfigurationException, TransformerException { DOMSource domSource = new DOMSource(doc); FileOutputStream out = new FileOutputStream(f); StreamResult streamResult = new StreamResult(out); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.transform(domSource, streamResult); } public static Document getDocumentFromFile(final File f) throws IOException, XMLException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); return doc; } catch (ParserConfigurationException ex) { throw new XMLException(ex.getMessage(), ex); } catch (SAXException ex) { throw new XMLException(ex.getMessage(), ex); } } public static void writeRequestXML(final RequestBean bean, final File f) throws IOException, ParserConfigurationException, TransformerConfigurationException, TransformerException { Document doc = request2XML(bean); writeXML(doc, f); } public static void writeResponseXML(final ResponseBean bean, final File f) throws IOException, ParserConfigurationException, TransformerConfigurationException, TransformerException { Document doc = response2XML(bean); writeXML(doc, f); } public static void writeXMLRequest(final File f, RequestBean bean) throws IOException, XMLException { Document doc = getDocumentFromFile(f); bean = xml2Request(doc); } public static void writeXMLResponse(final File f, ResponseBean bean) throws IOException, XMLException { Document doc = getDocumentFromFile(f); bean = xml2Response(doc); } public static RequestBean getRequestFromXMLFile(final File f) throws IOException, XMLException { Document doc = getDocumentFromFile(f); return xml2Request(doc); } }
package py.una.med.base.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.component.html.HtmlOutcomeTargetLink; import javax.faces.component.html.HtmlOutputLink; import javax.faces.context.FacesContext; import org.richfaces.component.UIPanelMenu; import org.richfaces.component.UIPanelMenuGroup; import org.richfaces.component.UIPanelMenuItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.context.WebApplicationContext; import py.una.med.base.breadcrumb.BreadcrumbController; import py.una.med.base.configuration.PropertiesUtil; import py.una.med.base.domain.Menu; import py.una.med.base.domain.Menu.Menus; import py.una.med.base.dynamic.forms.SIGHComponentFactory; import py.una.med.base.util.HostResolver; import py.una.med.base.util.I18nHelper; /** * Clase que implementa la creacion del menu de la aplicacion. * * @author Arturo Volpe Torres * @since 1.0 * @version 1.0 Feb 20, 2013 * */ @SessionScoped @Controller @ManagedBean @Scope(value = WebApplicationContext.SCOPE_SESSION) public class MenuBean { private UIPanelMenu menupanel; // private final Logger logger = LoggerFactory.getLogger(MenuBean.class); @Autowired private Menus menus; @Autowired private I18nHelper helper; private HashMap<String, Boolean> expanded; @Autowired private PropertiesUtil properties; @Autowired private HostResolver hostResolver; /** * Configura y retorna un menu * * @return Menu entero de la aplicacion */ public UIPanelMenu getMenu() { // XXX Ver como generar el menupanel UNA sola vez. menupanel = SIGHComponentFactory.getMenu(); menupanel.setGroupExpandedLeftIcon("triangleUp"); menupanel.setGroupCollapsedLeftIcon("triangleDown"); menupanel.setTopGroupExpandedRightIcon("chevronUp"); menupanel.setTopGroupCollapsedRightIcon("chevronDown"); menupanel.setItemLeftIcon("disc"); menupanel.setStyleClass("menu"); menupanel.getChildren().clear(); menupanel.getChildren().addAll(buildMenu()); return menupanel; } /** * Si se llama a esta funcion algo esta mal, se utiliza solamente para que * "menu" sea una atributo de menuBean * * @param obj */ public void setMenu(UIPanelMenu menupanel) { this.menupanel = menupanel; } private List<UIComponent> buildMenu() { List<UIComponent> menuGroups = new ArrayList<UIComponent>( menus.menus.size()); for (Menu menu : menus.menus) { UIComponent component = getComponent(menu); if (component != null) { menuGroups.add(component); } } return menuGroups; } private UIComponent getComponent(Menu menu) { if (!isVisible(menu)) { return null; } if (menu.getChildrens() == null || menu.getChildrens().size() == 0) { return getSingleMenu(menu); } else { return getMultipleMenu(menu); } } private UIComponent getMultipleMenu(Menu menu) { UIPanelMenuGroup menuGroup = SIGHComponentFactory.getMenuGroup(); menuGroup.setId(menu.getIdFather() + menu.getId()); menuGroup.setLabel(helper.getString(menu.getName())); menuGroup.setExpanded(false); for (Menu children : menu.getChildrens()) { UIComponent component = getComponent(children); if (component != null) { menuGroup.getChildren().add(component); } } if (menuGroup.getChildren().isEmpty()) { return null; } return menuGroup; } private UIComponent getSingleMenu(Menu menu) { UIPanelMenuItem item = SIGHComponentFactory.getMenuItem(); item.setId(menu.getIdFather() + menu.getId()); item.setLabel(helper.getString(menu.getName())); UIComponent link; if (menu.getUrl() != null) { String menuUrl = menu.getUrl(); String appPlaceHolder = properties .getProperty("application.appUrlPlaceHolder"); if (menuUrl.startsWith(appPlaceHolder) || menuUrl.startsWith("/view")) { // link correspondiente a este sistema menuUrl = menuUrl.replace(appPlaceHolder, ""); link = SIGHComponentFactory.getLink(); ((HtmlOutcomeTargetLink) link).setOutcome(menuUrl + BreadcrumbController.BREADCRUM_URL); menu.setUrl(menuUrl); } else { String urlPlaceHolder = menuUrl.substring(0, menuUrl.indexOf("/")); // link a otro sistema menuUrl = menuUrl.replace(urlPlaceHolder, hostResolver.getSystemURL(urlPlaceHolder)); link = FacesContext .getCurrentInstance() .getApplication() .createComponent(FacesContext.getCurrentInstance(), HtmlOutputLink.COMPONENT_TYPE, "javax.faces.Link"); ((HtmlOutputLink) link).setValue(menuUrl + BreadcrumbController.BREADCRUM_URL); menu.setUrl(menuUrl); } } else { link = SIGHComponentFactory.getLink(); } link.getChildren().add(item); return link; } private boolean isVisible(Menu menu) { if (menu == null) { return false; } if (menu.getPermissions() == null) { return true; } for (String permission : menu.getPermissions()) { if (AuthorityController.hasRoleStatic(permission)) { return true; } } return false; } /** * Retorna si un menu dado debe estar expandido * * @return lista de menus, con su corresopndiente debe estar o no expandido */ public HashMap<String, Boolean> getExpanded() { return expanded; } /** * * @param expanded */ public void setExpanded(HashMap<String, Boolean> expanded) { this.expanded = expanded; } }
package se.cybercom.rest.doc; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.CodeSource; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import org.slf4j.Logger; /** * * @author Peter Ivarsson Peter.Ivarsson@cybercom.com */ @Startup @Singleton public class RestDocHandler { private static final Logger logger = org.slf4j.LoggerFactory.getLogger( RestDocHandler.class.getName() ); public static RestInfo restInfo = new RestInfo(); /** * Add the folowing in wildfly * * <system-properties> * <property name="use.rest-doc" value="yes"/> * </system-properties> */ @PostConstruct private void init() { restInfo.setClassInfo( new ArrayList<>() ); restInfo.setDataModelInfo( new ArrayList<>() ); String useRestDoc = System.getProperty( "use.rest-doc" ); if( (useRestDoc != null) && useRestDoc.equals( "yes" ) ) { // Only do this if the file useRestDoc property is yes CodeSource src = RestDocHandler.class.getProtectionDomain().getCodeSource(); if( src != null ) { URL jar = src.getLocation(); try { Files.walk( Paths.get( jar.getPath() ) ) .filter( Files::isRegularFile ) .forEach( ( path ) -> { checkClassFilesForPathAnnotations( path ); } ); } catch( IOException ioe ) { logger.debug( "IOException reading war file: " + ioe.getMessage() ); } } } } private void checkClassFilesForPathAnnotations( Path classNamePath ) { logger.debug( "Class file: " + classNamePath.getFileName().toString() ); ClassInfo classInfo = getFullClassName( classNamePath ); if( classInfo == null ) { // Skipp this file return; } if( classInfo.getPackageAndClassName().startsWith("se.cybercom.rest.doc" ) ) { // Skipp this file, Internal documention Classes return; } try { Class clazz = Class.forName( classInfo.getPackageAndClassName() ); Annotation[] annotations = clazz.getAnnotations(); for( Annotation annotation: annotations ) { if( annotation instanceof javax.ws.rs.Path ) { String pathValue = ((javax.ws.rs.Path) annotation).value(); // We found a class with Path annotation addClassInfoToRestInfoList( classInfo, (javax.ws.rs.Path) annotation ); } } checkClassMethodsForPathInformation( classInfo, clazz ); } catch( ClassNotFoundException cnfe ) { logger.debug( "ClassNotFoundException: " + cnfe.getMessage() ); } } private ClassInfo getFullClassName( Path classNamePath ) { String pathName; String className = ""; int classIndex; StringBuilder packetAndclassName = new StringBuilder(); boolean addDot = false; boolean addPackageName = false; int pathCount = classNamePath.getNameCount(); for( int i = 0; i < pathCount; i++ ) { if( addDot == true ) { packetAndclassName.append( "." ); } pathName = classNamePath.getName( i ).toString(); if( addPackageName == true ) { classIndex = pathName.indexOf( ".class" ); if( classIndex > 0 ) { className = pathName.substring( 0, classIndex ); packetAndclassName.append( className ); } else { packetAndclassName.append( pathName ); addDot = true; } } else { if( pathName.equals( "classes" ) ) { addPackageName = true; } } } if( className.contains( "$" ) ) { // Probarbly an enum value return null; } ClassInfo classInfo = new ClassInfo(); classInfo.setClassName( className ); classInfo.setPackageAndClassName( packetAndclassName.toString() ); return classInfo; } private void addClassInfoToRestInfoList( ClassInfo classInfo, javax.ws.rs.Path annotation ) { String pathValue = annotation.value(); classInfo.setClassRootPath( pathValue ); restInfo.getClassInfo().add( classInfo ); } private void checkClassMethodsForPathInformation( ClassInfo classInfo, Class clazz ) { Method[] methods = clazz.getDeclaredMethods(); for( Method method: methods ) { Annotation[] methodAnnotations = method.getAnnotations(); for( Annotation annotation: methodAnnotations ) { if( annotation instanceof javax.ws.rs.Path ) { // We found a method with Path annotation addMethodInfoToRestInfoList( classInfo, (javax.ws.rs.Path) annotation, method ); } } } } private void addMethodInfoToRestInfoList( ClassInfo classInfo, javax.ws.rs.Path annotation, Method method ) { if( classInfo.getClassRootPath() == null ) { // Add to restInfoList classInfo.setClassRootPath( "" ); restInfo.getClassInfo().add( classInfo ); } List<MethodInfo> methodInfoList = classInfo.getMethodInfo(); if( methodInfoList == null ) { classInfo.setMethodInfo( new ArrayList<>() ); } String pathValue; if( classInfo.getClassRootPath().length() > 0 ) { pathValue = classInfo.getClassRootPath() + "/" + annotation.value(); } else { pathValue = annotation.value(); } ReturnInfo returnInfo = new ReturnInfo(); MethodInfo methodInfo = new MethodInfo(); methodInfo.setReturnInfo( returnInfo ); methodInfo.setMethodName( method.getName() ); methodInfo.setRestPath( pathValue ); classInfo.getMethodInfo().add( methodInfo ); addMethodsPathMethod( methodInfo, returnInfo, method ); addMethodReturnType( methodInfo, returnInfo, method ); addMethodParameters( methodInfo, method ); } private void addMethodsPathMethod( MethodInfo methodInfo, ReturnInfo returnInfo, Method method ) { StringBuilder producesTypes = new StringBuilder(); boolean firstProduceType = true; StringBuilder consumeTypes = new StringBuilder(); boolean firstConsumeType = true; logger.debug( "Method: " + method.toGenericString() ); Annotation[] methodAnnotations = method.getAnnotations(); for( Annotation annotation: methodAnnotations ) { logger.debug( "Method Annotation: " + annotation.annotationType().toGenericString() ); if( annotation instanceof javax.ws.rs.GET ) { methodInfo.setHttpRequestType( "GET" ); } else { if( annotation instanceof javax.ws.rs.POST ) { methodInfo.setHttpRequestType( "POST" ); } else { if( annotation instanceof javax.ws.rs.PUT ) { methodInfo.setHttpRequestType( "PUT" ); } else { if( annotation instanceof javax.ws.rs.DELETE ) { methodInfo.setHttpRequestType( "DELETE" ); } else { if( annotation instanceof javax.ws.rs.Produces ) { javax.ws.rs.Produces produces = (javax.ws.rs.Produces) annotation; for( String returnType: produces.value() ) { if( firstProduceType == true ) { firstProduceType = false; } else { producesTypes.append( ", " ); } producesTypes.append( returnType ); } methodInfo.setProducesType(producesTypes.toString() ); } else { if( annotation instanceof javax.ws.rs.Consumes ) { javax.ws.rs.Consumes consumes = (javax.ws.rs.Consumes) annotation; for( String consumeType: consumes.value() ) { if( firstConsumeType == true ) { firstConsumeType = false; } else { consumeTypes.append( ", " ); } consumeTypes.append( consumeType ); } methodInfo.setConsumeType( consumeTypes.toString() ); } else { if( annotation instanceof se.cybercom.rest.doc.DocReturnType ) { se.cybercom.rest.doc.DocReturnType returnType = (se.cybercom.rest.doc.DocReturnType) annotation; addAnnotatedReturnType( returnInfo, returnType.key() ); } } } } } } } } } private void addMethodReturnType( MethodInfo methodInfo, ReturnInfo returnInfo, Method method ) { returnInfo.setReturnClassName( method.getReturnType().getName() ); } private void addAnnotatedReturnType( ReturnInfo returnInfo, String returnTypeClassName ) { returnInfo.setAnnotatedReturnType( returnTypeClassName ); addDomainDataInfo( returnTypeClassName ); } private void addDomainDataInfo( String className ) { try { Class clazz = Class.forName( className ); DataModelInfo dataModelInfo = new DataModelInfo(); dataModelInfo.setFields( new ArrayList<>() ); Method[] methods = clazz.getMethods(); for( Method method : methods ) { if( isGetter( method ) ) { String fieldType = method.getReturnType().getName(); if( ! fieldType.equals( "java.lang.Class" ) ) { FieldInfo fieldInfo = new FieldInfo(); char c[] = method.getName().substring( 3 ).toCharArray(); c[0] = Character.toLowerCase( c[0] ); fieldInfo.setFieldName( new String(c) ); fieldInfo.setFieldType( fieldType ); dataModelInfo.getFields().add( fieldInfo ); } } } if( ! dataModelInfo.getFields().isEmpty() ) { dataModelInfo.setPackageAndClassName( className ); restInfo.getDataModelInfo().add( dataModelInfo ); } } catch( ClassNotFoundException cnfe ) { logger.debug( "ClassNotFoundException: " + cnfe.getMessage() ); } } private void addMethodParameters( MethodInfo methodInfo, Method method ) { ParameterInfo parameterInfo; if( methodInfo.getParameterInfo() == null ) { methodInfo.setParameterInfo( new ArrayList<>() ); } for( Parameter parameter: method.getParameters() ) { Annotation[] annotations = parameter.getAnnotations(); for( Annotation annotation: annotations ) { if( annotation instanceof javax.ws.rs.PathParam ) { javax.ws.rs.PathParam pathParam = (javax.ws.rs.PathParam) annotation; parameterInfo = new ParameterInfo(); parameterInfo.setParameterType( "javax.ws.rs.PathParam" ); parameterInfo.setParameterAnnotationName( pathParam.value() ); parameterInfo.setParameterClassName( parameter.getType().getName() ); methodInfo.getParameterInfo().add( parameterInfo ); } else { if( annotation instanceof javax.ws.rs.HeaderParam ) { javax.ws.rs.HeaderParam headerParam = (javax.ws.rs.HeaderParam) annotation; parameterInfo = new ParameterInfo(); parameterInfo.setParameterType( "javax.ws.rs.HeaderParam" ); parameterInfo.setParameterAnnotationName( headerParam.value() ); parameterInfo.setParameterClassName( parameter.getType().getName() ); methodInfo.getParameterInfo().add( parameterInfo ); } } } if( annotations.length == 0 ) { // This parameter has no annotation parameterInfo = new ParameterInfo(); if( methodInfo.getConsumeType().isEmpty() ) { parameterInfo.setParameterType( "-" ); } else { parameterInfo.setParameterType( methodInfo.getConsumeType() ); } if( parameter.getName().startsWith( "arg" ) ) { switch( parameter.getName().charAt( 3 ) ) { case '0': parameterInfo.setParameterAnnotationName( "First argument" ); break; case '1': parameterInfo.setParameterAnnotationName( "Second argument" ); break; case '2': parameterInfo.setParameterAnnotationName( "Third argument" ); break; case '3': parameterInfo.setParameterAnnotationName( "Fourth argument" ); break; case '4': parameterInfo.setParameterAnnotationName( "Fifth argument" ); break; case '5': parameterInfo.setParameterAnnotationName( "Sixth argument" ); break; case '6': parameterInfo.setParameterAnnotationName( "Seventh argument" ); break; case '7': parameterInfo.setParameterAnnotationName( "Eighth argument" ); break; case '8': parameterInfo.setParameterAnnotationName( "Ninth argument" ); break; case '9': parameterInfo.setParameterAnnotationName( "Tenth argument" ); break; default: parameterInfo.setParameterAnnotationName( "-" ); break; } } else { parameterInfo.setParameterAnnotationName( parameter.getName() ); } parameterInfo.setParameterClassName( parameter.getType().getName() ); methodInfo.getParameterInfo().add( parameterInfo ); addDomainDataInfo(parameter.getType().getName() ); logger.debug( "Parameter without annotation: " + parameter.getName() + " Type: " + parameter.getType().getName() ); } } } private boolean isGetter( Method method ) { if( ! method.getName().startsWith( "get" ) ) return false; if( method.getParameterTypes().length != 0 ) return false; return ! method.getReturnType().equals( void.class ); } }
package shadow.doctool; import java.io.StringWriter; import java.util.ArrayDeque; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import shadow.Loggers; import shadow.AST.ASTWalker.WalkType; import shadow.AST.AbstractASTVisitor; import shadow.parser.javacc.ASTClassOrInterfaceDeclaration; import shadow.parser.javacc.ASTCompilationUnit; import shadow.parser.javacc.ASTEnumDeclaration; import shadow.parser.javacc.ASTFieldDeclaration; import shadow.parser.javacc.ASTGenericDeclaration; import shadow.parser.javacc.ASTMethodDeclaration; import shadow.parser.javacc.ShadowException; import shadow.parser.javacc.ShadowParser.TypeKind; import shadow.typecheck.Package; public class DocumentationVisitor extends AbstractASTVisitor { private static final Logger logger = Loggers.DOC_TOOL; private Document document; private org.w3c.dom.Node currentNode;; public DocumentationVisitor() throws ParserConfigurationException { // Create a new document to represent the top-level class in question DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); currentNode = document.appendChild(document.createElement("shadowdoc")); } public void OutputDocumentation() { try { // Convert and output the DOM as an XML document Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); System.out.println(writer.toString()); } catch (Exception e) { System.out.println("Unable to output documentation:"); System.out.println(e); } } @Override public Object visit(ASTMethodDeclaration node, Boolean secondVisit) throws ShadowException { //printDocumentation(node, depth); /* System.out.println(node.getModifiers()); System.out.println(getPackageName(node.getType())); System.out.println(node.jjtGetChild(0).getImage()); MethodType type = (MethodType)node.getType(); System.out.println(type.getReturnTypes()); for (String parameter : type.getParameterNames()) { System.out.println(parameter); System.out.println(type.getParameterType(parameter).getType()); } */ Element method = (Element) currentNode.appendChild(document.createElement("method")); // The first child of an ASTMethodDeclaration is an ASTMethodDeclarator. // We retrieve the method name from this child method.setAttribute("name", node.jjtGetChild(0).getImage()); return WalkType.NO_CHILDREN; } @Override public Object visit(ASTFieldDeclaration node, Boolean secondVisit) throws ShadowException { Element field = (Element) currentNode.appendChild(document.createElement("field")); // The second child of an ASTFieldDeclaration is an ASTVariableDeclarator. // We retrieve the variable name from this child field.setAttribute("name", node.jjtGetChild(1).getImage()); field.setAttribute("type", node.getType().getQualifiedName()); return WalkType.NO_CHILDREN; } @Override public Object visit(ASTClassOrInterfaceDeclaration node, Boolean secondVisit) throws ShadowException { if (secondVisit) { // Step out of tag for this class currentNode = currentNode.getParentNode(); } else { // Create package tags if this is the outermost class if (node.jjtGetParent() instanceof ASTCompilationUnit) currentNode = appendPackages(currentNode, node.getType().getPackage()); // Create a tag using the name associated with this nodes ClassType/TypeKind currentNode = currentNode.appendChild(document.createElement(getClassTag(node.getKind()))); ((Element) currentNode).setAttribute("name", node.getImage()); } return WalkType.POST_CHILDREN; } @Override public Object visit(ASTEnumDeclaration node, Boolean secondVisit) throws ShadowException { if (secondVisit) { } else { } return WalkType.POST_CHILDREN; } // TODO: Figure out what exactly this is and whether or not it will need to // have documentation support @Override public Object visit(ASTGenericDeclaration node, Boolean secondVisit) throws ShadowException { if (secondVisit) { } else { } return WalkType.POST_CHILDREN; } /** * Climbs the tree of packages and then appends corresponding tags to the * given document node in top-bottom order. Returns the node corresponding * to the lowest package. */ private Node appendPackages(Node root, Package lowest) { ArrayDeque<String> packages = new ArrayDeque<String>(); // Climb the chain of packages Package currentPackage = lowest; do { packages.addFirst(getPackageName(currentPackage)); currentPackage = currentPackage.getParent(); } while (currentPackage != null); Node current = root; for (String packageName : packages) { current = current.appendChild(document.createElement("package")); ((Element) current).setAttribute("name", packageName); } return current; } /** Returns the proper name for a ClassType tag based on its TypeKind */ private static String getClassTag(TypeKind kind) { switch (kind) { case CLASS: return "class"; case EXCEPTION: return "exception"; case ENUM: return "enum"; case INTERFACE: return "interface"; case SINGLETON: return "singleton"; default: return null; // Shouldn't be possible } } /** Returns the qualified name of a given package */ private static String getPackageName(Package containingPackage) { if (containingPackage == null || containingPackage.getQualifiedName().isEmpty()) return "default"; else return containingPackage.getQualifiedName(); } }
package wasdev.sample.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SimpleServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().print("Hello Walters GitWorld!"); response.getWriter().print("<br/> 3 + 4 Sum is 7"); } }
package wasdev.sample.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.ibm.watson.developer_cloud.language_translator.v2.LanguageTranslator; import com.ibm.watson.developer_cloud.language_translator.v2.model.Language; import com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationResult; import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AudioFormat; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; /** * Servlet implementation class SimpleServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().println("Hello World! Mi primera colonia, chispas..."); try{ //Buscar servicio Language Translator LanguageTranslator servicioTraduccion = buscarServicioTranslator(); //Traducir texto String cadenaATraducir = "The rain in Spain stays mainly on the plain"; response.getWriter().println(cadenaATraducir); String resultado = traduce( servicioTraduccion, cadenaATraducir ); response.setContentType("text/html"); response.getWriter().println(resultado); //Buscar servicio Text to Speech String urlServicioVoz = "https://stream.watsonplatform.net/text-to-speech/api"; String passwordServicioVoz = "TVeaxrFKR35N"; String userServicioVoz = "64210083-c962-4ef1-8627-74a5dbbc3b84"; TextToSpeech servicioVoz = new TextToSpeech(); servicioVoz.setUsernameAndPassword(userServicioVoz, passwordServicioVoz); List<Voice> voices = servicioVoz.getVoices().execute(); System.out.println(voices); //TODO-Establecer voz //Definir audio //Sintentizar voz //servicioVoz.synthesize(resultado, voices.get(1)); AudioFormat audioFormat = new AudioFormat("audio/wav"); servicioVoz.synthesize(resultado, voices.get(1), audioFormat); response.getWriter().println("Ha sonado la voz"); }catch( Exception ex){ System.out.println(ex); } } private LanguageTranslator buscarServicioTranslator() throws Exception{ String username = ""; String password = ""; String url = ""; System.out.println("VCAP_SERVICES " + System.getenv("VCAP_SERVICES") + "*************"); if (System.getenv("VCAP_SERVICES") == null || System.getenv("VCAP_SERVICES").equals("{}")){ username = "43f7d029-7b34-4b75-854e-661e10d2a766"; password = "QL5niDv8BYvh"; url = "https://gateway.watsonplatform.net/language-translator/api"; }else{ JsonObject vcap = new JsonParser().parse(System.getenv("VCAP_SERVICES")).getAsJsonObject(); System.out.println("vcal " + vcap.toString()); JsonObject language = vcap.getAsJsonArray("language_translator").get(0).getAsJsonObject(); System.out.println("language " + vcap.toString()); JsonObject credentials = language.getAsJsonObject("credentials"); System.out.println("credentials " + vcap.toString()); username = credentials.get("username").getAsString(); password = credentials.get("password").getAsString(); url = credentials.get("url").getAsString(); } LanguageTranslator service = new LanguageTranslator(); service.setEndPoint(url); service.setUsernameAndPassword(username, password); return service; } private String traduce (LanguageTranslator servicio, String input) throws Exception{ TranslationResult translationResult = servicio.translate(input, Language.ENGLISH, Language.SPANISH).execute(); System.out.println(translationResult.getFirstTranslation()); return translationResult.getFirstTranslation(); } }
package wasdev.sample.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SimpleServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().print("Welcome back Mr. Beeru Singh!*************"); } }
package net.finmath.time; import java.util.ArrayList; import java.util.Date; import org.joda.time.LocalDate; import net.finmath.time.businessdaycalendar.BusinessdayCalendarAny; import net.finmath.time.businessdaycalendar.BusinessdayCalendarInterface; import net.finmath.time.businessdaycalendar.BusinessdayCalendarInterface.DateRollConvention; import net.finmath.time.daycount.DayCountConventionInterface; import net.finmath.time.daycount.DayCountConvention_30E_360; import net.finmath.time.daycount.DayCountConvention_30E_360_ISDA; import net.finmath.time.daycount.DayCountConvention_30U_360; import net.finmath.time.daycount.DayCountConvention_ACT_360; import net.finmath.time.daycount.DayCountConvention_ACT_365; import net.finmath.time.daycount.DayCountConvention_ACT_ACT_ISDA; /** * Generates a schedule based on some meta data (frequency, maturity, date roll convention, etc.). * A schedule is just a collection of {@link net.finmath.time.Period}s. * * <ul> * <li>The period length is specified via {@link net.finmath.time.ScheduleGenerator.Frequency}. * <li>The schedule generation considers short periods via the specification of {@link net.finmath.time.ScheduleGenerator.DaycountConvention}.</li> * <li>The schedule may use an externally provided business day adjustment via an object implementing {@link net.finmath.time.businessdaycalendar.BusinessdayCalendarInterface}</li> * <li>You may specify fixing and payment adjustments. * </ul> * * @author Christian Fries * @date 02.03.2014 */ public class ScheduleGenerator { /** * Possible frequencies supported by {@link ScheduleGenerator}. * * @author Christian Fries */ public enum Frequency { /** Daily periods. **/ DAILY, /** Weekly periods. **/ WEEKLY, /** One months periods. **/ MONTHLY, /** Three months periods. **/ QUARTERLY, /** Six months periods. **/ SEMIANNUAL, /** Twelve months periods. **/ ANNUAL, /** A single period, i.e., the period is as long as from start to maturity. **/ TENOR } /** * Possible day count conventions supported by {@link DaycountConvention}. * * @author Christian Fries */ public enum DaycountConvention { /** See {@link net.finmath.time.daycount.DayCountConvention_30E_360_ISDA }. **/ E30_360_ISDA, /** See {@link net.finmath.time.daycount.DayCountConvention_30E_360 }. **/ E30_360, /** See {@link net.finmath.time.daycount.DayCountConvention_30U_360 }. **/ U30_360, /** See {@link net.finmath.time.daycount.DayCountConvention_ACT_360 }. **/ ACT_360, /** See {@link net.finmath.time.daycount.DayCountConvention_ACT_365 }. **/ ACT_365, /** See {@link net.finmath.time.daycount.DayCountConvention_ACT_ACT_ISDA }. **/ ACT_ACT_ISDA, ACT_ACT; public static DaycountConvention getEnum(String string) { if(string == null) throw new IllegalArgumentException(); if(string.equalsIgnoreCase("30e/360 isda")) return E30_360_ISDA; if(string.equalsIgnoreCase("e30/360 isda")) return E30_360_ISDA; if(string.equalsIgnoreCase("30e/360")) return E30_360; if(string.equalsIgnoreCase("e30/360")) return E30_360; if(string.equalsIgnoreCase("30/360")) return E30_360; if(string.equalsIgnoreCase("30u/360")) return U30_360; if(string.equalsIgnoreCase("u30/360")) return U30_360; if(string.equalsIgnoreCase("act/360")) return ACT_360; if(string.equalsIgnoreCase("act/365")) return ACT_365; if(string.equalsIgnoreCase("act/act isda")) return ACT_ACT_ISDA; if(string.equalsIgnoreCase("act/act")) return ACT_ACT; return DaycountConvention.valueOf(string.toUpperCase()); } } /** * Possible stub period conventions supported. * * @author Christian Fries */ public enum ShortPeriodConvention { /** The first period will be shorter, if a regular period does not fit. **/ FIRST, /** The last period will be shorter, if a regular period does not fit. **/ LAST } private ScheduleGenerator() { } /** * Schedule generation for given {referenceDate,startDate,maturityDate}. * * Generates a schedule based on some meta data. * <ul> * <li>The schedule generation considers short stub periods at beginning or at the end.</li> * <li>Date rolling is performed using the provided businessdayCalendar.</li> * </ul> * * The reference date is used internally to represent all dates as doubles, i.e. * t = 0 corresponds to the reference date. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startDate The start date of the first period (this may/should be an unadjusted date). * @param maturityDate The end date of the last period (this may/should be an unadjusted date). * @param frequency The frequency. * @param daycountConvention The daycount convention. * @param shortPeriodConvention If short period exists, have it first or last. * @param dateRollConvention Adjustment to be applied to the all dates. * @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @param isUseEndOfMonth If ShortPeriodConvention is LAST and startDate is an end of month date, all period will be adjusted to EOM. If ShortPeriodConvention is FIRST and maturityDate is an end of month date, all period will be adjusted to EOM. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, LocalDate maturityDate, Frequency frequency, DaycountConvention daycountConvention, ShortPeriodConvention shortPeriodConvention, DateRollConvention dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays, boolean isUseEndOfMonth ) { /* * Generate periods - note: we do not use any date roll convention */ ArrayList<Period> periods = new ArrayList<Period>(); DayCountConventionInterface daycountConventionObject = null; switch (daycountConvention) { case E30_360_ISDA: daycountConventionObject = new DayCountConvention_30E_360_ISDA(); break; case E30_360: daycountConventionObject = new DayCountConvention_30E_360(); break; case U30_360: daycountConventionObject = new DayCountConvention_30U_360(); break; case ACT_360: daycountConventionObject = new DayCountConvention_ACT_360(); break; case ACT_365: daycountConventionObject = new DayCountConvention_ACT_365(); break; case ACT_ACT_ISDA: case ACT_ACT: default: daycountConventionObject = new DayCountConvention_ACT_ACT_ISDA(); break; } int periodLengthDays = 0; int periodLengthWeeks = 0; int periodLengthMonth = 0; switch(frequency) { case DAILY: periodLengthDays = 1; break; case WEEKLY: periodLengthWeeks = 1; break; case MONTHLY: periodLengthMonth = 1; break; case QUARTERLY: periodLengthMonth = 3; break; case SEMIANNUAL: periodLengthMonth = 6; break; case ANNUAL: default: periodLengthMonth = 12; break; case TENOR: periodLengthMonth = 100000; break; } // This should not happen. if(periodLengthDays == 0 && periodLengthWeeks == 0 && periodLengthMonth == 0) throw new IllegalArgumentException("Schedule generation requires positive period length."); if(shortPeriodConvention == ShortPeriodConvention.LAST) { /* * Going forward on periodStartDate, starting with startDate as periodStartDate */ LocalDate periodStartDateUnadjusted = startDate; LocalDate periodEndDateUnadjusted = startDate; LocalDate periodStartDate = businessdayCalendar.getAdjustedDate(periodStartDateUnadjusted, dateRollConvention); int periodIndex = 0; while(periodStartDateUnadjusted.isBefore(maturityDate)) { periodIndex++; // The following code only makes calculations on periodEndXxx while the periodStartXxx is only copied and used to check if we terminate // Determine period end if(isUseEndOfMonth && startDate.getDayOfMonth() == startDate.dayOfMonth().getMaximumValue()) { periodEndDateUnadjusted = startDate .plusDays(1) .plusDays(periodLengthDays*periodIndex) .plusWeeks(periodLengthWeeks*periodIndex) .plusMonths(periodLengthMonth*periodIndex) .minusDays(1); } else { periodEndDateUnadjusted = startDate .plusDays(periodLengthDays*periodIndex) .plusWeeks(periodLengthWeeks*periodIndex) .plusMonths(periodLengthMonth*periodIndex); } if(periodEndDateUnadjusted.isAfter(maturityDate)) { periodEndDateUnadjusted = maturityDate; periodStartDateUnadjusted = maturityDate; // Terminate loop (next periodEndDateUnadjusted) } // Adjust period LocalDate periodEndDate = businessdayCalendar.getAdjustedDate(periodEndDateUnadjusted, dateRollConvention); // Skip empty periods if(periodStartDate.compareTo(periodEndDate) == 0) continue; // Roll fixing date LocalDate fixingDate = businessdayCalendar.getRolledDate(periodStartDate, fixingOffsetDays); // TODO: There might be an additional calendar adjustment of the fixingDate, if the index has its own businessdayCalendar. // Roll payment date LocalDate paymentDate = businessdayCalendar.getRolledDate(periodEndDate, paymentOffsetDays); // TODO: There might be an additional calendar adjustment of the paymentDate, if the index has its own businessdayCalendar. // Create period periods.add(new Period(fixingDate, paymentDate, periodStartDate, periodEndDate)); periodStartDate = periodEndDate; periodStartDateUnadjusted = periodEndDateUnadjusted; } } else { /* * Going backward on periodEndDate, starting with maturity as periodEndDate */ LocalDate periodStartDateUnadjusted = maturityDate; LocalDate periodEndDateUnadjusted = maturityDate; LocalDate periodEndDate = businessdayCalendar.getAdjustedDate(periodEndDateUnadjusted, dateRollConvention); int periodIndex = 0; while(periodEndDateUnadjusted.isAfter(startDate)) { periodIndex++; // The following code only makes calculations on periodStartXxx while the periodEndXxx is only copied and used to check if we terminate // Determine period start if(isUseEndOfMonth && maturityDate.getDayOfMonth() == maturityDate.dayOfMonth().getMaximumValue()) { periodStartDateUnadjusted = maturityDate .plusDays(1) .minusDays(periodLengthDays*periodIndex) .minusWeeks(periodLengthWeeks*periodIndex) .minusMonths(periodLengthMonth*periodIndex) .minusDays(1); } else { periodStartDateUnadjusted = maturityDate .minusDays(periodLengthDays*periodIndex) .minusWeeks(periodLengthWeeks*periodIndex) .minusMonths(periodLengthMonth*periodIndex); } if(periodStartDateUnadjusted.isBefore(startDate)) { periodStartDateUnadjusted = startDate; periodEndDateUnadjusted = startDate; // Terminate loop (next periodEndDateUnadjusted) } // Adjust period LocalDate periodStartDate = businessdayCalendar.getAdjustedDate(periodStartDateUnadjusted, dateRollConvention); // Skip empty periods if(periodStartDate.compareTo(periodEndDate) == 0) continue; // Roll fixing date LocalDate fixingDate = businessdayCalendar.getRolledDate(periodStartDate, fixingOffsetDays); // TODO: There might be an additional calendar adjustment of the fixingDate, if the index has its own businessdayCalendar. // Roll payment date LocalDate paymentDate = businessdayCalendar.getRolledDate(periodEndDate, paymentOffsetDays); // TODO: There might be an additional calendar adjustment of the paymentDate, if the index has its own businessdayCalendar. // Create period periods.add(0, new Period(fixingDate, paymentDate, periodStartDate, periodEndDate)); periodEndDate = periodStartDate; periodEndDateUnadjusted = periodStartDateUnadjusted; } } return new Schedule(referenceDate, periods, daycountConventionObject); } /** * Schedule generation for given {referenceDate,startDate,maturityDate}. * * Generates a schedule based on some meta data. * <ul> * <li>The schedule generation considers short stub periods at beginning or at the end.</li> * <li>Date rolling is performed using the provided businessdayCalendar.</li> * </ul> * * The reference date is used internally to represent all dates as doubles, i.e. * t = 0 corresponds to the reference date. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startDate The start date of the first period (this may/should be an unadjusted date). * @param maturityDate The end date of the last period (this may/should be an unadjusted date). * @param frequency The frequency. * @param daycountConvention The daycount convention. * @param shortPeriodConvention If short period exists, have it first or last. * @param dateRollConvention Adjustment to be applied to the all dates. * @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, LocalDate maturityDate, Frequency frequency, DaycountConvention daycountConvention, ShortPeriodConvention shortPeriodConvention, DateRollConvention dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { return createScheduleFromConventions(referenceDate, startDate, maturityDate, frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays, false); } /** * Schedule generation for given {referenceDate,startDate,maturityDate}. * * Generates a schedule based on some meta data. * <ul> * <li>The schedule generation considers short stub periods at beginning or at the end.</li> * <li>Date rolling is performed using the provided businessdayCalendar.</li> * </ul> * * The reference date is used internally to represent all dates as doubles. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startDate The start date of the first period (this may/should be an unadjusted date). * @param maturityDate The end date of the last period (this may/should be an unadjusted date). * @param frequency The frequency (as String). * @param daycountConvention The daycount convention (as String). * @param shortPeriodConvention If short period exists, have it first or last (as String). * @param dateRollConvention Adjustment to be applied to the all dates (as String). * @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, LocalDate maturityDate, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { return createScheduleFromConventions( referenceDate, startDate, maturityDate, Frequency.valueOf(frequency.replace("/", "_").toUpperCase()), DaycountConvention.getEnum(daycountConvention), ShortPeriodConvention.valueOf(shortPeriodConvention.replace("/", "_").toUpperCase()), DateRollConvention.getEnum(dateRollConvention), businessdayCalendar, fixingOffsetDays, paymentOffsetDays ); } /** * Schedule generation for given {referenceDate,startDate,maturityDate}. Method using Date instead of LocalDate for backward compatibility. * * Generates a schedule based on some meta data. * <ul> * <li>The schedule generation considers short stub periods at beginning or at the end.</li> * <li>Date rolling is performed using the provided businessdayCalendar.</li> * </ul> * * The reference date is used internally to represent all dates as doubles. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startDate The start date of the first period (this may/should be an unadjusted date). * @param maturityDate The end date of the last period (this may/should be an unadjusted date). * @param frequency The frequency (as String). * @param daycountConvention The daycount convention (as String). * @param shortPeriodConvention If short period exists, have it first or last (as String). * @param dateRollConvention Adjustment to be applied to the all dates (as String). * @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( Date referenceDate, Date startDate, Date maturityDate, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { return createScheduleFromConventions(new LocalDate(referenceDate), new LocalDate(startDate), new LocalDate(maturityDate), frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays); } /** * Simple schedule generation where startDate and maturityDate are calculated based on tradeDate, spotOffsetDays, startOffsetString and maturityString. * * The schedule generation considers short periods. Date rolling is ignored. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param tradeDate Base date for the schedule generation (used to build spot date). * @param spotOffsetDays Number of business days to be added to the trade date to obtain the spot date. * @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param frequency The frequency (as String). * @param daycountConvention The daycount convention (as String). * @param shortPeriodConvention If short period exists, have it first or last (as String). * @param dateRollConvention Adjustment to be applied to the all dates (as String). * @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate tradeDate, int spotOffsetDays, String startOffsetString, String maturityString, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { LocalDate spotDate = businessdayCalendar.getRolledDate(tradeDate, spotOffsetDays); LocalDate unadjustedStartDate = businessdayCalendar.createDateFromDateAndOffsetCode(spotDate, startOffsetString); LocalDate unadjustedMaturityDate = businessdayCalendar.createDateFromDateAndOffsetCode(unadjustedStartDate, maturityString); return createScheduleFromConventions(referenceDate, unadjustedStartDate, unadjustedMaturityDate, frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays); } /** * Simple schedule generation where startDate and maturityDate are calculated based on referenceDate, spotOffsetDays, startOffsetString and maturityString. * * The schedule generation considers short periods. Date rolling is ignored. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param spotOffsetDays Number of business days to be added to the reference date to obtain the spot date. * @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param frequency The frequency (as String). * @param daycountConvention The daycount convention (as String). * @param shortPeriodConvention If short period exists, have it first or last (as String). * @param dateRollConvention Adjustment to be applied to the all dates (as String). * @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @param isUseEndOfMonth If ShortPeriodConvention is LAST and startDate is an end of month date, all period will be adjusted to EOM. If ShortPeriodConvention is FIRST and maturityDate is an end of month date, all period will be adjusted to EOM. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, int spotOffsetDays, String startOffsetString, String maturityString, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays, boolean isUseEndOfMonth ) { LocalDate spotDate = businessdayCalendar.getRolledDate(referenceDate, spotOffsetDays); LocalDate startDate = businessdayCalendar.createDateFromDateAndOffsetCode(spotDate, startOffsetString); LocalDate maturityDate = businessdayCalendar.createDateFromDateAndOffsetCode(startDate, maturityString); return createScheduleFromConventions( referenceDate, startDate, maturityDate, Frequency.valueOf(frequency.replace("/", "_").toUpperCase()), DaycountConvention.getEnum(daycountConvention), ShortPeriodConvention.valueOf(shortPeriodConvention.replace("/", "_").toUpperCase()), DateRollConvention.getEnum(dateRollConvention), businessdayCalendar, fixingOffsetDays, paymentOffsetDays, isUseEndOfMonth ); } /** * Simple schedule generation where startDate and maturityDate are calculated based on referenceDate, spotOffsetDays, startOffsetString and maturityString. * * The schedule generation considers short periods. Date rolling is ignored. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param spotOffsetDays Number of business days to be added to the trade date to obtain the spot date. * @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param frequency The frequency (as String). * @param daycountConvention The daycount convention (as String). * @param shortPeriodConvention If short period exists, have it first or last (as String). * @param dateRollConvention Adjustment to be applied to the all dates (as String). * @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, int spotOffsetDays, String startOffsetString, String maturityString, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { // tradeDate=referenceDate return createScheduleFromConventions(referenceDate, referenceDate, spotOffsetDays, startOffsetString, maturityString, frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays); } /** * Simple schedule generation where startDate and maturityDate are calculated based on referenceDate, startOffsetString and maturityString. * * The schedule generation considers short periods. Date rolling is ignored. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startOffsetString The start date as an offset from the spotDate (build from tradeDate and spotOffsetDays) entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param maturityString The end date of the last period entered as a code like 1D, 1W, 1M, 2M, 3M, 1Y, etc. * @param frequency The frequency (as String). * @param daycountConvention The daycount convention (as String). * @param shortPeriodConvention If short period exists, have it first or last (as String). * @param dateRollConvention Adjustment to be applied to the all dates (as String). * @param businessdayCalendar Business day calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, String startOffsetString, String maturityString, String frequency, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { // spotOffsetDays=0 return createScheduleFromConventions(referenceDate, 0, startOffsetString, maturityString, frequency, daycountConvention, shortPeriodConvention, dateRollConvention, businessdayCalendar, fixingOffsetDays, paymentOffsetDays); } /** * Generates a schedule based on some meta data. The schedule generation * considers short periods. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startDate The start date of the first period. * @param frequency The frequency. * @param maturity The end date of the last period. * @param daycountConvention The daycount convention. * @param shortPeriodConvention If short period exists, have it first or last. * @param dateRollConvention Adjustment to be applied to the all dates. * @param businessdayCalendar Businessday calendar (holiday calendar) to be used for date roll adjustment. * @param fixingOffsetDays Number of business days to be added to period start to get the fixing date. * @param paymentOffsetDays Number of business days to be added to period end to get the payment date. * @return The corresponding schedule * @deprecated Will be removed in version 2.3 */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, String frequency, double maturity, String daycountConvention, String shortPeriodConvention, String dateRollConvention, BusinessdayCalendarInterface businessdayCalendar, int fixingOffsetDays, int paymentOffsetDays ) { LocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity); return createScheduleFromConventions( referenceDate, startDate, maturityDate, Frequency.valueOf(frequency.toUpperCase()), DaycountConvention.getEnum(daycountConvention), ShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()), DateRollConvention.getEnum(dateRollConvention), businessdayCalendar, fixingOffsetDays, paymentOffsetDays ); } /** * Generates a schedule based on some meta data. The schedule generation * considers short periods. Date rolling is ignored. * * @param referenceDate The date which is used in the schedule to internally convert dates to doubles, i.e., the date where t=0. * @param startDate The start date of the first period. * @param frequency The frequency. * @param maturity The end date of the last period. * @param daycountConvention The daycount convention. * @param shortPeriodConvention If short period exists, have it first or last. * @return The corresponding schedule * @deprecated Will be removed in version 2.3 */ public static ScheduleInterface createScheduleFromConventions( LocalDate referenceDate, LocalDate startDate, String frequency, double maturity, String daycountConvention, String shortPeriodConvention ) { return createScheduleFromConventions( referenceDate, startDate, frequency, maturity, daycountConvention, shortPeriodConvention, "UNADJUSTED", new BusinessdayCalendarAny(), 0, 0); } /** * Create a new date by "adding" a year fraction to the start date. * The year fraction is interpreted in a 30/360 way. More specifically, * every integer unit advances by a year, each remaining fraction of 12 * advances by a month and each remaining fraction of 30 advances a day. * * The function may be used to ease the creation of maturities in spreadsheets. * * @param baseDate The start date. * @param offsetYearFrac The year fraction in 30/360 to be used for adding to the start date. * @return A date corresponding the maturity. */ private static LocalDate createDateFromDateAndOffset(LocalDate baseDate, double offsetYearFrac) { // Years LocalDate maturity = baseDate.plusYears((int)offsetYearFrac); // Months offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 12; maturity = maturity.plusMonths((int)offsetYearFrac); // Days offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 30; maturity = maturity.plusDays((int)Math.round(offsetYearFrac)); return maturity; } }
package jolie.net.ssl; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; import jolie.net.CommMessage; import jolie.net.protocols.CommProtocol; import jolie.net.protocols.SequentialCommProtocol; import jolie.runtime.Value; import jolie.runtime.VariablePath; /** * Commodity class for supporting the implementation * of SSL-based protocols through wrapping. * @author Fabrizio Montesi * 2010: complete rewrite * 2015: major fixups */ public class SSLProtocol extends SequentialCommProtocol { private static final int INITIAL_BUFFER_SIZE = 8192; private final boolean isClient; private boolean firstTime; private final CommProtocol wrappedProtocol; private SSLEngine sslEngine; private OutputStream outputStream; private InputStream inputStream; private final SSLInputStream sslInputStream = new SSLInputStream(); private final SSLOutputStream sslOutputStream = new SSLOutputStream(); private class SSLInputStream extends InputStream { private ByteBuffer clearInputBuffer = ByteBuffer.allocate( 0 ); @Override public int read() throws IOException { if ( !clearInputBuffer.hasRemaining() ) { handshake(); unwrap( this ); // EOF reached? if ( !clearInputBuffer.hasRemaining() ) { return -1; } } try { return clearInputBuffer.get(); } catch ( BufferUnderflowException e ) { return -1; } } @Override public int read( byte[] b, int off, int len ) throws IOException { if ( len == 0 ) return 0; if ( !clearInputBuffer.hasRemaining() ) { handshake(); unwrap( this ); // EOF reached? if ( !clearInputBuffer.hasRemaining() ) { return -1; } } try { clearInputBuffer.get( b, off, len ); return len; } catch ( BufferUnderflowException e ) { // okay, just return the maximum possible len = clearInputBuffer.remaining(); clearInputBuffer.get( b, off, len ); return len; } } @Override public long skip( long n ) throws IOException { if ( n <= 0 ) { return 0; } long skipped = 0; while ( skipped < n && clearInputBuffer.hasRemaining() ) { clearInputBuffer.get(); ++skipped; } return skipped; } @Override public int available() throws IOException { return clearInputBuffer.remaining(); } // close() not necessary, does nothing } private class SSLOutputStream extends OutputStream { private final ByteBuffer internalBuffer = ByteBuffer.allocate( INITIAL_BUFFER_SIZE ); private void writeCache() throws IOException { if ( internalBuffer.hasRemaining() ) { handshake(); internalBuffer.flip(); wrap( internalBuffer ); internalBuffer.clear(); } } @Override public void write( int b ) throws IOException { try { internalBuffer.put( ( byte ) b ); } catch ( BufferOverflowException e ) { // let us retry after freeing the buffer writeCache(); internalBuffer.put( ( byte ) b ); } } @Override public void write( byte[] b, int off, int len ) throws IOException { try { if ( INITIAL_BUFFER_SIZE < ( len - off ) ) { internalBuffer.put( b, off, ( INITIAL_BUFFER_SIZE - 1 ) ); // otherwise it won't work in writeCache wrt .remaining writeCache(); write( b, ( off + ( INITIAL_BUFFER_SIZE - 1 ) ), len ); } else { internalBuffer.put( b, off, ( len - off ) ); writeCache(); } } catch ( BufferOverflowException e ) { throw new IOException( e.fillInStackTrace() ); } } @Override public void flush() throws IOException { writeCache(); } // close() not necessary, does nothing } private class SSLResult { private ByteBuffer buffer; private SSLEngineResult log; public SSLResult( int capacity ) { buffer = ByteBuffer.allocate( capacity ); } } public SSLProtocol( VariablePath configurationPath, URI uri, CommProtocol wrappedProtocol, boolean isClient ) { super( configurationPath ); this.wrappedProtocol = wrappedProtocol; this.isClient = isClient; this.firstTime = true; } @Override public String name() { return wrappedProtocol.name() + "s"; } private String getSSLStringParameter( String parameterName, String defaultValue ) { if ( hasParameter( "ssl" ) ) { Value sslParams = getParameterFirstValue( "ssl" ); if ( sslParams.hasChildren( parameterName ) ) { return sslParams.getFirstChild( parameterName ).strValue(); } } return defaultValue; } private int getSSLIntegerParameter( String parameterName, int defaultValue ) { if ( hasParameter( "ssl" ) ) { Value sslParams = getParameterFirstValue( "ssl" ); if ( sslParams.hasChildren( parameterName ) ) { return sslParams.getFirstChild( parameterName ).intValue(); } } return defaultValue; } private void init() throws IOException { // Set default parameters String protocol = getSSLStringParameter( "protocol", "TLSv1" ), keyStoreFormat = getSSLStringParameter( "keyStoreFormat", "JKS" ), trustStoreFormat = getSSLStringParameter( "trustStoreFormat", "JKS" ), keyStoreFile = getSSLStringParameter( "keyStore", null ), keyStorePassword = getSSLStringParameter( "keyStorePassword", null ), trustStoreFile = getSSLStringParameter( "trustStore", System.getProperty( "java.home" ) + "/lib/security/cacerts" ), trustStorePassword = getSSLStringParameter( "trustStorePassword", null ); if ( keyStoreFile == null && isClient == false ) { throw new IOException( "Compulsory parameter needed for server mode: ssl.keyStore" ); } try { SSLContext context = SSLContext.getInstance( protocol ); KeyStore ks = KeyStore.getInstance( keyStoreFormat ); KeyStore ts = KeyStore.getInstance( trustStoreFormat ); char[] passphrase; if ( keyStorePassword != null ) { passphrase = keyStorePassword.toCharArray(); } else { passphrase = null; } if ( keyStoreFile != null ) { ks.load( new FileInputStream( keyStoreFile ), passphrase ); } else { ks.load( null, null ); } KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" ); kmf.init( ks, passphrase ); if ( trustStorePassword != null ) { passphrase = trustStorePassword.toCharArray(); } else { passphrase = null; } ts.load( new FileInputStream( trustStoreFile ), passphrase ); TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" ); tmf.init( ts ); context.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null ); sslEngine = context.createSSLEngine(); sslEngine.setEnabledProtocols( new String[]{ protocol } ); sslEngine.setUseClientMode( isClient ); if ( isClient == false ) { if ( getSSLIntegerParameter( "wantClientAuth", 1 ) > 0 ) { sslEngine.setWantClientAuth( true ); } else { sslEngine.setWantClientAuth( false ); } } } catch ( NoSuchAlgorithmException e ) { throw new IOException( e ); } catch ( KeyManagementException e ) { throw new IOException( e ); } catch ( KeyStoreException e ) { throw new IOException( e ); } catch ( UnrecoverableKeyException e ) { throw new IOException( e ); } catch ( CertificateException e ) { throw new IOException( e ); } } private void handshake() throws IOException, SSLException { if ( firstTime ) { init(); sslEngine.beginHandshake(); firstTime = false; } boolean keepRun = true; Runnable runnable; while ( keepRun && sslEngine.getHandshakeStatus() != HandshakeStatus.FINISHED && sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING ) { switch ( sslEngine.getHandshakeStatus() ) { case NEED_TASK: while ( ( runnable = sslEngine.getDelegatedTask() ) != null ) { runnable.run(); } break; case NEED_WRAP: wrap( ByteBuffer.allocate( INITIAL_BUFFER_SIZE ) ); break; case NEED_UNWRAP: keepRun = unwrap( null ); if ( sslEngine.isInboundDone() && sslEngine.isOutboundDone() ) { keepRun = false; } break; } } } private boolean unwrap( SSLInputStream sslInputStream ) throws IOException { ByteBuffer cryptBuffer = ByteBuffer.allocate( 0 ); final SSLResult result = new SSLResult( INITIAL_BUFFER_SIZE ); boolean keepRun = true; boolean returnResult = true; while ( keepRun ) { result.log = sslEngine.unwrap( cryptBuffer, result.buffer ); switch ( result.log.getStatus() ) { case BUFFER_OVERFLOW: final int appSize = sslEngine.getSession().getApplicationBufferSize(); // Resize "result.buffer" if needed if ( appSize > result.buffer.capacity() ) { final ByteBuffer b = ByteBuffer.allocate( appSize ); result.buffer.flip(); b.put( result.buffer ); result.buffer = b; } else { result.buffer.compact(); } break; case BUFFER_UNDERFLOW: final int netSize = sslEngine.getSession().getPacketBufferSize(); // Resize "cryptBuffer" if needed if ( netSize > cryptBuffer.capacity() ) { final ByteBuffer b = ByteBuffer.allocate( netSize ); cryptBuffer.flip(); b.put( cryptBuffer ); cryptBuffer = b; } else { cryptBuffer.compact(); } int currByte = inputStream.read(); if ( currByte >= 0 ) { cryptBuffer.put( ( byte ) currByte ); cryptBuffer.flip(); } else { // input stream EOF reached, we may not continue returnResult = false; keepRun = false; } break; case CLOSED: returnResult = false; case OK: if ( result.log.bytesConsumed() > 0 && sslInputStream != null ) { sslInputStream.clearInputBuffer = result.buffer; sslInputStream.clearInputBuffer.flip(); } keepRun = false; break; } } return returnResult; } private void wrap( ByteBuffer source ) throws IOException { final SSLResult result = new SSLResult( source.capacity() ); result.log = sslEngine.wrap( source, result.buffer ); while ( result.log.getStatus() == Status.BUFFER_OVERFLOW ) { final int appSize = sslEngine.getSession().getApplicationBufferSize(); // Resize "result.buffer" if needed // if ( appSize > result.buffer.capacity() ) { // final ByteBuffer b = ByteBuffer.allocate( appSize ); // result.buffer.flip(); // b.put( result.buffer ); // result.buffer = b; // } else { // result.buffer.compact(); // From the docs: "The size of the outbound application data buffer generally does not matter." // For the time being we can double it and later implement some smarter optimisations. result.buffer = ByteBuffer.allocate( result.buffer.capacity() * 2 ); result.log = sslEngine.wrap( source, result.buffer ); } // must be Status.OK or Status.CLOSED here if ( result.log.bytesProduced() > 0 ) { final WritableByteChannel outputChannel = Channels.newChannel( outputStream ); result.buffer.flip(); while ( result.buffer.hasRemaining() ) outputChannel.write( result.buffer ); outputStream.flush(); } } @Override public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { outputStream = ostream; inputStream = istream; if ( firstTime ) { wrappedProtocol.setChannel( this.channel() ); } wrappedProtocol.send( sslOutputStream, message, sslInputStream ); sslOutputStream.flush(); } @Override public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { outputStream = ostream; inputStream = istream; if ( firstTime ) { wrappedProtocol.setChannel( this.channel() ); } CommMessage message = wrappedProtocol.recv( sslInputStream, sslOutputStream ); sslOutputStream.flush(); return message; } }
package org.smoothbuild.io.fs.base; import static com.google.common.truth.Truth.assertThat; import static java.text.MessageFormat.format; import static org.quackery.Case.newCase; import static org.quackery.Suite.suite; import static org.quackery.report.AssertException.assertEquals; import static org.quackery.report.AssertException.assertTrue; import static org.quackery.report.AssertException.fail; import static org.smoothbuild.io.fs.base.Path.path; import static org.smoothbuild.testing.common.AssertCall.assertCall; import static org.smoothbuild.util.Lists.list; import static org.smoothbuild.util.Lists.map; import java.nio.file.Paths; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.quackery.Case; import org.quackery.Quackery; import org.quackery.Suite; import org.quackery.junit.QuackeryRunner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.testing.EqualsTester; @RunWith(QuackeryRunner.class) public class PathTest { @Quackery public static Suite path_value_is_validated() { return suite("path value is validated") .add(suite("path can be created for valid name") .addAll(map(listOfCorrectPaths(), PathTest::pathCanBeCreatedForValidName))) .add(suite("cannot create path with invalid value") .addAll(map(listOfInvalidPaths(), PathTest::cannotCreatePathWithInvalidValue))); } private static Case pathCanBeCreatedForValidName(String path) { return newCase(format("path [{0}]", path), () -> path(path)); } private static Case cannotCreatePathWithInvalidValue(String path) { return newCase(format("path [{0}]", path), () -> { try { path(path); fail(); } catch (IllegalPathException e) { } }); } @Test public void empty_string_path_is_root() { assertThat(path("").isRoot()) .isTrue(); } @Test public void simple_path_is_not_root() { assertThat(path("file.txt").isRoot()) .isFalse(); } @Quackery public static Suite implements_value() { return suite("implements value") .add(testValue("", "")) .add(testValue("abc", "abc")) .add(testValue("abc/def", "abc/def")) .add(testValue("abc/def/ghi", "abc/def/ghi")); } private static Case testValue(String path, String value) { return newCase(format("path [{0}] has value [{1}]", path, value), () -> assertEquals(path(path).value(), value)); } @Quackery public static Suite implements_toJPath() { return suite("implements toJPath") .add(testToJPath("", Paths.get("."))) .add(testToJPath("abc", Paths.get("abc"))) .add(testToJPath("abc/def", Paths.get("abc/def"))) .add(testToJPath("abc/def/ghi", Paths.get("abc/def/ghi"))); } private static Case testToJPath(String path, java.nio.file.Path jPath) { return newCase(format("path [{0}] converted to JPath equals [{1}]", path, jPath), () -> assertEquals(path(path).toJPath(), jPath)); } @Test public void parent_of_root_dir_throws_exception() { assertCall(() -> Path.root().parent()) .throwsException(IllegalArgumentException.class); } @Quackery public static Suite implements_parent() { return suite("implements parent") .add(testParent("abc", "")) .add(testParent("abc/def", "abc")) .add(testParent("abc/def/ghi", "abc/def")) .add(testParent(" ", "")); } private static Case testParent(String path, String parent) { return newCase(format("parent of [{0}] is [{1}]", path, parent), () -> assertEquals(path(path).parent(), path(parent))); } @Quackery public static Suite implements_appending() { return suite("implements appending") .add(testAppending("", "", "")) .add(testAppending("abc", "", "abc")) .add(testAppending("abc/def", "", "abc/def")) .add(testAppending("abc/def/ghi", "", "abc/def/ghi")) .add(testAppending("", "abc", "abc")) .add(testAppending("", "abc/def", "abc/def")) .add(testAppending("", "abc/def/ghi", "abc/def/ghi")) .add(testAppending("abc", "xyz", "abc/xyz")) .add(testAppending("abc", "xyz/uvw", "abc/xyz/uvw")) .add(testAppending("abc", "xyz/uvw/rst", "abc/xyz/uvw/rst")) .add(testAppending("abc/def", "xyz", "abc/def/xyz")) .add(testAppending("abc/def", "xyz/uvw", "abc/def/xyz/uvw")) .add(testAppending("abc/def", "xyz/uvw/rst", "abc/def/xyz/uvw/rst")) .add(testAppending("abc/def/ghi", "xyz", "abc/def/ghi/xyz")) .add(testAppending("abc/def/ghi", "xyz/uvw", "abc/def/ghi/xyz/uvw")) .add(testAppending("abc/def/ghi", "xyz/uvw/rst", "abc/def/ghi/xyz/uvw/rst")) .add(testAppending(" ", " ", " / ")) .add(testAppending(" ", " / ", " / / ")) .add(testAppending(" / ", " ", " / / ")) .add(testAppending(" / ", " / ", " / / / ")); } private static Case testAppending(String first, String second, String expected) { return newCase(format("appending [{0}] to [{1}] returns [{2}]", first, second, expected), () -> { String actual = path(first).append(path(second)).value(); assertEquals(actual, expected); }); } @Quackery public static Suite implements_parts() { return suite("implements parts") .add(testParts("", list())) .add(testParts("abc", list("abc"))) .add(testParts("abc/def", list("abc", "def"))) .add(testParts("abc/def/ghi", list("abc", "def", "ghi"))) .add(testParts(" ", list(" "))) .add(testParts(" / ", list(" ", " "))) .add(testParts(" / / ", list(" ", " ", " "))); } private static Case testParts(String path, List<String> parts) { return newCase(format("[{0}] has parts: {1}", path, parts), () -> { List<String> actualParts = map(path(path).parts(), Path::value); assertEquals(actualParts, parts); }); } @Test public void last_part_of_root_dir_throws_exception() { assertCall(() -> Path.root().lastPart()) .throwsException(IllegalArgumentException.class); } @Quackery public static Suite implements_last_part() { return suite("implements lastPart") .add(testLastPart(" ", " ")) .add(testLastPart(" / ", " ")) .add(testLastPart("abc", "abc")) .add(testLastPart("abc/def", "def")) .add(testLastPart("abc/def/ghi", "ghi")); } private static Case testLastPart(String path, String lastPart) { return newCase(format("last part of [{0}] is [{1}]", path, lastPart), () -> assertEquals(path(path).lastPart(), path(lastPart))); } @Test public void first_part_of_root_dir_throws_exception() { assertCall(() -> Path.root().firstPart()) .throwsException(IllegalArgumentException.class); } @Quackery public static Suite implements_first_part() { return suite("implements firstPart") .add(testFirstPart(" ", " ")) .add(testFirstPart(" / ", " ")) .add(testFirstPart("abc", "abc")) .add(testFirstPart("abc/def", "abc")) .add(testFirstPart("abc/def/ghi", "abc")); } private static Case testFirstPart(String path, String firstPart) { return newCase(format("first part of [{0}] is [{1}]", path, firstPart), () -> assertEquals(path(path).firstPart(), path(firstPart))); } @Quackery public static Suite implements_start_with() { return suite("implements startsWith") .add(testStartsWith(Path.root(), Path.root())) .add(testStartsWith(Path.path("abc"), Path.root())) .add(testStartsWith(Path.path("abc/def"), Path.root())) .add(testStartsWith(Path.path("abc/def/ghi"), Path.root())) .add(testStartsWith(Path.path("abc/def/ghi"), Path.path("abc"))) .add(testStartsWith(Path.path("abc/def/ghi"), Path.path("abc/def"))) .add(testStartsWith(Path.path("abc/def/ghi"), Path.path("abc/def/ghi"))) .add(testNotStartsWith(Path.path("abc/def/ghi"), Path.path("ab"))) .add(testNotStartsWith(Path.path("abc/def/ghi"), Path.path("abc/d"))) .add(testNotStartsWith(Path.path("abc/def/ghi"), Path.path("def"))) .add(testNotStartsWith(Path.path("abc/def/ghi"), Path.path("ghi"))) .add(testNotStartsWith(Path.root(), Path.path("abc"))); } private static Case testStartsWith(Path path, Path head) { return newCase(format("{0} starts with {1}", path, head), () -> assertTrue(path.startsWith(head))); } private static Case testNotStartsWith(Path path, Path notHead) { return newCase(format("{0} not starts with {1}", path, notHead), () -> assertTrue(!path.startsWith(notHead))); } @Test public void test_equals_and_hash_code() { EqualsTester tester = new EqualsTester(); tester.addEqualityGroup(path("equal/path"), path("equal/path")); for (Path path : listOfCorrectNonEqualPaths()) { tester.addEqualityGroup(path); } tester.testEquals(); } @Test public void test_to_string() { assertThat(path("abc/def").toString()) .isEqualTo("'abc/def'"); } public static List<String> listOfCorrectPaths() { Builder<String> builder = ImmutableList.builder(); builder.add(""); builder.add("abc"); builder.add("abc/def"); builder.add("abc/def/ghi"); builder.add("abc/def/ghi/ijk"); // These paths look really strange but Linux allows creating them. // I cannot see any good reason for forbidding them. builder.add("..."); builder.add(".../abc"); builder.add("abc/..."); builder.add("abc/.../def"); return builder.build(); } public static ImmutableList<String> listOfInvalidPaths() { Builder<String> builder = ImmutableList.builder(); builder.add("/"); builder.add("."); builder.add("./"); builder.add("./."); builder.add("././"); builder.add("abc/"); builder.add("abc/def/"); builder.add("abc/def/ghi/"); builder.add("./abc"); builder.add("./abc/def"); builder.add("./abc/def/ghi"); builder.add(".."); builder.add("../"); builder.add("./../"); builder.add("../abc"); builder.add("abc/.."); builder.add("abc/../def"); builder.add("../.."); builder.add(" builder.add(" builder.add("/abc"); builder.add("//abc"); builder.add("///abc"); builder.add("abc builder.add("abc builder.add("abc//def"); builder.add("abc///def"); return builder.build(); } private static List<Path> listOfCorrectNonEqualPaths() { Builder<Path> builder = ImmutableList.builder(); builder.add(path("")); builder.add(path("abc")); builder.add(path("abc/def")); builder.add(path("abc/def/ghi")); builder.add(path("abc/def/ghi/ijk")); // These paths look really strange but Linux allows creating them. // I cannot see any good reason for forbidding them. builder.add(path("...")); builder.add(path(".../abc")); builder.add(path("abc/...")); builder.add(path("abc/.../def")); return builder.build(); } }
package ch.elexis.data; import java.lang.reflect.Method; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.status.ElexisStatus; import ch.elexis.core.exceptions.PersistenceException; import ch.rgw.tools.ExHandler; import ch.rgw.tools.IFilter; import ch.rgw.tools.JdbcLink; import ch.rgw.tools.JdbcLink.Stm; import ch.rgw.tools.Log; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; /** * Query manages all database queries of PersistentObjects and derived classes * * Die Query-Klasse erledigt alle Datenbankabfragen auf PersistentObjects und davon abgeleitete * Klassen. * * @author Gerry */ public class Query<T> { public static final String EQUALS = "="; public static final String GREATER = ">"; public static final String LESS = "<"; public static final String LESS_OR_EQUAL = "<="; public static final String GREATER_OR_EQUAL = ">="; public static final String NOT_EQUAL = "<>"; public static final String LIKE = "LIKE"; // private Query(){/* leer */} private StringBuilder sql; private static Log log = Log.get(Query.class.getName()); // private boolean restrictions; private PersistentObject template; private Method load; private final static String SELECT_ID_FROM = "SELECT ID FROM "; private String link = " WHERE "; private String lastQuery = ""; private final LinkedList<IFilter> postQueryFilters = new LinkedList<IFilter>(); private String ordering; private final ArrayList<String> exttables = new ArrayList<String>(2); /** * Konstruktor * * @param cl * Die Klasse, auf die die Abfrage angewendet werden soll (z.B. Patient.class) */ public Query(final Class<? extends PersistentObject> cl){ try { template = CoreHub.poFactory.createTemplate(cl); // template=cl.newInstance(); load = cl.getMethod("load", new Class[] { String.class }); clear(); } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Query: Konnte Methode load auf " + cl.getName() + " nicht auflösen", ex, ElexisStatus.LOG_ERRORS); throw new PersistenceException(status); } } public Query(final Class<? extends PersistentObject> cl, final String field, final String value){ try { template = CoreHub.poFactory.createTemplate(cl); // template=cl.newInstance(); load = cl.getMethod("load", new Class[] { String.class }); clear(); add(field, "=", value); } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Query: Konnte Methode load auf " + cl.getName() + " nicht auflösen", ex, ElexisStatus.LOG_ERRORS); throw new PersistenceException(status); } } /** * This method allows to set a custom sql query string; E.g. The original Query does not support * the usage of INNER JOINS, to use them nevertheless we need to provide a direct method to set * query strings * * @param cl * the persistent object to set the query for * @param string * the SQL query string * @author Marco Descher */ public Query(Class<? extends PersistentObject> cl, final String string){ try { template = CoreHub.poFactory.createTemplate(cl); // template=cl.newInstance(); load = cl.getMethod("load", new Class[] { String.class }); sql = new StringBuilder(500); sql.append(string); ordering = null; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Query: Konnte Methode load auf " + cl.getName() + " nicht auflösen", ex, ElexisStatus.LOG_ERRORS); throw new PersistenceException(status); } } /** * Delete query to e.g. re-use the query for a new execution run * * @see #clear(boolean) */ public void clear(){ clear(false); } /** * Delete query to e.g. re-use the query for a new execution run * * @param includeDeletedEntriesInQuery * to include deleted elements in your query initialize your query with * {@link #clear(boolean)} == <code>true</code>, the default as executed by * {@link #clear()} is <code>false</code> */ public void clear(boolean includeDeletedEntriesInQuery){ sql = new StringBuilder(500); String table = template.getTableName(); sql.append(SELECT_ID_FROM).append(table); String cns = template.getConstraint(); if (cns.equals("")) { if (includeDeletedEntriesInQuery) { link = " WHERE "; } else { sql.append(" WHERE deleted=").append(JdbcLink.wrap("0")); link = " AND "; } } else { sql.append(" WHERE ").append(cns); if (!includeDeletedEntriesInQuery) { sql.append(" AND deleted=").append(JdbcLink.wrap("0")); } link = " AND "; } ordering = null; exttables.clear(); } private void append(final String... s){ sql.append(link); for (String a : s) { sql.append(" ").append(a); } if (link.equals(" WHERE ") || link.equals("")) { link = " AND "; } } public void startGroup(){ append("("); link = ""; } /** * Gruppierung ende */ public void endGroup(){ sql.append(")"); } public void insertTrue(){ append("1=1"); } public void insertFalse(){ append("1=0"); } public void and(){ if (link.equals(" OR ")) { link = " AND "; } } public void or(){ link = " OR "; } public boolean add(final String feld, String operator, String wert, final boolean toLower){ String mapped; mapped = template.map(feld); // treat date parameter separately // TODO This works only for european-style dates (dd.mm.yyyy) if (mapped.startsWith("S:D:")) { mapped = mapped.substring(4); // if a date should be matched partially if (operator.equalsIgnoreCase("LIKE") && !wert.matches("[0-9]{8,8}")) { StringBuilder sb = null; wert = wert.replaceAll("%", ""); final String filler = "%%%%%%%%"; // are we looking for the year? if (wert.matches("[0-9]{3,}")) { sb = new StringBuilder(wert); sb.append(filler); wert = sb.substring(0, 8); } else { // replace single digits as in 1.2.1932 with double digits // as in 01.02.1932 wert = wert.replaceAll("[^0-9]([0-9])\\.", "0$1."); // remove dots sb = new StringBuilder(wert.replaceAll("\\.", "")); // String must consist of 8 or more digits (ddmmYYYY) sb.append(filler); // convert to YYYYmmdd format wert = sb.substring(4, 8) + sb.substring(2, 4) + sb.substring(0, 2); } } else { TimeTool tm = new TimeTool(); if (tm.set(wert) == true) { wert = tm.toString(TimeTool.DATE_COMPACT); } } } else if (mapped.startsWith("EXT:")) { int ix = mapped.indexOf(':', 5); if (ix == -1) { log.log("Ungültiges Feld " + feld, Log.ERRORS); return false; } String table = mapped.substring(4, ix); mapped = table + "." + mapped.substring(ix + 1); String firsttable = template.getTableName() + "."; if (!exttables.contains(table)) { exttables.add(table); sql.insert(SELECT_ID_FROM.length(), table + ","); ix = sql.indexOf("deleted="); if (ix != -1) { sql.insert(ix, firsttable); } } if (exttables.size() == 1) { sql.insert(7, firsttable); // Select ID from // firsttable,secondtable } append(table + ".ID=" + firsttable + "ID"); // append(mapped,operator,wert); } else if (mapped.matches(".*:.*")) { log.log("Ungültiges Feld " + feld, Log.ERRORS); return false; } if (wert == null) { if (operator.equalsIgnoreCase("is") || operator.equals("=")) { // let's be a bit fault tolerant operator = ""; } append(mapped, "is", operator, "null"); } else { wert = PersistentObject.getConnection().wrapFlavored(wert); // wert = JdbcLink.wrap(wert); if (toLower) { mapped = "lower(" + mapped + ")"; wert = "lower(" + wert + ")"; } append(mapped, operator, wert); } return true; } public boolean add(final String feld, final String operator, final String wert){ return add(feld, operator, wert, false); } public void addToken(final String token){ append(token); } public String findSingle(final String f, final String op, final String v){ clear(); sql.append(link).append(template.map(f)).append(op).append(JdbcLink.wrap(v)); String ret = PersistentObject.getConnection().queryString(sql.toString()); return ret; } public List<T> queryFields(final String[] fields, final String[] values, final boolean exact){ clear(); String op = "="; if (exact == false) { op = " LIKE "; } and(); for (int i = 0; i < fields.length; i++) { if (StringTool.isNothing(values[i])) { continue; } add(fields[i], op, values[i]); } return execute(); } public PreparedStatement getPreparedStatement(final PreparedStatement previous){ try { if (previous != null) { previous.close(); } PreparedStatement ps = PersistentObject.getConnection().prepareStatement(sql.toString()); return ps; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler beim PreparedStatement " + ex.getMessage(), ex, ElexisStatus.LOG_ERRORS); throw new PersistenceException(status); } } public ArrayList<String> execute(final PreparedStatement ps, final String[] values){ try { for (int i = 0; i < values.length; i++) { ps.setString(i + 1, values[i]); } if (ps.execute() == true) { ArrayList<String> ret = new ArrayList<String>(); ResultSet res = ps.getResultSet(); while (res.next()) { ret.add(res.getString(1)); } return ret; } } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler beim Ausführen von " + sql.toString(), ex, ElexisStatus.LOG_ERRORS); throw new PersistenceException(status); } return null; } public void orderBy(final boolean reverse, final String... n1){ if (n1 != null && n1.length > 0) { StringBuilder sb = new StringBuilder(); sb.append(" ORDER BY "); for (String s : n1) { String mapped = template.map(s); if (mapped.matches("[A-Z]{2,}:.+")) { log.log("Ungültiges Feld " + s, Log.ERRORS); return; } if (mapped.startsWith("S:D:")) { mapped = mapped.substring(4); } sb.append(mapped); if (reverse == true) { sb.append(" DESC"); } sb.append(","); } sb.delete(sb.length() - 1, 10000); ordering = sb.toString(); } } public List<T> execute(){ if (ordering != null) { sql.append(ordering); } lastQuery = sql.toString(); // log.log("Executing query: "+lastQuery,Log.DEBUGMSG); LinkedList<T> ret = new LinkedList<T>(); return (List<T>) queryExpression(lastQuery, ret); } public Collection<T> execute(final Collection<T> collection){ if (ordering != null) { sql.append(ordering); } lastQuery = sql.toString(); return queryExpression(lastQuery, collection); } @SuppressWarnings("unchecked") public Collection<T> queryExpression(final String expr, Collection<T> ret){ // LinkedList<T> ret=new LinkedList<T>(); if (ret == null) { ret = new LinkedList<T>(); } Stm stm = null; try { stm = PersistentObject.getConnection().getStatement(); ResultSet res = stm.query(expr); log.log("Executed " + expr, Log.DEBUGMSG); while ((res != null) && (res.next() == true)) { String id = res.getString(1); T o = (T) load.invoke(null, new Object[] { id }); if (o == null) { continue; } boolean bAdd = true; for (IFilter fi : postQueryFilters) { if (fi.select(o) == false) { bAdd = false; break; } } if (bAdd == true) { ret.add(o); } } res.close(); return ret; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler bei Datenbankabfrage " + ex.getMessage(), ex, ElexisStatus.LOG_ERRORS); log.log("Fehler bei Datenbankabfrage: " + ex.getMessage(), Log.WARNINGS); throw new PersistenceException(status); } finally { PersistentObject.getConnection().releaseStatement(stm); } } /* * public PersistentObject createFromID(String id){ try{ * return(PersistentObject)load.invoke(null,new Object[]{id}); }catch(Exception ex){ * ExHandler.handle(ex); log.log("Konnte Objekt nicht erzeugen",Log.ERRORS); return null; } } */ public int size(){ try { Stm stm = PersistentObject.getConnection().getStatement(); String res = stm.queryString("SELECT COUNT(*) FROM " + template.getTableName()); PersistentObject.getConnection().releaseStatement(stm); return Integer.parseInt(res); } catch (Exception ex) { ExHandler.handle(ex); return 10000; } } public String getLastQuery(){ return lastQuery; } public String getActualQuery(){ return sql.toString(); } public void addPostQueryFilter(final IFilter f){ postQueryFilters.add(f); } public void removePostQueryFilter(final IFilter f){ postQueryFilters.remove(f); } }
import capsule.AetherDependencyManager; import capsule.DependencyManager; import capsule.PomReader; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Capsule implements Runnable, FileVisitor<Path> { /* * This class contains several strange hacks to avoid creating more classes. * We'd like this file to compile to a single .class file. * * Also, the code here is not meant to be the most efficient, but methods should be as independent and stateless as possible. * Other than those few, methods called in the constructor, all others are can be called in any order, and don't rely on any state. * * We do a lot of data transformations that would have really benefitted from Java 8's lambdas and streams, * but we want Capsule to support Java 7. */ private static final String VERSION = "0.6.0"; private static final String PROP_RESET = "capsule.reset"; private static final String PROP_VERSION = "capsule.version"; private static final String PROP_LOG = "capsule.log"; private static final String PROP_TREE = "capsule.tree"; private static final String PROP_APP_ID = "capsule.app.id"; private static final String PROP_PRINT_JRES = "capsule.jvms"; private static final String PROP_CAPSULE_JAVA_HOME = "capsule.java.home"; private static final String PROP_MODE = "capsule.mode"; private static final String PROP_USE_LOCAL_REPO = "capsule.local"; private static final String PROP_OFFLINE = "capsule.offline"; private static final String PROP_RESOLVE = "capsule.resolve"; private static final String PROP_JAVA_VERSION = "java.version"; private static final String PROP_JAVA_HOME = "java.home"; private static final String PROP_OS_NAME = "os.name"; private static final String PROP_USER_HOME = "user.home"; private static final String PROP_JAVA_LIBRARY_PATH = "java.library.path"; private static final String PROP_FILE_SEPARATOR = "file.separator"; private static final String PROP_PATH_SEPARATOR = "path.separator"; private static final String PROP_JAVA_SECURITY_POLICY = "java.security.policy"; private static final String PROP_JAVA_SECURITY_MANAGER = "java.security.manager"; private static final String ENV_CAPSULE_REPOS = "CAPSULE_REPOS"; private static final String ATTR_APP_NAME = "Application-Name"; private static final String ATTR_APP_VERSION = "Application-Version"; private static final String ATTR_APP_CLASS = "Application-Class"; private static final String ATTR_APP_ARTIFACT = "Application"; private static final String ATTR_UNIX_SCRIPT = "Unix-Script"; private static final String ATTR_WINDOWS_SCRIPT = "Windows-Script"; private static final String ATTR_EXTRACT = "Extract-Capsule"; private static final String ATTR_MIN_JAVA_VERSION = "Min-Java-Version"; private static final String ATTR_JAVA_VERSION = "Java-Version"; private static final String ATTR_MIN_UPDATE_VERSION = "Min-Update-Version"; private static final String ATTR_JDK_REQUIRED = "JDK-Required"; private static final String ATTR_JVM_ARGS = "JVM-Args"; private static final String ATTR_ARGS = "Args"; private static final String ATTR_ENV = "Environment-Variables"; private static final String ATTR_SYSTEM_PROPERTIES = "System-Properties"; private static final String ATTR_APP_CLASS_PATH = "App-Class-Path"; private static final String ATTR_CAPSULE_IN_CLASS_PATH = "Capsule-In-Class-Path"; private static final String ATTR_BOOT_CLASS_PATH = "Boot-Class-Path"; private static final String ATTR_BOOT_CLASS_PATH_A = "Boot-Class-Path-A"; private static final String ATTR_BOOT_CLASS_PATH_P = "Boot-Class-Path-P"; private static final String ATTR_LIBRARY_PATH_A = "Library-Path-A"; private static final String ATTR_LIBRARY_PATH_P = "Library-Path-P"; private static final String ATTR_SECURITY_MANAGER = "Security-Manager"; private static final String ATTR_SECURITY_POLICY = "Security-Policy"; private static final String ATTR_SECURITY_POLICY_A = "Security-Policy-A"; private static final String ATTR_JAVA_AGENTS = "Java-Agents"; private static final String ATTR_REPOSITORIES = "Repositories"; private static final String ATTR_DEPENDENCIES = "Dependencies"; private static final String ATTR_NATIVE_DEPENDENCIES_LINUX = "Native-Dependencies-Linux"; private static final String ATTR_NATIVE_DEPENDENCIES_WIN = "Native-Dependencies-Win"; private static final String ATTR_NATIVE_DEPENDENCIES_MAC = "Native-Dependencies-Mac"; private static final String ATTR_IMPLEMENTATION_VERSION = "Implementation-Version"; // outgoing private static final String VAR_CAPSULE_DIR = "CAPSULE_DIR"; private static final String VAR_CAPSULE_JAR = "CAPSULE_JAR"; private static final String VAR_JAVA_HOME = "JAVA_HOME"; private static final String ENV_CACHE_DIR = "CAPSULE_CACHE_DIR"; private static final String ENV_CACHE_NAME = "CAPSULE_CACHE_NAME"; private static final String PROP_CAPSULE_JAR = "capsule.jar"; private static final String PROP_CAPSULE_DIR = "capsule.dir"; private static final String PROP_CAPSULE_APP = "capsule.app"; // misc private static final String CACHE_DEFAULT_NAME = "capsule"; private static final String DEPS_CACHE_NAME = "deps"; private static final String APP_CACHE_NAME = "apps"; private static final String POM_FILE = "pom.xml"; private static final String DOT = "\\."; private static final String CUSTOM_CAPSULE_CLASS_NAME = "CustomCapsule"; private static final String FILE_SEPARATOR = System.getProperty(PROP_FILE_SEPARATOR); private static final String PATH_SEPARATOR = System.getProperty(PROP_PATH_SEPARATOR); private static final Path DEFAULT_LOCAL_MAVEN = Paths.get(System.getProperty(PROP_USER_HOME), ".m2", "repository"); private static final boolean debug = "debug".equals(System.getProperty(PROP_LOG, "quiet")); private static final boolean verbose = debug || "verbose".equals(System.getProperty(PROP_LOG, "quiet")); private final Path cacheDir; private final JarFile jar; // null only in tests private final byte[] jarBuffer; // non-null only in tests private final Path jarFile; // never null private final Manifest manifest; // never null private final String javaHome; private final String appId; // null iff isEmptyCapsule() private final Path appCache; // non-null iff capsule is extracted private final boolean cacheUpToDate; private final String mode; private final Object pom; // non-null iff jar has pom AND manifest doesn't have ATTR_DEPENDENCIES private final Object dependencyManager; // non-null iff needsDependencyManager is true private Process child; /** * Launches the application * * @param args the program's command-line arguments */ @SuppressWarnings({"BroadCatchBlock", "CallToPrintStackTrace"}) public static final void main(String[] args) { try { final Capsule capsule = newCapsule(getJarFile(), args); if (anyPropertyDefined(PROP_VERSION, PROP_PRINT_JRES, PROP_TREE, PROP_RESOLVE)) { if (anyPropertyDefined(PROP_VERSION)) capsule.printVersion(); if (anyPropertyDefined(PROP_PRINT_JRES)) capsule.printJVMs(); if (anyPropertyDefined(PROP_TREE)) capsule.printDependencyTree(args); if (anyPropertyDefined(PROP_RESOLVE)) capsule.resolve(args); return; } final Process p = capsule.launch(ManagementFactory.getRuntimeMXBean().getInputArguments(), args); if (p != null) System.exit(p.waitFor()); } catch (Throwable t) { System.err.println("CAPSULE EXCEPTION: " + t.getMessage() + (!verbose ? " (for stack trace, run with -D" + PROP_LOG + "=verbose)" : "")); if (verbose) t.printStackTrace(System.err); System.exit(1); } } private static Capsule newCapsule(Path jarFile, String[] args) { try { final Class<?> clazz = Class.forName(CUSTOM_CAPSULE_CLASS_NAME); try { Constructor<?> ctor = clazz.getConstructor(Path.class, String[].class); ctor.setAccessible(true); return (Capsule) ctor.newInstance(jarFile, args); } catch (Exception e) { throw new RuntimeException("Could not launch custom capsule.", e); } } catch (ClassNotFoundException e) { return new Capsule(jarFile, args); } } protected Capsule(Path jarFile, String[] args) { this.jarFile = jarFile; try { this.jar = new JarFile(jarFile.toFile()); this.jarBuffer = null; this.manifest = jar.getManifest(); if (manifest == null) throw new RuntimeException("JAR file " + jarFile + " does not have a manifest"); } catch (IOException e) { throw new RuntimeException("Could not read JAR file " + jarFile + " manifest"); } this.cacheDir = initCacheDir(getCacheDir()); this.javaHome = getJavaHome(); this.mode = System.getProperty(PROP_MODE); this.pom = (!hasAttribute(ATTR_DEPENDENCIES) && hasPom()) ? createPomReader() : null; this.dependencyManager = needsDependencyManager() ? createDependencyManager(getRepositories()) : null; this.appId = getAppId(args); this.appCache = needsAppCache() ? getAppCacheDir() : null; this.cacheUpToDate = appCache != null ? isUpToDate() : false; } @Deprecated // Used only in tests Capsule(Path jarFile, String[] args, Path cacheDir, byte[] jarBuffer, Object dependencyManager) { this.jarFile = jarFile; this.jar = null; this.jarBuffer = jarBuffer; this.manifest = getJarInputStream().getManifest(); if (manifest == null) throw new RuntimeException("JAR file " + jarFile + " does not have a manifest"); this.cacheDir = initCacheDir(cacheDir); this.javaHome = getJavaHome(); this.mode = System.getProperty(PROP_MODE); this.pom = (!hasAttribute(ATTR_DEPENDENCIES) && hasPom()) ? createPomReader() : null; this.dependencyManager = dependencyManager; this.appId = getAppId(args); this.appCache = needsAppCache() ? getAppCacheDir() : null; this.cacheUpToDate = appCache != null ? isUpToDate() : false; } protected final boolean isTest() { // so far only getEntry and extractJar run different code for tests return jar == null; } private JarInputStream getJarInputStream() { try { return new JarInputStream(new ByteArrayInputStream(jarBuffer)); } catch (IOException e) { throw new AssertionError(e); } } private boolean needsDependencyManager() { return hasAttribute(ATTR_APP_ARTIFACT) || isEmptyCapsule() || pom != null || getDependencies() != null || getNativeDependencies() != null; } private Process launch(List<String> cmdLine, String[] args) throws IOException, InterruptedException { ProcessBuilder pb = launchCapsuleArtifact(cmdLine, args); if (pb == null) pb = prepareForLaunch(cmdLine, args); Runtime.getRuntime().addShutdownHook(new Thread(this)); if (!isInheritIoBug()) pb.inheritIO(); this.child = pb.start(); if (isInheritIoBug()) pipeIoStreams(); return child; } // visible for testing final ProcessBuilder prepareForLaunch(List<String> cmdLine, String[] args) { ensureExtractedIfNecessary(); final ProcessBuilder pb = buildProcess(cmdLine, args); if (appCache != null && !cacheUpToDate) markCache(); verbose("Launching app " + appId); return pb; } private void printVersion() { System.out.println("CAPSULE: Application " + appId); System.out.println("CAPSULE: Capsule Version " + VERSION); } private void printJVMs() { final Map<String, Path> jres = getJavaHomes(false); if (jres == null) println("No detected Java installations"); else { System.out.println("CAPSULE: Detected Java installations:"); for (Map.Entry<String, Path> j : jres.entrySet()) System.out.println(j.getKey() + (j.getKey().length() < 8 ? "\t\t" : "\t") + j.getValue()); } System.out.println("CAPSULE: selected " + (javaHome != null ? javaHome : (System.getProperty(PROP_JAVA_HOME) + " (current)"))); } private void resolve(String[] args) throws IOException, InterruptedException { ensureExtractedIfNecessary(); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH)); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_P)); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_A)); resolveAppArtifact(getAppArtifact(args)); resolveDependencies(getDependencies(), "jar"); resolveNativeDependencies(); } private void ensureExtractedIfNecessary() { if (appCache != null && !cacheUpToDate) { resetAppCache(); if (shouldExtract()) extractCapsule(); } } private static boolean isInheritIoBug() { return isWindows() && compareVersions(System.getProperty(PROP_JAVA_VERSION), "1.8.0") < 0; } private void pipeIoStreams() { new Thread(this, "pipe-out").start(); new Thread(this, "pipe-err").start(); new Thread(this, "pipe-in").start(); } @Override public final void run() { if (isInheritIoBug()) { switch (Thread.currentThread().getName()) { case "pipe-out": pipe(child.getInputStream(), System.out); return; case "pipe-err": pipe(child.getErrorStream(), System.err); return; case "pipe-in": pipe(System.in, child.getOutputStream()); return; default: // shutdown hook } } if (child != null) child.destroy(); } private static void pipe(InputStream in, OutputStream out) { try { int read; byte[] buf = new byte[1024]; while (-1 != (read = in.read(buf))) { out.write(buf, 0, read); out.flush(); } } catch (IOException e) { if (verbose) e.printStackTrace(System.err); } finally { try { out.close(); } catch (IOException e2) { if (verbose) e2.printStackTrace(System.err); } } } private boolean isEmptyCapsule() { return !hasAttribute(ATTR_APP_ARTIFACT) && !hasAttribute(ATTR_APP_CLASS) && getScript() == null; } private void printDependencyTree(String[] args) { System.out.println("Dependencies for " + appId); if (dependencyManager == null) System.out.println("No dependencies declared."); else if (hasAttribute(ATTR_APP_ARTIFACT) || isEmptyCapsule()) { final String appArtifact = isEmptyCapsule() ? getCommandLineArtifact(args) : getAttribute(ATTR_APP_ARTIFACT); if (appArtifact == null) throw new IllegalStateException("capsule " + jarFile + " has nothing to run"); printDependencyTree(appArtifact); } else printDependencyTree(getDependencies(), "jar"); final List<String> nativeDeps = getNativeDependencies(); if (nativeDeps != null) { System.out.println("\nNative Dependencies:"); printDependencyTree(nativeDeps, getNativeLibExtension()); } } private ProcessBuilder launchCapsuleArtifact(List<String> cmdLine, String[] args) { if (getScript() == null) { String appArtifact = getAppArtifact(args); if (appArtifact != null) { try { final List<Path> jars = resolveAppArtifact(appArtifact); if (jars == null) return null; if (isCapsule(jars.get(0))) { verbose("Running capsule " + jars.get(0)); return launchCapsule(jars.get(0), cmdLine, isEmptyCapsule() ? Arrays.copyOfRange(args, 1, args.length) : buildArgs(args).toArray(new String[0])); } else if (isEmptyCapsule()) throw new IllegalArgumentException("Artifact " + appArtifact + " is not a capsule."); } catch (RuntimeException e) { if (isEmptyCapsule()) throw new RuntimeException("Usage: java -jar capsule.jar CAPSULE_ARTIFACT_COORDINATES", e); else throw e; } } } return null; } private String getAppArtifact(String[] args) { String appArtifact = null; if (isEmptyCapsule()) { appArtifact = getCommandLineArtifact(args); if (appArtifact == null) throw new IllegalStateException("Capsule " + jarFile + " has nothing to run"); } if (appArtifact == null) appArtifact = getAttribute(ATTR_APP_ARTIFACT); return appArtifact; } private String getCommandLineArtifact(String[] args) { if (args.length > 0) return args[0]; return null; } // visible for testing final ProcessBuilder buildProcess(List<String> cmdLine, String[] args) { final ProcessBuilder pb = new ProcessBuilder(); if (!buildScriptProcess(pb)) buildJavaProcess(pb, cmdLine); final List<String> command = pb.command(); command.addAll(buildArgs(args)); buildEnvironmentVariables(pb.environment()); verbose(join(command, " ")); return pb; } /** * Returns a list of command line arguments to pass to the application. * * @param args The command line arguments passed to the capsule at launch */ protected List<String> buildArgs(String[] args) { final List<String> args0 = new ArrayList<String>(); args0.addAll(nullToEmpty(expand(getListAttribute(ATTR_ARGS)))); args0.addAll(Arrays.asList(args)); return args0; } private boolean buildJavaProcess(ProcessBuilder pb, List<String> cmdLine) { if (javaHome != null) pb.environment().put("JAVA_HOME", javaHome); final List<String> command = pb.command(); command.add(getJavaProcessName()); command.addAll(buildJVMArgs(cmdLine)); command.addAll(compileSystemProperties(buildSystemProperties(cmdLine))); addOption(command, "-Xbootclasspath:", compileClassPath(buildBootClassPath(cmdLine))); addOption(command, "-Xbootclasspath/p:", compileClassPath(buildClassPath(ATTR_BOOT_CLASS_PATH_P))); addOption(command, "-Xbootclasspath/a:", compileClassPath(buildClassPath(ATTR_BOOT_CLASS_PATH_A))); final List<Path> classPath = buildClassPath(); command.add("-classpath"); command.add(compileClassPath(classPath)); for (String jagent : nullToEmpty(buildJavaAgents())) command.add("-javaagent:" + jagent); command.add(getMainClass(classPath)); return true; } private String getScript() { return getAttribute(isWindows() ? ATTR_WINDOWS_SCRIPT : ATTR_UNIX_SCRIPT); } private boolean buildScriptProcess(ProcessBuilder pb) { final String script = getScript(); if (script == null) return false; if (appCache == null) throw new IllegalStateException("Cannot run the startup script " + script + " when the " + ATTR_EXTRACT + " attribute is set to false"); final Path scriptPath = appCache.resolve(sanitize(script)).toAbsolutePath(); ensureExecutable(scriptPath); pb.command().add(scriptPath.toString()); return true; } private static void ensureExecutable(Path file) { if (!Files.isExecutable(file)) { try { Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file); if (!perms.contains(PosixFilePermission.OWNER_EXECUTE)) { Set<PosixFilePermission> newPerms = EnumSet.copyOf(perms); newPerms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, newPerms); } } catch (UnsupportedOperationException e) { } catch (IOException e) { throw new RuntimeException(e); } } } private static void addOption(List<String> cmdLine, String prefix, String value) { if (value == null) return; cmdLine.add(prefix + value); } private static String compileClassPath(List<Path> cp) { return join(cp, PATH_SEPARATOR); } private List<Path> buildClassPath() { final List<Path> classPath = new ArrayList<Path>(); if (!isEmptyCapsule() && !hasAttribute(ATTR_APP_ARTIFACT)) { // the capsule jar final String isCapsuleInClassPath = getAttribute(ATTR_CAPSULE_IN_CLASS_PATH); if (isCapsuleInClassPath == null || Boolean.parseBoolean(isCapsuleInClassPath)) classPath.add(jarFile); else if (appCache == null) throw new IllegalStateException("Cannot set the " + ATTR_CAPSULE_IN_CLASS_PATH + " attribute to false when the " + ATTR_EXTRACT + " attribute is also set to false"); } if (hasAttribute(ATTR_APP_ARTIFACT)) { assert dependencyManager != null; classPath.addAll(nullToEmpty(resolveAppArtifact(getAttribute(ATTR_APP_ARTIFACT)))); } if (hasAttribute(ATTR_APP_CLASS_PATH)) { for (String sp : getListAttribute(ATTR_APP_CLASS_PATH)) { Path p = Paths.get(expand(sanitize(sp))); if (appCache == null && (!p.isAbsolute() || p.startsWith(appCache))) throw new IllegalStateException("Cannot resolve " + sp + " in " + ATTR_APP_CLASS_PATH + " attribute when the " + ATTR_EXTRACT + " attribute is set to false"); p = appCache.resolve(p); classPath.add(p); } } if (appCache != null) classPath.addAll(nullToEmpty(getDefaultCacheClassPath())); classPath.addAll(nullToEmpty(resolveDependencies(getDependencies(), "jar"))); return classPath; } private List<Path> buildBootClassPath(List<String> cmdLine) { String option = null; for (String o : cmdLine) { if (o.startsWith("-Xbootclasspath:")) option = o.substring("-Xbootclasspath:".length()); } if (option != null) return toPath(Arrays.asList(option.split(PATH_SEPARATOR))); return getPath(getListAttribute(ATTR_BOOT_CLASS_PATH)); } private List<Path> buildClassPath(String attr) { return getPath(getListAttribute(attr)); } /** * Returns a map of environment variables (property-value pairs). * * @param env the current environment */ private void buildEnvironmentVariables(Map<String, String> env) { final List<String> jarEnv = getListAttribute(ATTR_ENV); if (jarEnv != null) { for (String e : jarEnv) { String var = getBefore(e, '='); String value = getAfter(e, '='); if (var == null) throw new IllegalArgumentException("Malformed env variable definition: " + e); boolean overwrite = false; if (var.endsWith(":")) { overwrite = true; var = var.substring(0, var.length() - 1); } if (overwrite || !env.containsKey(var)) env.put(var, value != null ? value : ""); } } } /** * Returns a map of system properties (property-value pairs). * * @param cmdLine the list of JVM arguments passed to the capsule at launch */ protected Map<String, String> buildSystemProperties(List<String> cmdLine) { final Map<String, String> systemProperties = new HashMap<String, String>(); // attribute for (Map.Entry<String, String> pv : nullToEmpty(getMapAttribute(ATTR_SYSTEM_PROPERTIES, "")).entrySet()) systemProperties.put(pv.getKey(), expand(pv.getValue())); // library path if (appCache != null) { final List<Path> libraryPath = buildNativeLibraryPath(); libraryPath.add(appCache); systemProperties.put(PROP_JAVA_LIBRARY_PATH, compileClassPath(libraryPath)); } else if (hasAttribute(ATTR_LIBRARY_PATH_P) || hasAttribute(ATTR_LIBRARY_PATH_A)) throw new IllegalStateException("Cannot use the " + ATTR_LIBRARY_PATH_P + " or the " + ATTR_LIBRARY_PATH_A + " attributes when the " + ATTR_EXTRACT + " attribute is set to false"); if (hasAttribute(ATTR_SECURITY_POLICY) || hasAttribute(ATTR_SECURITY_POLICY_A)) { systemProperties.put(PROP_JAVA_SECURITY_MANAGER, ""); if (hasAttribute(ATTR_SECURITY_POLICY_A)) systemProperties.put(PROP_JAVA_SECURITY_POLICY, toJarUrl(getAttribute(ATTR_SECURITY_POLICY_A))); if (hasAttribute(ATTR_SECURITY_POLICY)) systemProperties.put(PROP_JAVA_SECURITY_POLICY, "=" + toJarUrl(getAttribute(ATTR_SECURITY_POLICY))); } if (hasAttribute(ATTR_SECURITY_MANAGER)) systemProperties.put(PROP_JAVA_SECURITY_MANAGER, getAttribute(ATTR_SECURITY_MANAGER)); // Capsule properties if (appCache != null) systemProperties.put(PROP_CAPSULE_DIR, appCache.toAbsolutePath().toString()); systemProperties.put(PROP_CAPSULE_JAR, getJarPath()); systemProperties.put(PROP_CAPSULE_APP, appId); // command line for (String option : cmdLine) { if (option.startsWith("-D")) addSystemProperty(option.substring(2), systemProperties); } return systemProperties; } private List<Path> buildNativeLibraryPath() { final List<Path> libraryPath = new ArrayList<Path>(); resolveNativeDependencies(); libraryPath.addAll(nullToEmpty(toAbsolutePath(appCache, getListAttribute(ATTR_LIBRARY_PATH_P)))); libraryPath.addAll(toPath(Arrays.asList(System.getProperty(PROP_JAVA_LIBRARY_PATH).split(PATH_SEPARATOR)))); libraryPath.addAll(nullToEmpty(toAbsolutePath(appCache, getListAttribute(ATTR_LIBRARY_PATH_A)))); libraryPath.add(appCache); return libraryPath; } private String getNativeLibExtension() { if (isWindows()) return "dll"; if (isMac()) return "dylib"; if (isUnix()) return "so"; throw new RuntimeException("Unsupported operating system: " + System.getProperty(PROP_OS_NAME)); } private List<String> getNativeDependencies() { return stripNativeDependencies(getNativeDependenciesAndRename()); } /** * Returns a list of dependencies, each in the format {@code groupId:artifactId:version[:classifier][,renameTo]} * (classifier and renameTo are optional) */ protected List<String> getNativeDependenciesAndRename() { if (isWindows()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_WIN); if (isMac()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_MAC); if (isUnix()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_LINUX); return null; } protected final List<String> stripNativeDependencies(List<String> nativeDepsAndRename) { if (nativeDepsAndRename == null) return null; final List<String> deps = new ArrayList<String>(nativeDepsAndRename.size()); for (String depAndRename : nativeDepsAndRename) { String[] dna = depAndRename.split(","); deps.add(dna[0]); } return deps; } private boolean hasRenamedNativeDependencies() { final List<String> depsAndRename = getNativeDependenciesAndRename(); if (depsAndRename == null) return false; for (String depAndRename : depsAndRename) { if (depAndRename.contains(",")) return true; } return false; } private void resolveNativeDependencies() { if (appCache == null) throw new IllegalStateException("Cannot set " + ATTR_EXTRACT + " to false if there are native dependencies."); final List<String> depsAndRename = getNativeDependenciesAndRename(); if (depsAndRename == null || depsAndRename.isEmpty()) return; final List<String> deps = new ArrayList<String>(depsAndRename.size()); final List<String> renames = new ArrayList<String>(depsAndRename.size()); for (String depAndRename : depsAndRename) { String[] dna = depAndRename.split(","); deps.add(dna[0]); renames.add(dna.length > 1 ? dna[1] : null); } verbose("Resolving native libs " + deps); final List<Path> resolved = resolveDependencies(deps, getNativeLibExtension()); if (resolved.size() != deps.size()) throw new RuntimeException("One of the native artifacts " + deps + " reolved to more than a single file"); assert appCache != null; if (!cacheUpToDate) { if (debug) System.err.println("Copying native libs to " + appCache); try { for (int i = 0; i < deps.size(); i++) { final Path lib = resolved.get(i); final String rename = sanitize(renames.get(i)); Files.copy(lib, appCache.resolve(rename != null ? rename : lib.getFileName().toString())); } } catch (IOException e) { throw new RuntimeException("Exception while copying native libs"); } } } private String getJarPath() { return jarFile.toAbsolutePath().getParent().toString(); } private static List<String> compileSystemProperties(Map<String, String> ps) { final List<String> command = new ArrayList<String>(); for (Map.Entry<String, String> entry : ps.entrySet()) command.add("-D" + entry.getKey() + (entry.getValue() != null && !entry.getValue().isEmpty() ? "=" + entry.getValue() : "")); return command; } private static void addSystemProperty(String p, Map<String, String> ps) { try { String name = getBefore(p, '='); String value = getAfter(p, '='); ps.put(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Illegal system property definition: " + p); } } /** * Returns a list of JVM arguments. * * @param cmdLine the list of JVM arguments passed to the capsule at launch */ protected List<String> buildJVMArgs(List<String> cmdLine) { final Map<String, String> jvmArgs = new LinkedHashMap<String, String>(); for (String a : nullToEmpty(getListAttribute(ATTR_JVM_ARGS))) { a = a.trim(); if (!a.isEmpty() && !a.startsWith("-Xbootclasspath:") && !a.startsWith("-javaagent:")) addJvmArg(expand(a), jvmArgs); } for (String option : cmdLine) { if (!option.startsWith("-D") && !option.startsWith("-Xbootclasspath:")) addJvmArg(option, jvmArgs); } return new ArrayList<String>(jvmArgs.values()); } private static void addJvmArg(String a, Map<String, String> args) { args.put(getJvmArgKey(a), a); } private static String getJvmArgKey(String a) { if (a.equals("-client") || a.equals("-server")) return "compiler"; if (a.equals("-enablesystemassertions") || a.equals("-esa") || a.equals("-disablesystemassertions") || a.equals("-dsa")) return "systemassertions"; if (a.equals("-jre-restrict-search") || a.equals("-no-jre-restrict-search")) return "-jre-restrict-search"; if (a.startsWith("-Xloggc:")) return "-Xloggc"; if (a.startsWith("-Xloggc:")) return "-Xloggc"; if (a.startsWith("-Xss")) return "-Xss"; if (a.startsWith("-XX:+") || a.startsWith("-XX:-")) return "-XX:" + a.substring("-XX:+".length()); if (a.contains("=")) return a.substring(0, a.indexOf("=")); return a; } private List<String> buildJavaAgents() { final Map<String, String> agents0 = getMapAttribute(ATTR_JAVA_AGENTS, ""); if (agents0 == null) return null; final List<String> agents = new ArrayList<String>(agents0.size()); for (Map.Entry<String, String> agent : agents0.entrySet()) { final String agentJar = agent.getKey(); final String agentOptions = agent.getValue(); try { final Path agentPath = getPath(agent.getKey()); agents.add(agentPath + ((agentOptions != null && !agentOptions.isEmpty()) ? "=" + agentOptions : "")); } catch (IllegalStateException e) { if (appCache == null) throw new RuntimeException("Cannot run the embedded Java agent " + agentJar + " when the " + ATTR_EXTRACT + " attribute is set to false"); throw e; } } return agents; } private static Path getJarFile() { final URL url = Capsule.class.getClassLoader().getResource(Capsule.class.getName().replace('.', '/') + ".class"); if (!"jar".equals(url.getProtocol())) throw new IllegalStateException("The Capsule class must be in a JAR file, but was loaded from: " + url); final String path = url.getPath(); if (path == null || !path.startsWith("file:")) throw new IllegalStateException("The Capsule class must be in a local JAR file, but was loaded from: " + url); try { final URI jarUri = new URI(path.substring(0, path.indexOf('!'))); return Paths.get(jarUri); } catch (URISyntaxException e) { throw new AssertionError(e); } } private String getAppId(String[] args) { String appName = System.getProperty(PROP_APP_ID); if (appName == null) appName = getAttribute(ATTR_APP_NAME); if (appName == null) { appName = getApplicationArtifactId(getAppArtifact(args)); if (appName != null) return getAppArtifactLatestVersion(appName); } if (appName == null) { if (pom != null) return getPomAppName(); appName = getAttribute(ATTR_APP_CLASS); } if (appName == null) { if (isEmptyCapsule()) return null; throw new RuntimeException("Capsule jar " + jarFile + " must either have the " + ATTR_APP_NAME + " manifest attribute, " + "the " + ATTR_APP_CLASS + " attribute, or contain a " + POM_FILE + " file."); } final String version = hasAttribute(ATTR_APP_VERSION) ? getAttribute(ATTR_APP_VERSION) : getAttribute(ATTR_IMPLEMENTATION_VERSION); return appName + (version != null ? "_" + version : ""); } private String getMainClass(List<Path> classPath) { try { String mainClass = getAttribute(ATTR_APP_CLASS); if (mainClass == null && hasAttribute(ATTR_APP_ARTIFACT)) mainClass = getMainClass(new JarFile(classPath.get(0).toAbsolutePath().toString())); if (mainClass == null) throw new RuntimeException("Jar " + classPath.get(0).toAbsolutePath() + " does not have a main class defined in the manifest."); return mainClass; } catch (IOException e) { throw new RuntimeException(e); } } private List<Path> getDefaultCacheClassPath() { final List<Path> cp = new ArrayList<Path>(); cp.add(appCache); // we don't use Files.walkFileTree because we'd like to avoid creating more classes (Capsule$1.class etc.) for (Path f : listDir(appCache)) { if (Files.isRegularFile(f) && f.getFileName().toString().endsWith(".jar")) { cp.add(f.toAbsolutePath()); } } return cp; } private Path getPath(String p) { if (isDependency(p) && dependencyManager != null) return getDependencyPath(dependencyManager, p); if (appCache == null) throw new IllegalStateException( (isDependency(p) ? "Dependency manager not found. Cannot resolve" : "Capsule not extracted. Cannot obtain path") + " " + p); if (isDependency(p)) { Path f = appCache.resolve(dependencyToLocalJar(true, p)); if (Files.isRegularFile(f)) return f; f = appCache.resolve(dependencyToLocalJar(false, p)); if (Files.isRegularFile(f)) return f; throw new IllegalArgumentException("Dependency manager not found, and could not locate artifact " + p + " in capsule"); } else return toAbsolutePath(appCache, p); } private String dependencyToLocalJar(boolean withGroupId, String p) { String[] coords = p.split(":"); StringBuilder sb = new StringBuilder(); if (withGroupId) sb.append(coords[0]).append('-'); sb.append(coords[1]).append('-'); sb.append(coords[2]); if (coords.length > 3) sb.append('-').append(coords[3]); sb.append(".jar"); return sb.toString(); } private List<Path> getPath(List<String> ps) { if (ps == null) return null; final List<Path> res = new ArrayList<Path>(ps.size()); for (String p : ps) res.add(getPath(p)); return res; } private String toJarUrl(String relPath) { return "jar:file:" + getJarPath() + "!/" + relPath; } private static List<Path> toPath(List<String> ps) { if (ps == null) return null; final List<Path> aps = new ArrayList<Path>(ps.size()); for (String p : ps) aps.add(Paths.get(p)); return aps; } private static List<Path> toAbsolutePath(Path root, List<String> ps) { if (ps == null) return null; final List<Path> aps = new ArrayList<Path>(ps.size()); for (String p : ps) aps.add(toAbsolutePath(root, p)); return aps; } private static Path toAbsolutePath(Path root, String p) { return root.resolve(sanitize(p)).toAbsolutePath(); } private String getAttribute(String attr) { String value = null; Attributes atts; if (mode != null) { atts = manifest.getAttributes(mode); if (atts == null) throw new IllegalArgumentException("Mode " + mode + " not defined in manifest"); value = atts.getValue(attr); } if (value == null) { atts = manifest.getMainAttributes(); value = atts.getValue(attr); } return value; } private boolean hasAttribute(String attr) { final Attributes.Name key = new Attributes.Name(attr); Attributes atts; if (mode != null) { atts = manifest.getAttributes(mode); if (atts != null && atts.containsKey(key)) return true; } atts = manifest.getMainAttributes(); return atts.containsKey(new Attributes.Name(attr)); } private List<String> getListAttribute(String attr) { return split(getAttribute(attr), "\\s+"); } private Map<String, String> getMapAttribute(String attr, String defaultValue) { return mapSplit(getAttribute(attr), '=', "\\s+", defaultValue); } private static List<String> split(String str, String separator) { if (str == null) return null; String[] es = str.split(separator); final List<String> list = new ArrayList<>(es.length); for (String e : es) { e = e.trim(); if (!e.isEmpty()) list.add(e); } return list; } private static Map<String, String> mapSplit(String map, char kvSeparator, String separator, String defaultValue) { if (map == null) return null; Map<String, String> m = new HashMap<>(); for (String entry : split(map, separator)) { final String key = getBefore(entry, kvSeparator); String value = getAfter(entry, kvSeparator); if (value == null) { if (defaultValue != null) value = defaultValue; else throw new IllegalArgumentException("Element " + entry + " in \"" + map + "\" is not a key-value entry separated with " + kvSeparator + " and no default value provided"); } m.put(key.trim(), value.trim()); } return m; } private Path getAppCacheDir() { Path appDir = cacheDir.resolve(APP_CACHE_NAME).resolve(appId); try { if (!Files.exists(appDir)) Files.createDirectory(appDir); return appDir; } catch (IOException e) { throw new RuntimeException("Application cache directory " + appDir.toAbsolutePath() + " could not be created."); } } private static Path getCacheDir() { final Path cache; final String cacheDirEnv = System.getenv(ENV_CACHE_DIR); if (cacheDirEnv != null) cache = Paths.get(cacheDirEnv); else { final String cacheNameEnv = System.getenv(ENV_CACHE_NAME); final String cacheName = cacheNameEnv != null ? cacheNameEnv : CACHE_DEFAULT_NAME; cache = getCacheHome().resolve((isWindows() ? "" : ".") + cacheName); } return cache; } private static Path initCacheDir(Path cache) { try { if (!Files.exists(cache)) Files.createDirectory(cache); if (!Files.exists(cache.resolve(APP_CACHE_NAME))) Files.createDirectory(cache.resolve(APP_CACHE_NAME)); if (!Files.exists(cache.resolve(DEPS_CACHE_NAME))) Files.createDirectory(cache.resolve(DEPS_CACHE_NAME)); return cache; } catch (IOException e) { throw new RuntimeException("Error opening cache directory " + cache.toAbsolutePath(), e); } } private static Path getCacheHome() { final Path userHome = Paths.get(System.getProperty(PROP_USER_HOME)); if (!isWindows()) return userHome; Path localData; final String localAppData = System.getenv("LOCALAPPDATA"); if (localAppData != null) { localData = Paths.get(localAppData); if (!Files.isDirectory(localData)) throw new RuntimeException("%LOCALAPPDATA% set to nonexistent directory " + localData); } else { localData = userHome.resolve(Paths.get("AppData", "Local")); if (!Files.isDirectory(localData)) localData = userHome.resolve(Paths.get("Local Settings", "Application Data")); if (!Files.isDirectory(localData)) throw new RuntimeException("%LOCALAPPDATA% is undefined, and neither " + userHome.resolve(Paths.get("AppData", "Local")) + " nor " + userHome.resolve(Paths.get("Local Settings", "Application Data")) + " have been found"); } return localData; } private boolean needsAppCache() { if (isEmptyCapsule()) return false; if (hasRenamedNativeDependencies()) return true; if (hasAttribute(ATTR_APP_ARTIFACT)) return false; return shouldExtract(); } private boolean shouldExtract() { final String extract = getAttribute(ATTR_EXTRACT); return extract == null || Boolean.parseBoolean(extract); } private void resetAppCache() { try { debug("Creating cache for " + jarFile + " in " + appCache.toAbsolutePath()); delete(appCache); Files.createDirectory(appCache); } catch (IOException e) { throw new RuntimeException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e); } } private boolean isUpToDate() { if (Boolean.parseBoolean(System.getProperty(PROP_RESET, "false"))) return false; try { Path extractedFile = appCache.resolve(".extracted"); if (!Files.exists(extractedFile)) return false; FileTime extractedTime = Files.getLastModifiedTime(extractedFile); FileTime jarTime = Files.getLastModifiedTime(jarFile); return extractedTime.compareTo(jarTime) >= 0; } catch (IOException e) { throw new AssertionError(e); } } private void extractCapsule() { try { verbose("Extracting " + jarFile + " to app cache directory " + appCache.toAbsolutePath()); if (!isTest()) extractJar(jar, appCache); else extractJar(getJarInputStream(), appCache); } catch (IOException e) { throw new RuntimeException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e); } } private void markCache() { try { Files.createFile(appCache.resolve(".extracted")); } catch (IOException e) { throw new RuntimeException(e); } } private static boolean isCapsule(Path path) { try { if (Files.isRegularFile(path) && path.getFileName().toString().endsWith(".jar")) { final JarFile jar = new JarFile(path.toFile()); return isCapsule(jar); } return false; } catch (IOException e) { throw new RuntimeException(e); } } private static boolean isCapsule(JarFile jar) { return "Capsule".equals(getMainClass(jar)); // for (Enumeration entries = jar.entries(); entries.hasMoreElements();) { // final JarEntry file = (JarEntry) entries.nextElement(); // if (file.getName().equals("Capsule.class")) // return true; // return false; } private static String getMainClass(JarFile jar) { try { final Manifest manifest = jar.getManifest(); if (manifest != null) return manifest.getMainAttributes().getValue("Main-Class"); return null; } catch (IOException e) { throw new RuntimeException(e); } } private static void extractJar(JarFile jar, Path targetDir) throws IOException { for (Enumeration entries = jar.entries(); entries.hasMoreElements();) { final JarEntry entry = (JarEntry) entries.nextElement(); if (entry.isDirectory() || !shouldExtractFile(entry.getName())) continue; try (InputStream is = jar.getInputStream(entry)) { writeFile(targetDir, entry.getName(), is); } } } private static void extractJar(JarInputStream jar, Path targetDir) throws IOException { for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) { if (entry.isDirectory() || !shouldExtractFile(entry.getName())) continue; writeFile(targetDir, entry.getName(), jar); } } private static boolean shouldExtractFile(String fileName) { if (fileName.equals(Capsule.class.getName().replace('.', '/') + ".class") || (fileName.startsWith(Capsule.class.getName().replace('.', '/') + "$") && fileName.endsWith(".class"))) return false; if (fileName.endsWith(".class")) return false; if (fileName.startsWith("capsule/")) return false; final String dir = getDirectory(fileName); if (dir != null && dir.startsWith("META-INF")) return false; return true; } private static void writeFile(Path targetDir, String fileName, InputStream is) throws IOException { final String dir = getDirectory(fileName); if (dir != null) Files.createDirectories(targetDir.resolve(dir)); final Path targetFile = targetDir.resolve(fileName); Files.copy(is, targetFile); } private static String getDirectory(String filename) { final int index = filename.lastIndexOf('/'); if (index < 0) return null; return filename.substring(0, index); } private String getJavaHome() { String jhome = System.getProperty(PROP_CAPSULE_JAVA_HOME); if (jhome == null && !isMatchingJavaVersion(System.getProperty(PROP_JAVA_VERSION))) { final boolean jdk = hasAttribute(ATTR_JDK_REQUIRED) && Boolean.parseBoolean(getAttribute(ATTR_JDK_REQUIRED)); final Path javaHomePath = findJavaHome(jdk); if (javaHomePath == null) { throw new RuntimeException("Could not find Java installation for requested version " + '[' + "Min. Java version: " + getAttribute(ATTR_MIN_JAVA_VERSION) + " JavaVersion: " + getAttribute(ATTR_JAVA_VERSION) + " Min. update version: " + getAttribute(ATTR_MIN_UPDATE_VERSION) + ']' + " (JDK required: " + jdk + ")" + ". You can override the used Java version with the -D" + PROP_CAPSULE_JAVA_HOME + " flag."); } jhome = javaHomePath.toAbsolutePath().toString(); } return jhome; } private boolean isMatchingJavaVersion(String javaVersion) { try { if (hasAttribute(ATTR_MIN_JAVA_VERSION) && compareVersions(javaVersion, getAttribute(ATTR_MIN_JAVA_VERSION)) < 0) { debug("Java version " + javaVersion + " fails to match due to " + ATTR_MIN_JAVA_VERSION + ": " + getAttribute(ATTR_MIN_JAVA_VERSION)); return false; } if (hasAttribute(ATTR_JAVA_VERSION) && compareVersions(javaVersion, shortJavaVersion(getAttribute(ATTR_JAVA_VERSION)), 3) > 0) { debug("Java version " + javaVersion + " fails to match due to " + ATTR_JAVA_VERSION + ": " + getAttribute(ATTR_JAVA_VERSION)); return false; } if (getMinUpdateFor(javaVersion) > parseJavaVersion(javaVersion)[3]) { debug("Java version " + javaVersion + " fails to match due to " + ATTR_MIN_UPDATE_VERSION + ": " + getAttribute(ATTR_MIN_UPDATE_VERSION) + " (" + getMinUpdateFor(javaVersion) + ")"); return false; } debug("Java version " + javaVersion + " matches"); return true; } catch (IllegalArgumentException ex) { verbose("Error parsing Java version " + javaVersion); return false; } } private String getJavaProcessName() { final String javaHome1 = javaHome != null ? javaHome : System.getProperty(PROP_JAVA_HOME); verbose("Using JVM: " + javaHome1 + (javaHome == null ? " (current)" : "")); return getJavaProcessName(javaHome1); } private static String getJavaProcessName(String javaHome) { return javaHome + FILE_SEPARATOR + "bin" + FILE_SEPARATOR + "java" + (isWindows() ? ".exe" : ""); } protected static final boolean isWindows() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows"); } protected static final boolean isMac() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("mac"); } protected static final boolean isUnix() { return System.getProperty(PROP_OS_NAME).toLowerCase().contains("nux") || System.getProperty(PROP_OS_NAME).toLowerCase().contains("solaris") || System.getProperty(PROP_OS_NAME).toLowerCase().contains("aix"); } private static boolean isDependency(String lib) { return lib.contains(":"); } private static String sanitize(String path) { if (path.startsWith("/") || path.startsWith("../") || path.contains("/../")) throw new IllegalArgumentException("Path " + path + " is not local"); return path; } private static String join(Collection<?> coll, String separator) { if (coll == null) return null; StringBuilder sb = new StringBuilder(); for (Object e : coll) { if (e != null) sb.append(e).append(separator); } sb.delete(sb.length() - separator.length(), sb.length()); return sb.toString(); } private static String getBefore(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return s; return s.substring(0, i); } private static String getAfter(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return null; return s.substring(i + 1); } private boolean hasEntry(String name) { try { return getEntry(name) != null; } catch (IOException e) { throw new RuntimeException(e); } } private InputStream getEntry(String name) throws IOException { if (!isTest()) { final JarEntry entry = jar.getJarEntry(name); if (entry == null) return null; return jar.getInputStream(entry); } // test final JarInputStream jis = getJarInputStream(); for (JarEntry entry; (entry = jis.getNextJarEntry()) != null;) { if (name.equals(entry.getName())) return jis; } return null; } private boolean hasPom() { return hasEntry(POM_FILE); } private Object createPomReader() { try { return new PomReader(getEntry(POM_FILE)); } catch (NoClassDefFoundError e) { throw new RuntimeException("Jar " + jarFile + " contains a pom.xml file, while the necessary dependency management classes are not found in the jar"); } catch (IOException e) { throw new RuntimeException("Failed reading pom", e); } } private List<String> getPomRepositories() { return ((PomReader) pom).getRepositories(); } private List<String> getPomDependencies() { return ((PomReader) pom).getDependencies(); } private String getPomAppName() { final PomReader pr = (PomReader) pom; return pr.getGroupId() + "_" + pr.getArtifactId() + "_" + pr.getVersion(); } private Object createDependencyManager(List<String> repositories) { try { final Path depsCache = cacheDir.resolve(DEPS_CACHE_NAME); final boolean reset = Boolean.parseBoolean(System.getProperty(PROP_RESET, "false")); final String local = expandCommandLinePath(System.getProperty(PROP_USE_LOCAL_REPO)); Path localRepo = depsCache; if (local != null) localRepo = !local.isEmpty() ? Paths.get(local) : DEFAULT_LOCAL_MAVEN; debug("Local repo: " + localRepo); final boolean offline = "".equals(System.getProperty(PROP_OFFLINE)) || Boolean.parseBoolean(System.getProperty(PROP_OFFLINE)); debug("Offline: " + offline); final DependencyManager dm = new AetherDependencyManager(localRepo.toAbsolutePath(), repositories, reset, offline); return dm; } catch (NoClassDefFoundError e) { throw new RuntimeException("Jar " + jarFile + " specifies dependencies, while the necessary dependency management classes are not found in the jar"); } } private List<String> getRepositories() { List<String> repos = new ArrayList<String>(); List<String> attrRepos = split(System.getenv(ENV_CAPSULE_REPOS), ":"); if (attrRepos == null) attrRepos = getListAttribute(ATTR_REPOSITORIES); if (attrRepos != null) repos.addAll(attrRepos); if (pom != null) { for (String repo : nullToEmpty(getPomRepositories())) { if (!repos.contains(repo)) repos.add(repo); } } return !repos.isEmpty() ? Collections.unmodifiableList(repos) : null; } /** * Returns a list of dependencies, each in the format {@code groupId:artifactId:version[:classifier]} (classifier is optional) */ protected List<String> getDependencies() { List<String> deps = getListAttribute(ATTR_DEPENDENCIES); if (deps == null && pom != null) deps = getPomDependencies(); return deps != null ? Collections.unmodifiableList(deps) : null; } private void printDependencyTree(String root) { final DependencyManager dm = (DependencyManager) dependencyManager; dm.printDependencyTree(root); } private void printDependencyTree(List<String> dependencies, String type) { if (dependencies == null) return; final DependencyManager dm = (DependencyManager) dependencyManager; dm.printDependencyTree(dependencies, type); } private List<Path> resolveDependencies(List<String> dependencies, String type) { if (dependencies == null) return null; return ((DependencyManager) dependencyManager).resolveDependencies(dependencies, type); } private String getAppArtifactLatestVersion(String coords) { if (coords == null) return null; final DependencyManager dm = (DependencyManager) dependencyManager; return dm.getLatestVersion(coords); } private List<Path> resolveAppArtifact(String coords) { if (coords == null) return null; final DependencyManager dm = (DependencyManager) dependencyManager; return dm.resolveRoot(coords); } private static Path getDependencyPath(Object dependencyManager, String p) { if (dependencyManager == null) throw new RuntimeException("No dependencies specified in the capsule. Cannot resolve dependency " + p); final DependencyManager dm = (DependencyManager) dependencyManager; List<Path> depsJars = dm.resolveDependency(p, "jar"); if (depsJars == null || depsJars.isEmpty()) throw new RuntimeException("Dependency " + p + " was not found."); return depsJars.iterator().next().toAbsolutePath(); } private void delete(Path dir) throws IOException { // we don't use Files.walkFileTree because we'd like to avoid creating more classes (Capsule$1.class etc.) for (Path f : listDir(dir, FILE_VISITOR_MODE_POSTORDER)) Files.delete(f); } private Path findJavaHome(boolean jdk) { final Map<String, Path> homes = getJavaHomes(jdk); if (homes == null) return null; Path best = null; String bestVersion = null; for (Map.Entry<String, Path> e : homes.entrySet()) { final String v = e.getKey(); debug("Trying JVM: " + e.getValue() + " (version " + e.getKey() + ")"); if (isMatchingJavaVersion(v)) { debug("JVM " + e.getValue() + " (version " + e.getKey() + ") matches"); if (bestVersion == null || compareVersions(v, bestVersion) > 0) { debug("JVM " + e.getValue() + " (version " + e.getKey() + ") is best so far"); bestVersion = v; best = e.getValue(); } } } return best; } private Map<String, Path> getJavaHomes(boolean jdk) { Path dir = Paths.get(System.getProperty(PROP_JAVA_HOME)).getParent(); while (dir != null) { Map<String, Path> homes = getJavaHomes(dir, jdk); if (homes != null) return homes; dir = dir.getParent(); } return null; } private Map<String, Path> getJavaHomes(Path dir, boolean jdk) { if (!Files.isDirectory(dir)) return null; Map<String, Path> dirs = new HashMap<String, Path>(); for (Path f : listDir(dir)) { if (Files.isDirectory(f)) { String dirName = f.getFileName().toString(); String ver = isJavaDir(dirName); if (ver != null && (!jdk || isJDK(dirName))) { final Path home = searchJavaHomeInDir(f); if (home != null) { if (parseJavaVersion(ver)[3] == 0) ver = getActualJavaVersion(home.toString()); dirs.put(ver, home); } } } } return !dirs.isEmpty() ? dirs : null; } private static String isJavaDir(String fileName) { fileName = fileName.toLowerCase(); if (fileName.startsWith("jdk") || fileName.startsWith("jre") || fileName.endsWith(".jdk") || fileName.endsWith(".jre")) { if (fileName.startsWith("jdk") || fileName.startsWith("jre")) fileName = fileName.substring(3); if (fileName.endsWith(".jdk") || fileName.endsWith(".jre")) fileName = fileName.substring(0, fileName.length() - 4); return shortJavaVersion(fileName); } else return null; } private static boolean isJDK(String filename) { return filename.toLowerCase().contains("jdk"); } private Path searchJavaHomeInDir(Path dir) { if (!Files.isDirectory(dir)) return null; for (Path f : listDir(dir)) { if (isJavaHome(f)) return f; Path home = searchJavaHomeInDir(f); if (home != null) return home; } return null; } private boolean isJavaHome(Path dir) { if (Files.isDirectory(dir)) { for (Path f : listDir(dir)) { if (Files.isDirectory(f) && f.getFileName().toString().equals("bin")) { for (Path f0 : listDir(f)) { if (Files.isRegularFile(f0)) { String fname = f0.getFileName().toString().toLowerCase(); if (fname.equals("java") || fname.equals("java.exe")) return true; } } break; } } } return false; } private static final Pattern PAT_JAVA_VERSION_LINE = Pattern.compile(".*?\"(.+?)\""); private static String getActualJavaVersion(String javaHome) { try { final ProcessBuilder pb = new ProcessBuilder(getJavaProcessName(javaHome), "-version"); if (javaHome != null) pb.environment().put("JAVA_HOME", javaHome); final Process p = pb.start(); final String version; try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()))) { final String versionLine = reader.readLine(); final Matcher m = PAT_JAVA_VERSION_LINE.matcher(versionLine); if (!m.matches()) throw new IllegalArgumentException("Could not parse version line: " + versionLine); version = m.group(1); } // p.waitFor(); return version; } catch (Exception e) { throw new RuntimeException(e); } } // visible for testing static String shortJavaVersion(String v) { try { final String[] vs = v.split(DOT); if (vs.length == 1) { if (Integer.parseInt(vs[0]) < 5) throw new RuntimeException("Unrecognized major Java version: " + v); v = "1." + v + ".0"; } if (vs.length == 2) v += ".0"; return v; } catch (NumberFormatException e) { return null; } } static final int compareVersions(String a, String b, int n) { return compareVersions(parseJavaVersion(a), parseJavaVersion(b), n); } static final int compareVersions(String a, String b) { return compareVersions(parseJavaVersion(a), parseJavaVersion(b)); } private static int compareVersions(int[] a, int[] b) { return compareVersions(a, b, 5); } private static int compareVersions(int[] a, int[] b, int n) { for (int i = 0; i < n; i++) { if (a[i] != b[i]) return a[i] - b[i]; } return 0; } private static boolean equals(int[] a, int[] b, int n) { for (int i = 0; i < n; i++) { if (a[i] != b[i]) return false; } return true; } private static final Pattern PAT_JAVA_VERSION = Pattern.compile("(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(_(?<update>\\d+))?(-(?<pre>[^-]+))?(-(?<build>.+))?"); // visible for testing static int[] parseJavaVersion(String v) { final Matcher m = PAT_JAVA_VERSION.matcher(v); if (!m.matches()) throw new IllegalArgumentException("Could not parse version: " + v); final int[] ver = new int[5]; ver[0] = toInt(m.group("major")); ver[1] = toInt(m.group("minor")); ver[2] = toInt(m.group("patch")); ver[3] = toInt(m.group("update")); final String pre = m.group("pre"); if (pre != null) { if (pre.startsWith("rc")) ver[4] = -1; else if (pre.startsWith("beta")) ver[4] = -2; else if (pre.startsWith("ea")) ver[4] = -3; } return ver; } // visible for testing static String toJavaVersionString(int[] version) { final StringBuilder sb = new StringBuilder(); sb.append(version[0]).append('.'); sb.append(version[1]).append('.'); sb.append(version[2]); if (version.length > 3 && version[3] > 0) sb.append('_').append(version[3]); if (version.length > 4 && version[4] != 0) { final String pre; switch (version[4]) { case -1: pre = "rc"; break; case -2: pre = "beta"; break; case -3: pre = "ea"; break; default: pre = "?"; } sb.append('-').append(pre); } return sb.toString(); } private static int toInt(String s) { return s != null ? Integer.parseInt(s) : 0; } private static int[] toInt(String[] ss) { int[] res = new int[ss.length]; for (int i = 0; i < ss.length; i++) res[i] = ss[i] != null ? Integer.parseInt(ss[i]) : 0; return res; } private static <T> List<T> nullToEmpty(List<T> list) { if (list == null) return Collections.emptyList(); return list; } private static <K, V> Map<K, V> nullToEmpty(Map<K, V> map) { if (map == null) return Collections.emptyMap(); return map; } private static <T> Collection<T> nullToEmpty(Collection<T> coll) { if (coll == null) return Collections.emptyList(); return coll; } private List<String> expand(List<String> strs) { if (strs == null) return null; final List<String> res = new ArrayList<String>(strs.size()); for (String s : strs) res.add(expand(s)); return res; } private String expand(String str) { if (appCache != null) str = str.replaceAll("\\$" + VAR_CAPSULE_DIR, appCache.toAbsolutePath().toString()); else if (str.contains("$" + VAR_CAPSULE_DIR)) throw new IllegalStateException("The $" + VAR_CAPSULE_DIR + " variable cannot be expanded when the " + ATTR_EXTRACT + " attribute is set to false"); str = expandCommandLinePath(str); str = str.replaceAll("\\$" + VAR_CAPSULE_JAR, getJarPath()); str = str.replaceAll("\\$" + VAR_JAVA_HOME, javaHome != null ? javaHome : System.getProperty(PROP_JAVA_HOME)); str = str.replace('/', FILE_SEPARATOR.charAt(0)); return str; } private static String expandCommandLinePath(String str) { if (str == null) return null; // if (isWindows()) // return str; // else return str.startsWith("~/") ? str.replace("~", System.getProperty(PROP_USER_HOME)) : str; } private static String getApplicationArtifactId(String coords) { if (coords == null) return null; final String[] cs = coords.split(":"); if (cs.length < 2) throw new IllegalArgumentException("Illegal main artifact coordinates: " + coords); String id = cs[0] + "_" + cs[1]; if (cs.length > 2) id += "_" + cs[2]; return id; } private int getMinUpdateFor(String version) { final Map<String, String> m = getMapAttribute(ATTR_MIN_UPDATE_VERSION, null); if (m == null) return 0; final int[] ver = parseJavaVersion(version); for (Map.Entry<String, String> entry : m.entrySet()) { if (equals(ver, toInt(shortJavaVersion(entry.getKey()).split(DOT)), 3)) return Integer.parseInt(entry.getValue()); } return 0; } private static boolean anyPropertyDefined(String... props) { for (String prop : props) { if (System.getProperty(prop) != null) return true; } return false; } private static void println(String str) { System.err.println("CAPSULE: " + str); } private static void verbose(String str) { if (verbose) System.err.println("CAPSULE: " + str); } private static void debug(String str) { if (debug) System.err.println("CAPSULE: " + str); } /////////////////// file visitor /* * This is written in a funny way because we don't want to create any classes, even anonymous ones, so that this file will compile * to a single class file. */ private final Object fileVisitorLock = new Object(); private int fileVisitorMode; private Path fileVisitorStart; private List<Path> fileVisitorResult; private static final int FILE_VISITOR_MODE_NO_RECURSE = 0; private static final int FILE_VISITOR_MODE_PREORDER = 1; private static final int FILE_VISITOR_MODE_POSTORDER = 2; protected final List<Path> listDir(Path dir) { return listDir(dir, FILE_VISITOR_MODE_NO_RECURSE); } protected final List<Path> listDir(Path dir, int fileVisitorMode) { synchronized (fileVisitorLock) { this.fileVisitorMode = fileVisitorMode; List<Path> res = new ArrayList<>(); this.fileVisitorStart = dir; this.fileVisitorResult = res; try { Files.walkFileTree(dir, this); return res; } catch (IOException e) { throw new RuntimeException(e); } finally { this.fileVisitorStart = null; this.fileVisitorResult = null; this.fileVisitorMode = -1; } } } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if(fileVisitorStart.equals(dir)) return FileVisitResult.CONTINUE; if (fileVisitorMode == FILE_VISITOR_MODE_PREORDER) fileVisitorResult.add(dir); else if (fileVisitorMode == FILE_VISITOR_MODE_NO_RECURSE) { fileVisitorResult.add(dir); return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) throw exc; if (fileVisitorMode == FILE_VISITOR_MODE_POSTORDER) fileVisitorResult.add(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { fileVisitorResult.add(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { throw exc; } private static ProcessBuilder launchCapsule(Path path, List<String> cmdLine, String[] args) { try { final ClassLoader cl = new URLClassLoader(new URL[]{path.toUri().toURL()}, null); Class clazz; try { clazz = cl.loadClass(CUSTOM_CAPSULE_CLASS_NAME); } catch (ClassNotFoundException e) { clazz = cl.loadClass(Capsule.class.getName()); } final Object capsule; try { Constructor<?> ctor = clazz.getConstructor(Path.class, String[].class); ctor.setAccessible(true); capsule = ctor.newInstance(path, args); } catch (Exception e) { throw new RuntimeException("Could not launch custom capsule.", e); } final Method launch = clazz.getMethod("prepareForLaunch", List.class, String[].class); launch.setAccessible(true); return (ProcessBuilder) launch.invoke(capsule, cmdLine, args); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException | NoSuchMethodException e) { throw new RuntimeException(path + " does not appear to be a valid capsule.", e); } catch (IllegalAccessException e) { throw new AssertionError(); } catch (InvocationTargetException e) { final Throwable t = e.getTargetException(); if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; throw new RuntimeException(t); } } }
package car; import interfaces.OldCarCheck; import interfaces.OneYearOldCarCheck; import lombok.Data; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; @Data public class Car { public static final int MINIMAL_NUMBER_OF_OWNERS = 1; public static final int ONE_YEAR_OLD = 1; public static final int TWENTY_YEARS_OLD = 20; @NotNull Long price; @NotNull CarModel carModel; @Min.List({@Min(value = TWENTY_YEARS_OLD, groups = OldCarCheck.class), @Min(value = ONE_YEAR_OLD, groups = OneYearOldCarCheck.class)}) @Max(value = ONE_YEAR_OLD, groups = OneYearOldCarCheck.class) long age; @NotNull @Size(min = MINIMAL_NUMBER_OF_OWNERS) List<String> owners; }
package invtweaks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import invtweaks.api.container.ContainerSection; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; /** * Allows to perform various operations on the inventory and/or containers. Works in both single and multiplayer. * * @author Jimeo Wan */ public class InvTweaksContainerManager extends InvTweaksObfuscation { // TODO: Throw errors when the container isn't available anymore public static final int DROP_SLOT = -999; public static final int INVENTORY_SIZE = 36; public static final int HOTBAR_SIZE = 9; public static final int ACTION_TIMEOUT = 500; public static final int POLLING_DELAY = 3; private GuiContainer guiContainer; private Container container; private Map<ContainerSection, List<Slot>> slotRefs = new HashMap<ContainerSection, List<Slot>>(); private int clickDelay = 0; /** * Creates an container manager linked to the currently available container: - If a container GUI is open, the * manager gives access to this container contents. - If no GUI is open, the manager works as if the player's * inventory was open. * * @param mc Minecraft */ @SuppressWarnings({"unchecked"}) public InvTweaksContainerManager(Minecraft mc) { super(mc); GuiScreen currentScreen = mc.currentScreen; if(currentScreen instanceof GuiContainer) { guiContainer = (GuiContainer)currentScreen; container = guiContainer.inventorySlots; } else { container = mc.thePlayer.inventoryContainer; } initSlots(); } // TODO: Remove dependency on Minecraft class // TODO: Refactor the mouse-coverage stuff that needs the GuiContainer into a different class. public InvTweaksContainerManager(Minecraft mc, Container cont, GuiContainer gui) { super(mc); guiContainer = gui; container = cont; initSlots(); } private void initSlots() { slotRefs = InvTweaksObfuscation.getContainerSlotMap(container); if(slotRefs == null) { slotRefs = new HashMap<ContainerSection, List<Slot>>(); } // TODO: Detect if there is a big enough unassigned section for inventory. List<Slot> slots = (List<Slot>)container.inventorySlots; int size = slots.size(); if(size >= InvTweaksConst.INVENTORY_SIZE && !slotRefs.containsKey(ContainerSection.INVENTORY)) { slotRefs.put(ContainerSection.INVENTORY, slots.subList(size - InvTweaksConst.INVENTORY_SIZE, size)); slotRefs.put(ContainerSection.INVENTORY_NOT_HOTBAR, slots.subList(size - InvTweaksConst.INVENTORY_SIZE, size - HOTBAR_SIZE)); slotRefs.put(ContainerSection.INVENTORY_HOTBAR, slots.subList(size - HOTBAR_SIZE, size)); } } /** * Moves a stack from source to destination, adapting the behavior according to the context: - If destination is * empty, the source stack is moved. - If the items can be merged, as much items are possible are put in the * destination, and the eventual remains go back to the source. - If the items cannot be merged, they are swapped. * * @param srcSection The source section * @param srcIndex The source slot * @param destSection The destination section * @param destIndex The destination slot * * @return false if the source slot is empty or the player is holding an item that couln't be put down. * * @throws TimeoutException */ // TODO: Server helper directly implementing this as a swap without the need for intermediate slots. public boolean move(ContainerSection srcSection, int srcIndex, ContainerSection destSection, int destIndex) { ItemStack srcStack = getItemStack(srcSection, srcIndex); ItemStack destStack = getItemStack(destSection, destIndex); if(srcStack == null && destIndex != DROP_SLOT) { return false; } else if(srcSection == destSection && srcIndex == destIndex) { return true; } // Mod support -- some mods play tricks with slots to display an item but not let it be interacted with. // (Specifically forestry backpack UI) if(destIndex != DROP_SLOT) { Slot destSlot = getSlot(destSection, destIndex); if(!destSlot.isItemValid(srcStack)) { return false; } } // Put hold item down if(getHeldStack() != null) { int firstEmptyIndex = getFirstEmptyIndex(ContainerSection.INVENTORY); if(firstEmptyIndex != -1) { leftClick(ContainerSection.INVENTORY, firstEmptyIndex); } else { return false; } } // Use intermediate slot if we have to swap tools, maps, etc. if(destStack != null && srcStack.itemID == destStack.itemID && (srcStack.getMaxStackSize() == 1 || srcStack.hasTagCompound() || destStack.hasTagCompound() )) { int intermediateSlot = getFirstEmptyUsableSlotNumber(); ContainerSection intermediateSection = getSlotSection(intermediateSlot); int intermediateIndex = getSlotIndex(intermediateSlot); if(intermediateIndex != -1) { Slot interSlot = getSlot(intermediateSection, intermediateIndex); if(!interSlot.isItemValid(destStack)) { return false; } Slot srcSlot = getSlot(srcSection, srcIndex); if(!srcSlot.isItemValid(destStack)) { return false; } // Step 1/3: Dest > Int leftClick(destSection, destIndex); leftClick(intermediateSection, intermediateIndex); // Step 2/3: Src > Dest leftClick(srcSection, srcIndex); leftClick(destSection, destIndex); // Step 3/3: Int > Src leftClick(intermediateSection, intermediateIndex); leftClick(srcSection, srcIndex); } else { return false; } } // Normal move else { leftClick(srcSection, srcIndex); leftClick(destSection, destIndex); if(getHeldStack() != null) { // Only return to original slot if it can be placed in that slot. // (Ex. crafting/furnace outputs) Slot srcSlot = getSlot(srcSection, srcIndex); if(srcSlot.isItemValid(getHeldStack())) { leftClick(srcSection, srcIndex); } else { // If the item cannot be placed in its original slot, move to an empty slot. int firstEmptyIndex = getFirstEmptyIndex(ContainerSection.INVENTORY); if(firstEmptyIndex != -1) { leftClick(ContainerSection.INVENTORY, firstEmptyIndex); } // else leave there because we have nowhere to put it. } } } return true; } /** * Moves some items from source to destination. * * @param srcSection The source section * @param srcIndex The source slot * @param destSection The destination section * @param destIndex The destination slot * @param amount The amount of items to move. If <= 0, does nothing. If > to the source stack size, moves as * much as possible from the stack size. If not all can be moved to the destination, only moves * as much as possible. * * @return false if the destination slot is already occupied by a different item (meaning items cannot be moved to * destination). * * @throws TimeoutException */ // TODO: Server helper directly implementing this. public boolean moveSome(ContainerSection srcSection, int srcIndex, ContainerSection destSection, int destIndex, int amount) { ItemStack source = getItemStack(srcSection, srcIndex); if(source == null || srcSection == destSection && srcIndex == destIndex) { return true; } ItemStack destination = getItemStack(srcSection, srcIndex); int sourceSize = source.stackSize; int movedAmount = Math.min(amount, sourceSize); if(destination == null || InvTweaksObfuscation.areItemStacksEqual(source, destination)) { leftClick(srcSection, srcIndex); for(int i = 0; i < movedAmount; i++) { rightClick(destSection, destIndex); } if(movedAmount < sourceSize) { leftClick(srcSection, srcIndex); } return true; } else { return false; } } // TODO: Server helper directly implementing this. public boolean drop(ContainerSection srcSection, int srcIndex) { return move(srcSection, srcIndex, null, DROP_SLOT); } // TODO: Server helper directly implementing this. public boolean dropSome(ContainerSection srcSection, int srcIndex, int amount) { return moveSome(srcSection, srcIndex, null, DROP_SLOT, amount); } /** * If an item is in hand (= attached to the cursor), puts it down. * * @return true unless the item could not be put down * * @throws Exception */ public boolean putHoldItemDown(ContainerSection destSection, int destIndex) { ItemStack heldStack = getHeldStack(); if(heldStack != null) { if(getItemStack(destSection, destIndex) == null) { click(destSection, destIndex, false); return true; } return false; } return true; } public void leftClick(ContainerSection section, int index) { click(section, index, false); } public void rightClick(ContainerSection section, int index) { click(section, index, true); } public void click(ContainerSection section, int index, boolean rightClick) { //System.out.println("Click " + section + ":" + index); // Click! (we finally call the Minecraft code) int slot = indexToSlot(section, index); if(slot != -1) { clickInventory(getPlayerController(), getWindowId(container), // Select container slot, // Targeted slot (rightClick) ? 1 : 0, // Click 0, // Normal click getThePlayer()); } if(clickDelay > 0) { try { Thread.sleep(clickDelay); } catch(InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // TODO: Move these mouse things somewhere else @SideOnly(Side.CLIENT) public Slot getSlotAtMousePosition() { // Copied from GuiContainer if(guiContainer != null) { int x = getMouseX(); int y = getMouseY(); for(int k = 0; k < getSlots(container).size(); k++) { Slot slot = (Slot) getSlots(container).get(k); if(getIsMouseOverSlot(slot, x, y)) { return slot; } } return null; } else { return null; } } @SideOnly(Side.CLIENT) public boolean getIsMouseOverSlot(Slot slot) { return getIsMouseOverSlot(slot, getMouseX(), getMouseY()); } @SideOnly(Side.CLIENT) private boolean getIsMouseOverSlot(Slot slot, int x, int y) { // Copied from GuiContainer if(guiContainer != null) { x -= getGuiX(guiContainer); y -= getGuiY(guiContainer); return x >= getXDisplayPosition(slot) - 1 && x < getXDisplayPosition(slot) + 16 + 1 && y >= getYDisplayPosition(slot) - 1 && y < getYDisplayPosition(slot) + 16 + 1; } else { return false; } } @SideOnly(Side.CLIENT) private int getMouseX() { return (Mouse.getEventX() * getWindowWidth(guiContainer)) / getDisplayWidth(); } @SideOnly(Side.CLIENT) private int getMouseY() { return getWindowHeight(guiContainer) - (Mouse.getEventY() * getWindowHeight(guiContainer)) / getDisplayHeight() - 1; } public boolean hasSection(ContainerSection section) { return slotRefs.containsKey(section); } public List<Slot> getSlots(ContainerSection section) { return slotRefs.get(section); } /** * @return The size of the whole container */ public int getSize() { int result = 0; for(List<Slot> slots : slotRefs.values()) { result += slots.size(); } return result; } /** * Returns the size of a section of the container. * * @param section * * @return The size, or 0 if there is no such section. */ public int getSize(ContainerSection section) { if(hasSection(section)) { return slotRefs.get(section).size(); } else { return 0; } } /** * @param section * * @return -1 if no slot is free */ public int getFirstEmptyIndex(ContainerSection section) { int i = 0; for(Slot slot : slotRefs.get(section)) { if(!hasStack(slot)) { return i; } i++; } return -1; } /** * @param slot * * @return true if the specified slot exists and is empty, false otherwise. */ public boolean isSlotEmpty(ContainerSection section, int slot) { if(hasSection(section)) { return getItemStack(section, slot) == null; } else { return false; } } public Slot getSlot(ContainerSection section, int index) { List<Slot> slots = slotRefs.get(section); if(slots != null) { return slots.get(index); } else { return null; } } /** * @param slotNumber * * @return -1 if not found */ public int getSlotIndex(int slotNumber) { return getSlotIndex(slotNumber, false); } /** * @param slotNumber * @param preferInventory Set to true if you prefer to have the index according to the whole inventory, instead of a * more specific section (hotbar/not hotbar) * * @return Full index of slot in the container */ public int getSlotIndex(int slotNumber, boolean preferInventory) { // TODO Caching with getSlotSection for(ContainerSection section : slotRefs.keySet()) { if(!preferInventory && section != ContainerSection.INVENTORY || (preferInventory && section != ContainerSection.INVENTORY_NOT_HOTBAR && section != ContainerSection.INVENTORY_HOTBAR)) { int i = 0; for(Slot slot : slotRefs.get(section)) { if(getSlotNumber(slot) == slotNumber) { return i; } i++; } } } return -1; } /** * Note: Prefers INVENTORY_HOTBAR/NOT_HOTBAR instead of INVENTORY. * * @param slotNumber * * @return null if the slot number is invalid. */ public ContainerSection getSlotSection(int slotNumber) { // TODO Caching with getSlotIndex for(ContainerSection section : slotRefs.keySet()) { if(section != ContainerSection.INVENTORY) { for(Slot slot : slotRefs.get(section)) { if(getSlotNumber(slot) == slotNumber) { return section; } } } } return null; } /** * Returns an ItemStack from the wanted section and slot. * * @param section * @param index * * @return An ItemStack or null. */ public ItemStack getItemStack(ContainerSection section, int index) throws NullPointerException, IndexOutOfBoundsException { int slot = indexToSlot(section, index); if(slot >= 0 && slot < getSlots(container).size()) { return getSlotStack(container, slot); } else { return null; } } public Container getContainer() { return container; } private int getFirstEmptyUsableSlotNumber() { for(ContainerSection section : slotRefs.keySet()) { for(Slot slot : slotRefs.get(section)) { // Use only standard slot (to make sure // we can freely put and remove items there) if(isBasicSlot(slot) && !hasStack(slot)) { return getSlotNumber(slot); } } } return -1; } /** * Converts section/index values to slot ID. * * @param section * @param index * * @return -1 if not found */ private int indexToSlot(ContainerSection section, int index) { if(index == DROP_SLOT) { return DROP_SLOT; } if(hasSection(section)) { Slot slot = slotRefs.get(section).get(index); if(slot != null) { return getSlotNumber(slot); } else { return -1; } } else { return -1; } } public void setClickDelay(int delay) { this.clickDelay = delay; } }
package ljdp.minechem.api.core; import static ljdp.minechem.api.core.EnumElement.*; import java.util.ArrayList; import java.util.Random; // Na2OLi2O(SiO2)2(B2O3)3H2O // MOLECULE IDS MUST BE CONTINIOUS OTHERWISE THE ARRAY WILL BE MISALIGNED. public enum EnumMolecule { cellulose(0, "Cellulose", new Element(C, 6), new Element(H, 10), new Element(O, 5)), water(1, "Water", new Element(H, 2), new Element(O)), carbonDioxide(2, "Carbon Dioxide", new Element(C), new Element(O, 2)), nitrogenDioxide(3, "Nitrogen Dioxide", new Element(N), new Element(O, 2)), toluene(4, "Toluene", new Element(C, 7), new Element(H, 8)), potassiumNitrate(5, "Potassium Nitrate", new Element(K), new Element(N), new Element(O, 3)), tnt(6, "Trinitrotoluene", new Element(C, 6), new Element(H, 2), new Molecule(nitrogenDioxide, 3), new Molecule(toluene)), siliconDioxide(7, "Silicon Dioxide", new Element(Si), new Element(O, 2)), calcite(8, "Calcite", new Element(Ca), new Element(C), new Element(O, 3)), pyrite(9, "Pyrite", new Element(Fe), new Element(S, 2)), nepheline(10, "Nepheline", new Element(Al), new Element(Si), new Element(O, 4)), sulfate(11, "Sulfate (ion)", new Element(S), new Element(O, 4)), noselite(12, "Noselite", new Element(Na, 8), new Molecule(nepheline, 6), new Molecule(sulfate)), sodalite(13, "Sodalite", new Element(Na, 8), new Molecule(nepheline, 6), new Element(Cl, 2)), nitrate(14, "Nitrate (ion)", new Element(N), new Element(O, 3)), carbonate(15, "Carbonate (ion)", new Element(C), new Element(O, 3)), cyanide(16, "Potassium Cyanide", new Element(K), new Element(C), new Element(N)), phosphate(17, "Phosphate (ion)", new Element(P), new Element(O, 4)), acetate(18, "Acetate (ion)", new Element(C, 2), new Element(H, 3), new Element(O, 2)), chromate(19, "Chromate (ion)", new Element(Cr), new Element(O, 4)), hydroxide(20, "Hydroxide (ion)", new Element(O), new Element(H)), ammonium(21, "Ammonium (ion)", new Element(N), new Element(H, 4)), hydronium(22, "Hydronium (ion)", new Element(H, 3), new Element(O)), peroxide(23, "Hydrogen Peroxide", new Element(H, 2), new Element(O, 2)), calciumOxide(24, "Calcium Oxide", new Element(Ca), new Element(O)), calciumCarbonate(25, "Calcium Carbonate", new Element(Ca), new Molecule(carbonate)), magnesiumCarbonate(26, "Magnesium Carbonate", new Element(Mg), new Molecule(carbonate)), lazurite(27, "Lazurite", new Element(Na, 8), new Molecule(nepheline), new Molecule(sulfate)), isoprene(28, "Isoprene", new Element(C, 5), new Element(H, 8)), butene(29, "Butene", new Element(C, 4), new Element(H, 8)), polyisobutylene(30, "Polyisobutylene Rubber", new Molecule(butene, 16), new Molecule(isoprene)), malicAcid(31, "Malic Acid", new Element(C, 4), new Element(H, 6), new Element(O, 5)), vinylChloride(32, "Vinyl Chloride Monomer", new Element(C, 2), new Element(H, 3), new Element(Cl)), polyvinylChloride(33, "Polyvinyl Chloride", new Molecule(vinylChloride, 64)), methamphetamine(34, "Methamphetamine", new Element(C, 10), new Element(H, 15), new Element(N)), psilocybin(35, "Psilocybin", new Element(C, 12), new Element(H, 17), new Element(N, 2), new Element(O, 4), new Element(P)), iron3oxide(36, "Iron (III) Oxide", new Element(Fe, 2), new Element(O, 3)), strontiumNitrate(37, "Strontium Nitrate", new Element(Sr), new Molecule(nitrate, 2)), magnetite(38, "Magnetite", new Element(Fe, 3), new Element(O, 4)), magnesiumOxide(39, "Magnesium Oxide", new Element(Mg), new Element(O)), cucurbitacin(40, "Cucurbitacin", new Element(C, 30), new Element(H, 42), new Element(O, 7)), asparticAcid(41, "Aspartic Acid", new Element(C, 4), new Element(H, 7), new Element(N), new Element(O, 4)), hydroxylapatite(42, "Hydroxylapatite", new Element(Ca, 5), new Molecule(phosphate, 3), new Element(O), new Element(H)), alinine(43, "Alinine (amino acid)", new Element(C, 3), new Element(H, 7), new Element(N), new Element(O, 2)), glycine(44, "Glycine (amino acid)", new Element(C, 2), new Element(H, 5), new Element(N), new Element(O, 2)), serine(45, "Serine (amino acid)", new Element(C, 3), new Element(H, 7), new Molecule(nitrate)), mescaline(46, "Mescaline", new Element(C, 11), new Element(H, 17), new Molecule(nitrate)), methyl(47, "Methyl (ion)", new Element(C), new Element(H, 3)), methylene(48, "Methylene (ion)", new Element(C), new Element(H, 2)), cyanoacrylate(49, "Cyanoacrylate", new Molecule(methyl), new Molecule(methylene), new Element(C, 3), new Element(N), new Element(H), new Element(O, 2)), polycyanoacrylate(50, "Poly-cyanoacrylate", new Molecule(cyanoacrylate, 3)), redPigment(51, "Cobalt(II) nitrate", new Element(Co), new Molecule(nitrate, 2)), orangePigment(52, "Potassium Dichromate", new Element(K, 2), new Element(Cr, 2), new Element(O, 7)), yellowPigment(53, "Potassium Chromate", new Element(Cr), new Element(K, 2), new Element(O, 4)), limePigment(54, "Nickel(II) Chloride", new Element(Ni), new Element(Cl, 2)), lightbluePigment(55, "Copper(II) Sulfate", new Element(Cu), new Molecule(sulfate)), purplePigment(56, "Potassium Permanganate", new Element(K), new Element(Mn), new Element(O, 4)), greenPigment(57, "Zinc Green", new Element(Co), new Element(Zn), new Element(O, 2)), blackPigment(58, "Carbon Black", new Element(C), new Element(H, 2), new Element(O)), whitePigment(59, "Titanium Dioxide", new Element(Ti), new Element(O, 2)), metasilicate(60, "Metasilicate", new Element(Si), new Element(O, 3)), beryl(61, "Beryl", new Element(Be, 3), new Element(Al, 2), new Molecule(metasilicate, 6)), ethanol(62, "Ethyl Alchohol", new Element(C, 2), new Element(H, 6), new Element(O)), amphetamine(63, "Aphetamine", new Element(C, 9), new Element(H, 13), new Element(N)), theobromine(64, "Theobromine", new Element(C, 7), new Element(H, 8), new Element(N, 4), new Element(O, 2)), starch(65, "Starch", new Molecule(cellulose, 2), new Molecule(cellulose, 1)), sucrose(66, "Sucrose", new Element(C, 12), new Element(H, 22), new Element(O, 11)), muscarine(67, "Muscarine", new Element(C, 9), new Element(H, 20), new Element(N), new Element(O, 2)), aluminiumOxide(68, "Aluminium Oxide", new Element(Al, 2), new Element(O, 3)), fullrene(69, "Carbon Nanotubes", new Element(C, 64), new Element(C, 64), new Element(C, 64), new Element(C, 64)), keratin(70, "Keratin", new Element(C, 2), new Molecule(water), new Element(N)), penicillin(71, "Penicillin", new Element(C, 16), new Element(H, 18), new Element(N, 2), new Element(O, 4), new Element(S)), testosterone(72, "Testosterone", new Element(C, 19), new Element(H, 28), new Element(O, 2)), kaolinite(73, "Kaolinite", new Element(Al, 2), new Element(Si, 2), new Element(O, 5), new Molecule(hydroxide, 4)), fingolimod(74, "Fingolimod", new Element(C, 19), new Element(H, 33), new Molecule(nitrogenDioxide)), // LJDP, You ment to say fingolimod not myrocin. arginine(75, "Arginine (amino acid)", new Element(C, 6), new Element(H, 14), new Element(N, 4), new Element(O, 2)), shikimicAcid(76, "Shikimic Acid", new Element(C, 7), new Element(H, 10), new Element(O, 5)), sulfuricAcid(77, "Sulfuric Acid", new Element(H, 2), new Element(S), new Element(O, 4)), glyphosate(78, "Glyphosate", new Element(C, 3), new Element(H, 8), new Element(N), new Element(O, 5), new Element(P)), quinine(79, "Quinine", new Element(C, 20), new Element(H, 24), new Element(N, 2), new Element(O, 2)), ddt(80, "DDT", new Element(C, 14), new Element(H, 9), new Element(Cl, 5)), dota(81, "DOTA", new Element(C, 16), new Element(H, 28), new Element(N, 4), new Element(O, 8)), poison(82, "T-2 Mycotoxin", new Element(C, 24), new Element(H, 34), new Element(O, 9)), salt(83, "Salt", new Element(Na, 1), new Element(Cl, 1)), nhthree(84, "Ammonia", new Element(N, 1), new Element(H, 3)), nod(85, "Nodularin", new Element(C, 41), new Element(H, 60), new Element(N, 8), new Element(O, 10)), ttx(86, "TTX (Tetrodotoxin)", new Element(C, 11), new Element(H, 11), new Element(N, 3), new Element(O, 8)), afroman(87, "THC", new Element(C, 21), new Element(H, 30), new Element(O, 2)), mt(88, "Methylcyclopentadienyl Manganese Tricarbonyl", new Element(C, 9), new Element(H, 7), new Element(Mn, 1), new Element(O, 3)), // Level 1 buli(89, "Tert-Butyllithium", new Element(Li, 1), new Element(C, 4), new Element(H, 9)), // Level 2 plat(90, "Chloroplatinic acid", new Element(H, 2), new Element(Pt, 1), new Element(Cl, 6)), // Level 3 phosgene(91, "Phosgene", new Element(C, 1), new Element(O, 1), new Element(Cl, 2)), aalc(92, "Allyl alcohol", new Element(C, 3), new Element(H, 6), new Element(O, 1)), hist(93, "Diphenhydramine", new Element(C, 17), new Element(H, 21), new Element(N), new Element(O)), pal2(94, "Batrachotoxin", new Element(C, 31), new Element(H, 42), new Element(N, 2), new Element(O, 6)), ret(95, "Retinol", new Element(C, 20), new Element(H, 30), new Element(O)), stevenk(96, "Xylitol", new Element(C, 5), new Element(H, 12), new Element(O, 5)), weedex(97, "Aminocyclopyrachlor", new Element(C,8), new Element(H,8), new Element(Cl), new Element(N,3), new Element(O,2)), biocide(98, "Ptaquiloside", new Element(C, 20), new Element(H, 30), new Element(O, 8)), xanax(99, "Alprazolam", new Element(C,17), new Element(H,13), new Element(Cl), new Element(N,4)), hcl(100, "Hydrogen Chloride", new Element(H), new Element(Cl)), redrocks(101, "Cocaine - Freebase", new Element(C,17), new Element(H,21), new element(N), new Element(O,4)), coke(102, "Cocaine Hydrochloride", new Molecule(redrocks), new Molecule(hcl)) ; public static EnumMolecule[] molecules = values(); private final String descriptiveName; private final ArrayList<Chemical> components; private int id; public float red; public float green; public float blue; public float red2; public float green2; public float blue2; EnumMolecule(int id, String descriptiveName, Chemical... chemicals) { this.id = id; this.components = new ArrayList<Chemical>(); this.descriptiveName = descriptiveName; for (Chemical chemical : chemicals) { this.components.add(chemical); } Random random = new Random(id); this.red = random.nextFloat(); this.green = random.nextFloat(); this.blue = random.nextFloat(); this.red2 = random.nextFloat(); this.green2 = random.nextFloat(); this.blue2 = random.nextFloat(); } public static EnumMolecule getById(int id) { for (EnumMolecule molecule : molecules) { if (molecule.id == id) return molecule; } return null; } public int id() { return this.id; } public String descriptiveName() { return this.descriptiveName; } public ArrayList<Chemical> components() { return this.components; } }
package org.zkoss.ganttz; import static org.zkoss.ganttz.i18n.I18nHelper._; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.zkoss.ganttz.adapters.IDisabilityConfiguration; import org.zkoss.ganttz.adapters.PlannerConfiguration; import org.zkoss.ganttz.data.Dependency; import org.zkoss.ganttz.data.GanttDiagramGraph; import org.zkoss.ganttz.data.Position; import org.zkoss.ganttz.data.Task; import org.zkoss.ganttz.data.GanttDiagramGraph.IGraphChangeListener; import org.zkoss.ganttz.extensions.ICommand; import org.zkoss.ganttz.extensions.ICommandOnTask; import org.zkoss.ganttz.extensions.IContext; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.timetracker.TimeTrackerComponent; import org.zkoss.ganttz.timetracker.TimeTrackerComponentWithoutColumns; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.ComponentsFinder; import org.zkoss.ganttz.util.LongOperationFeedback; import org.zkoss.ganttz.util.OnZKDesktopRegistry; import org.zkoss.ganttz.util.LongOperationFeedback.ILongOperation; import org.zkoss.ganttz.util.script.IScriptsRegister; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zk.ui.util.Clients; import org.zkoss.zul.Button; import org.zkoss.zul.ListModel; import org.zkoss.zul.Separator; import org.zkoss.zul.SimpleListModel; public class Planner extends HtmlMacroComponent { public static void registerNeededScripts() { IScriptsRegister register = getScriptsRegister(); register.register(ScriptsRequiredByPlanner.class); } private static IScriptsRegister getScriptsRegister() { return OnZKDesktopRegistry.getLocatorFor(IScriptsRegister.class) .retrieve(); } public static boolean guessContainersExpandedByDefaultGivenPrintParameters( Map<String, String> printParameters) { return guessContainersExpandedByDefault(convertToURLParameters(printParameters)); } private static Map<String, String[]> convertToURLParameters( Map<String, String> printParameters) { Map<String, String[]> result = new HashMap<String, String[]>(); for (Entry<String, String> each : printParameters.entrySet()) { result.put(each.getKey(), new String[] { each.getValue() }); } return result; } public static boolean guessContainersExpandedByDefault( Map<String, String[]> queryURLParameters) { String[] values = queryURLParameters.get("expanded"); if (values == null) { return false; } return toLowercaseSet(values).contains("all"); } private static Set<String> toLowercaseSet(String[] values) { Set<String> result = new HashSet<String>(); for (String each : values) { result.add(each.toLowerCase()); } return result; } private GanttDiagramGraph diagramGraph; private LeftPane leftPane; private GanttPanel ganttPanel; private List<? extends CommandContextualized<?>> contextualizedGlobalCommands; private CommandContextualized<?> goingDownInLastArrowCommand; private List<? extends CommandOnTaskContextualized<?>> commandsOnTasksContextualized; private CommandOnTaskContextualized<?> doubleClickCommand; private FunctionalityExposedForExtensions<?> context; private transient IDisabilityConfiguration disabilityConfiguration; private boolean isShowingCriticalPath = false; private ZoomLevel initialZoomLevel = null; public Planner() { registerNeededScripts(); } TaskList getTaskList() { if (ganttPanel == null) { return null; } List<Object> children = ganttPanel.getChildren(); return ComponentsFinder.findComponentsOfType(TaskList.class, children).get(0); } public int getTaskNumber() { return getTaskList().getTasksNumber(); } public int getAllTasksNumber() { return diagramGraph.getTasks().size(); } public String getContextPath() { return Executions.getCurrent().getContextPath(); } public DependencyList getDependencyList() { if (ganttPanel == null) { return null; } List<Object> children = ganttPanel.getChildren(); List<DependencyList> found = ComponentsFinder.findComponentsOfType(DependencyList.class, children); if (found.isEmpty()) { return null; } return found.get(0); } public void addTasks(Position position, Collection<? extends Task> newTasks) { TaskList taskList = getTaskList(); if (taskList != null && leftPane != null) { taskList.addTasks(position, newTasks); leftPane.addTasks(position, newTasks); } } public void addTask(Position position, Task task) { addTasks(position, Arrays.asList(task)); } void addDependencies(Collection<? extends Dependency> dependencies) { DependencyList dependencyList = getDependencyList(); if (dependencyList == null) { return; } for (DependencyComponent d : getTaskList().asDependencyComponents( dependencies)) { dependencyList.addDependencyComponent(d); } } public ListModel getZoomLevels() { return new SimpleListModel(ZoomLevel.values()); } public void setZoomLevel(final ZoomLevel zoomLevel) { if (ganttPanel == null) { return; } ganttPanel.setZoomLevel(zoomLevel); } public void zoomIncrease() { if (ganttPanel == null) { return; } LongOperationFeedback.execute(ganttPanel, new ILongOperation() { @Override public String getName() { return _("increasing zoom"); } @Override public void doAction() throws Exception { ganttPanel.zoomIncrease(); } }); } public void zoomDecrease() { if (ganttPanel == null) { return; } LongOperationFeedback.execute(ganttPanel, new ILongOperation() { @Override public String getName() { return _("decreasing zoom"); } @Override public void doAction() throws Exception { ganttPanel.zoomDecrease(); } }); } public <T> void setConfiguration(PlannerConfiguration<T> configuration) { if (configuration == null) { return; } this.diagramGraph = new GanttDiagramGraph(configuration .getStartConstraints(), configuration.getEndConstraints(), configuration.isDependenciesConstraintsHavePriority()); FunctionalityExposedForExtensions<T> newContext = new FunctionalityExposedForExtensions<T>( this, configuration, diagramGraph); this.contextualizedGlobalCommands = contextualize(newContext, configuration.getGlobalCommands()); this.commandsOnTasksContextualized = contextualize(newContext, configuration.getCommandsOnTasks()); goingDownInLastArrowCommand = contextualize(newContext, configuration .getGoingDownInLastArrowCommand()); doubleClickCommand = contextualize(newContext, configuration .getDoubleClickCommand()); this.context = newContext; this.disabilityConfiguration = configuration; resettingPreviousComponentsToNull(); newContext.add(configuration.getData()); setupComponents(); setAt("insertionPointLeftPanel", leftPane); leftPane.afterCompose(); setAt("insertionPointRightPanel", ganttPanel); ganttPanel.afterCompose(); leftPane.setGoingDownInLastArrowCommand(goingDownInLastArrowCommand); TimeTrackerComponent timetrackerheader = new TimeTrackerComponentWithoutColumns( ganttPanel.getTimeTracker(), "timetrackerheader"); setAt("insertionPointTimetracker", timetrackerheader); timetrackerheader.afterCompose(); Component chartComponent = configuration.getChartComponent(); if (chartComponent != null) { setAt("insertionPointChart", chartComponent); } if (!configuration.isCriticalPathEnabled()) { Button showCriticalPathButton = (Button) getFellow("showCriticalPath"); showCriticalPathButton.setVisible(false); } } private void resettingPreviousComponentsToNull() { this.ganttPanel = null; this.leftPane = null; } private void setAt(String insertionPointId, Component component) { Component insertionPoint = getFellow(insertionPointId); insertionPoint.getChildren().clear(); insertionPoint.appendChild(component); } private <T> List<CommandOnTaskContextualized<T>> contextualize( FunctionalityExposedForExtensions<T> context, List<ICommandOnTask<T>> commands) { List<CommandOnTaskContextualized<T>> result = new ArrayList<CommandOnTaskContextualized<T>>(); for (ICommandOnTask<T> c : commands) { result.add(contextualize(context, c)); } return result; } private <T> CommandOnTaskContextualized<T> contextualize( FunctionalityExposedForExtensions<T> context, ICommandOnTask<T> commandOnTask) { return CommandOnTaskContextualized.create(commandOnTask, context .getMapper(), context); } private <T> CommandContextualized<T> contextualize(IContext<T> context, ICommand<T> command) { if (command == null) { return null; } return CommandContextualized.create(command, context); } private <T> List<CommandContextualized<T>> contextualize( IContext<T> context, Collection<? extends ICommand<T>> commands) { ArrayList<CommandContextualized<T>> result = new ArrayList<CommandContextualized<T>>(); for (ICommand<T> command : commands) { result.add(contextualize(context, command)); } return result; } private void setupComponents() { insertGlobalCommands(); this.leftPane = new LeftPane(this.diagramGraph.getTopLevelTasks()); this.ganttPanel = new GanttPanel(this.context, commandsOnTasksContextualized, doubleClickCommand, disabilityConfiguration); Button button = (Button) getFellow("btnPrint"); button.setDisabled(!context.isPrintEnabled()); } @SuppressWarnings("unchecked") private void insertGlobalCommands() { Component toolbar = getToolbar(); Component firstSeparator = getFirstSeparatorFromToolbar(); toolbar.getChildren().removeAll(getBefore(toolbar, firstSeparator)); for (CommandContextualized<?> c : contextualizedGlobalCommands) { toolbar.insertBefore(c.toButton(), firstSeparator); } } @SuppressWarnings("unchecked") private List<Component> getBefore(Component parent, Component child) { List<Component> children = parent.getChildren(); List<Component> result = new ArrayList<Component>(); for (Component object : children) { if (object == child) { break; } result.add(object); } return result; } @SuppressWarnings("unchecked") private Component getFirstSeparatorFromToolbar() { Component toolbar = getToolbar(); List<Component> children = toolbar.getChildren(); List<Separator> separators = ComponentsFinder .findComponentsOfType( Separator.class, children); return separators.get(0); } private Component getToolbar() { Component toolbar = getFellow("toolbar"); return toolbar; } void removeTask(Task task) { TaskList taskList = getTaskList(); taskList.remove(task); getDependencyList().taskRemoved(task); leftPane.taskRemoved(task); setHeight(getHeight());// forcing smart update taskList.adjustZoomColumnsHeight(); getDependencyList().redrawDependencies(); } @Override public void afterCompose() { super.afterCompose(); } public TimeTracker getTimeTracker() { return ganttPanel.getTimeTracker(); } private IGraphChangeListener showCriticalPathOnChange = new IGraphChangeListener() { @Override public void execute() { context.showCriticalPath(); } }; private boolean containersExpandedByDefault = false; public void showCriticalPath() { Button showCriticalPathButton = (Button) getFellow("showCriticalPath"); if (disabilityConfiguration.isCriticalPathEnabled()) { if (isShowingCriticalPath) { context.hideCriticalPath(); diagramGraph.removePostGraphChangeListener(showCriticalPathOnChange); showCriticalPathButton.setSclass("planner-command"); showCriticalPathButton.setTooltiptext(_("Show critical path")); } else { context.showCriticalPath(); diagramGraph.addPostGraphChangeListener(showCriticalPathOnChange); showCriticalPathButton.setSclass("planner-command clicked"); showCriticalPathButton.setTooltiptext(_("Hide critical path")); } isShowingCriticalPath = !isShowingCriticalPath; } } public void showAllLabels() { Button showAllLabelsButton = (Button) getFellow("showAllLabels"); if (showAllLabelsButton.getSclass().equals( "planner-command show-labels")) { Clients.evalJavaScript("zkTasklist.showAllTooltips();"); showAllLabelsButton .setSclass("planner-command show-labels clicked"); } else { Clients.evalJavaScript("zkTasklist.hideAllTooltips();"); showAllLabelsButton.setSclass("planner-command show-labels"); } } public void showAllResources() { Button showAllLabelsButton = (Button) getFellow("showAllResources"); if (showAllLabelsButton.getSclass().equals( "planner-command show-resources")) { Clients.evalJavaScript("zkTasklist.showResourceTooltips();"); showAllLabelsButton .setSclass("planner-command show-resources clicked"); } else { Clients.evalJavaScript("zkTasklist.hideResourceTooltips();"); showAllLabelsButton.setSclass("planner-command show-resources"); } } public void print() { // Pending to raise print configuration popup. Information retrieved // should be passed as parameter to context print method context.print(); } public ZoomLevel getZoomLevel() { if (ganttPanel == null) { return initialZoomLevel != null ? initialZoomLevel : ZoomLevel.DETAIL_ONE; } return ganttPanel.getTimeTracker().getDetailLevel(); } public boolean isInitialZoomLevelAlreadySet() { return this.initialZoomLevel != null; } public void setInitialZoomLevel(final ZoomLevel zoomLevel) { this.initialZoomLevel = zoomLevel; } public boolean areContainersExpandedByDefault() { return containersExpandedByDefault; } public void setAreContainersExpandedByDefault( boolean containersExpandedByDefault) { this.containersExpandedByDefault = containersExpandedByDefault; } }
package org.zkoss.ganttz; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.zkoss.ganttz.adapters.PlannerConfiguration; import org.zkoss.ganttz.data.Dependency; import org.zkoss.ganttz.data.GanttDiagramGraph; import org.zkoss.ganttz.data.Position; import org.zkoss.ganttz.data.Task; import org.zkoss.ganttz.extensions.ICommand; import org.zkoss.ganttz.extensions.ICommandOnTask; import org.zkoss.ganttz.extensions.IContext; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.util.ComponentsFinder; import org.zkoss.ganttz.util.OnZKDesktopRegistry; import org.zkoss.ganttz.util.script.IScriptsRegister; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zul.Separator; public class Planner extends HtmlMacroComponent { private GanttDiagramGraph diagramGraph = new GanttDiagramGraph(); private LeftPane leftPane; private GanttPanel ganttPanel; private List<? extends CommandContextualized<?>> contextualizedGlobalCommands; private CommandContextualized<?> goingDownInLastArrowCommand; private List<? extends CommandOnTaskContextualized<?>> commandsOnTasksContextualized; private CommandOnTaskContextualized<?> editTaskCommand; private FunctionalityExposedForExtensions<?> context; public Planner() { registerNeededScripts(); } private void registerNeededScripts() { IScriptsRegister register = getScriptsRegister(); register.register(ScriptsRequiredByPlanner.class); } TaskList getTaskList() { if (ganttPanel == null) return null; List<Object> children = ganttPanel.getChildren(); return ComponentsFinder.findComponentsOfType(TaskList.class, children).get(0); } public String getContextPath() { return Executions.getCurrent().getContextPath(); } public DependencyList getDependencyList() { if (ganttPanel == null) return null; List<Object> children = ganttPanel.getChildren(); List<DependencyList> found = ComponentsFinder.findComponentsOfType(DependencyList.class, children); if (found.isEmpty()) return null; return found.get(0); } public void addTasks(Position position, Collection<? extends Task> newTasks) { TaskList taskList = getTaskList(); if (taskList != null && leftPane != null) { taskList.addTasks(position, newTasks); leftPane.addTasks(position, newTasks); } } public void addTask(Position position, Task task) { addTasks(position, Arrays.asList(task)); } void addDependencies(Collection<? extends Dependency> dependencies) { DependencyList dependencyList = getDependencyList(); if (dependencyList == null) { return; } for (DependencyComponent d : getTaskList().asDependencyComponents( dependencies)) { dependencyList.addDependencyComponent(d); } } public void zoomIncrease() { if (ganttPanel == null) { return; } ganttPanel.zoomIncrease(); } public void zoomDecrease() { if (ganttPanel == null) { return; } ganttPanel.zoomDecrease(); } public <T> void setConfiguration(PlannerConfiguration<T> configuration) { if (configuration == null) return; this.diagramGraph = new GanttDiagramGraph(); FunctionalityExposedForExtensions<T> context = new FunctionalityExposedForExtensions<T>( this, configuration.getAdapter(), configuration.getNavigator(), diagramGraph); this.contextualizedGlobalCommands = contextualize(context, configuration.getGlobalCommands()); this.commandsOnTasksContextualized = contextualize(context, configuration.getCommandsOnTasks()); goingDownInLastArrowCommand = contextualize(context, configuration .getGoingDownInLastArrowCommand()); editTaskCommand = contextualize(context, configuration .getEditTaskCommand()); this.context = context; context.add(configuration.getData()); setupComponents(); setAt("insertionPointLeftPanel", leftPane); leftPane.afterCompose(); setAt("insertionPointRightPanel", ganttPanel); ganttPanel.afterCompose(); Component chartComponent = configuration.getChartComponent(); if (chartComponent != null) { getFellow("insertionPointChart").appendChild(chartComponent); } } private void setAt(String insertionPointId, Component component) { Component insertionPoint = getFellow(insertionPointId); insertionPoint.getChildren().clear(); insertionPoint.appendChild(component); } private <T> List<CommandOnTaskContextualized<T>> contextualize( FunctionalityExposedForExtensions<T> context, List<ICommandOnTask<T>> commands) { List<CommandOnTaskContextualized<T>> result = new ArrayList<CommandOnTaskContextualized<T>>(); for (ICommandOnTask<T> c : commands) { result.add(contextualize(context, c)); } return result; } private <T> CommandOnTaskContextualized<T> contextualize( FunctionalityExposedForExtensions<T> context, ICommandOnTask<T> commandOnTask) { return CommandOnTaskContextualized.create(commandOnTask, context .getMapper(), context); } private <T> CommandContextualized<T> contextualize(IContext<T> context, ICommand<T> command) { if (command == null) return null; return CommandContextualized.create(command, context); } private <T> List<CommandContextualized<T>> contextualize( IContext<T> context, Collection<? extends ICommand<T>> commands) { ArrayList<CommandContextualized<T>> result = new ArrayList<CommandContextualized<T>>(); for (ICommand<T> command : commands) { result.add(contextualize(context, command)); } return result; } public GanttDiagramGraph getGanttDiagramGraph() { return diagramGraph; } private void setupComponents() { insertGlobalCommands(); this.leftPane = new LeftPane(this.diagramGraph.getTopLevelTasks()); this.ganttPanel = new GanttPanel(this.context, commandsOnTasksContextualized, editTaskCommand); } @SuppressWarnings("unchecked") private void insertGlobalCommands() { Component toolbar = getToolbar(); Component firstSeparator = getFirstSeparatorFromToolbar(); toolbar.getChildren().removeAll(getBefore(toolbar, firstSeparator)); for (CommandContextualized<?> c : contextualizedGlobalCommands) { toolbar.insertBefore(c.toButton(), firstSeparator); } } @SuppressWarnings("unchecked") private List<Component> getBefore(Component parent, Component child) { List<Component> children = parent.getChildren(); List<Component> result = new ArrayList<Component>(); for (Component object : children) { if (object == child) { break; } result.add(object); } return result; } @SuppressWarnings("unchecked") private Component getFirstSeparatorFromToolbar() { Component toolbar = getToolbar(); List<Component> children = toolbar.getChildren(); List<Separator> separators = ComponentsFinder .findComponentsOfType( Separator.class, children); return separators.get(0); } private Component getToolbar() { Component toolbar = getFellow("toolbar"); return toolbar; } void removeTask(Task task) { TaskList taskList = getTaskList(); taskList.remove(task); getDependencyList().taskRemoved(task); leftPane.taskRemoved(task); setHeight(getHeight());// forcing smart update taskList.adjustZoomColumnsHeight(); getDependencyList().redrawDependencies(); } private IScriptsRegister getScriptsRegister() { return OnZKDesktopRegistry.getLocatorFor(IScriptsRegister.class) .retrieve(); } @Override public void afterCompose() { super.afterCompose(); } public TimeTracker getTimeTracker() { return ganttPanel.getTimeTracker(); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * * @author Hyun Choi, Ted Pyne, Patrick Forelli */ public class CheckersGUI extends javax.swing.JFrame { //keeps track of a Board, a 2d array of JLabels to represent each tile, and JPanel to store the tiles public Board board; private JLabel[][] GUIboard; //JPanel entireGUI for the enclosure of both the board and the text private JPanel entireGUI; //outer JPanel panel for the outer board panel, boardGUI for the inner board panel private JPanel panel; private JPanel boardGUI; //JPanel for textual info; JLabels/JButton for information and toggling private JPanel text; private JLabel victoryStatus; private JLabel turnStatus; private JButton aiToggle; //AI implementation private AI ai; private boolean aiActive; private boolean selected = false; //if a piece is selected or not private int[][] currentSelected; //coordinates of the selected piece and the target area private final int MULTIPLIER = 62; //width of one tile /** * Creates new form CheckersGUI */ public CheckersGUI() { board = new Board(); GUIboard = new JLabel[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { //if(board.getPiece(i,j) != null) GUIboard[i][j] = new JLabel(); } } entireGUI = new JPanel(); //outer JPanel to store the boardGUI and the textual information entireGUI.setLayout(new BoxLayout(entireGUI, BoxLayout.X_AXIS)); aiActive = false; //by default, AI is inactive text = new JPanel(); //inner JPanel to hold text text.setLayout(new GridLayout (3,2)); initializeText(); currentSelected = new int[2][2]; boardGUI = new JPanel(); boardGUI.setLayout(new GridLayout(8,8)); //tiles in a GridLayout of 8x8 boardGUI.addMouseListener(new MouseAdapter() { //essence of the GUI's click detection int selected =0; public void mouseClicked(MouseEvent e) { if (selected==0) //if nothing is selected { currentSelected[0]=arrayCoord(pressed(e)); //store coordinates of the press in array selected++; //if invalid selection, revert if(!board.isValidSelection(currentSelected[0][1], currentSelected[0][0])){ currentSelected = new int[2][2]; selected=0; } else { int i = currentSelected[0][1]; int j = currentSelected[0][0]; if (board.getPiece(i,j).getIsWhite())//if the piece is white { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhitekingselected.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhiteselected.png"))); } else //so that means it's a red { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredkingselected.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredselected.png"))); } } } else if (selected ==1) //target tile { //using the coordinates, make a move and render the board on the GUI currentSelected[1]=arrayCoord(pressed(e)); TurnProcessor turnProc = new TurnProcessor(currentSelected[0][1], currentSelected[0][0], currentSelected[1][1], currentSelected[1][0], board); if(currentSelected[1][1]==currentSelected[0][1] && currentSelected[0][0] == currentSelected[1][0]){ currentSelected = new int[2][2]; selected=0; renderBoard(); } else if(!turnProc.isValidTurn()){ selected = 1; } else{ move(currentSelected); renderBoard(); //revert to original state currentSelected = new int[2][2]; selected=0; } if (ai!=null) //make AI move if AI is active { ai.makeMove(); renderBoard(); } } } }); panel = new JPanel(); //enclose GridLayout within JPanel on the JFrame panel.add(boardGUI); renderBoard(); //render board on the GUI } public void renderBoard() //method to arrange images to form the board { boolean previousColorIsWhite = false; //for arrangement for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board.getPiece(i,j) != null) { if (board.getPiece(i,j).getIsWhite())//if the piece is white { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhiteking.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhite.png"))); } else //so that means it's a red { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredking.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithred.png"))); } previousColorIsWhite=true; } else //if no piece, then blank tile (white or green) { if (previousColorIsWhite) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/greentile.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitetile.png"))); previousColorIsWhite = !previousColorIsWhite; } boardGUI.add(GUIboard[i][j]); } previousColorIsWhite=!previousColorIsWhite; } refreshText(); //update the text fields //combine the two components of the GUI entireGUI.add(panel); entireGUI.add(text); setResizable(false); //window cannot be resized //make it visible pack(); this.setContentPane(entireGUI); setVisible(true); } private void initializeText() { final JLabel VICTORY = new JLabel ("VICTORY"); victoryStatus = new JLabel(); final JLabel TURN = new JLabel ("TURN"); turnStatus = new JLabel(); final JLabel AI = new JLabel ("AI STATUS"); aiToggle = new JButton("AI INACTIVE"); aiToggle.addActionListener(new ActionListener() { //button for toggling AI activation status public void actionPerformed(ActionEvent e) { aiActive = !aiActive; if (aiActive) { ai = new AI(board); aiToggle.setText("AI ACTIVE"); } else { aiToggle.setText("AI INACTIVE"); ai = null; } } }); text.add(VICTORY); text.add(victoryStatus); text.add(TURN); text.add(turnStatus); text.add(AI); text.add(aiToggle); } public void refreshText() { if (board.gameIsWon()!=null) //set victor if there is one { if (board.gameIsWon().getIsWhite()) { victoryStatus.setText("WHITE"); } else { victoryStatus.setText("BLACK"); } } else { victoryStatus.setText("???"); } if (board.isWhiteTurn()) //display turn turnStatus.setText("WHITE"); else turnStatus.setText("RED"); } private int[] pressed(MouseEvent e) //returns pixel coordinates where clicked { Component c = boardGUI.findComponentAt(e.getX(), e.getY()); int[] coordinates = new int[2]; coordinates[0] = e.getX(); coordinates[1] = e.getY(); return coordinates; } private int[] arrayCoord(int[] pixelCoord) //returns coordinates within the checkerboard, limited to [0,0] to [7,7] { for (int i=0; i<2; i++) pixelCoord[i] /= MULTIPLIER; return pixelCoord; } private void move(int[][] currentSelected) //moves the pieces in the Board variable { board.makeMove(currentSelected[0][1],currentSelected[0][0],currentSelected[1][1],currentSelected[1][0]); } public static void main (String[] args) //runs the game with debugging console { CheckersGUI gui = new CheckersGUI(); gui.renderBoard(); } }
package io.sweers.barber.sample; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.widget.FrameLayout; import io.sweers.barber.Barber; import io.sweers.barber.Kind; import io.sweers.barber.Required; import io.sweers.barber.StyledAttr; /** * Sample view showcasing Barber's ease-of-use */ public class BarberView extends FrameLayout { @StyledAttr(value = R.styleable.BarberView_stripeColor, kind = Kind.COLOR) int stripeColor = Color.BLUE; @StyledAttr(R.styleable.BarberView_stripeCount) int stripeCount = 3; @Required @StyledAttr(value = R.styleable.BarberView_poleWidth, kind = Kind.DIMEN_PIXEL_SIZE) int poleWidth; private final Paint paint = new Paint(); public BarberView(Context context) { super(context); } public BarberView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BarberView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Barber.style(this, attrs, R.styleable.BarberView, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public BarberView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); Barber.style(this, attrs, R.styleable.BarberView, defStyleAttr, defStyleRes); } @Override protected void dispatchDraw(@NonNull Canvas canvas) { super.dispatchDraw(canvas); int stripeWidth = getHeight() / (2 * stripeCount); paint.setStrokeWidth(stripeWidth); int poleXStart = (getWidth() / 2) - (poleWidth / 2); for (int i = 0; i < (stripeCount * 2) + 4; ++i) { paint.setColor(i % 2 == 0 ? stripeColor : Color.WHITE); canvas.drawLine(poleXStart, i*stripeWidth, poleXStart + poleWidth, (i*stripeWidth) + stripeWidth, paint); } paint.setColor(Color.BLACK); paint.setStrokeWidth(20f); canvas.drawLine(poleXStart, 0, poleXStart, getHeight(), paint); canvas.drawLine(poleXStart + poleWidth, 0, poleXStart + poleWidth, getHeight(), paint); paint.setStrokeWidth(80f); canvas.drawLine(poleXStart, getHeight(), poleXStart + poleWidth, getHeight(), paint); canvas.drawLine(poleXStart, 0, poleXStart + poleWidth, 0, paint); } }
package io.scif.io; import io.scif.AbstractSCIFIOComponent; import io.scif.common.Constants; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import org.scijava.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Location extends AbstractSCIFIOComponent { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(Location.class); // -- Fields -- private boolean isURL = true; private URL url; private File file; // -- Constructors -- public Location(Context context) { setContext(context); } public Location(Context context, String pathname) { this(context); log().trace("Location(" + pathname + ")"); try { url = new URL(scifio().location().getMappedId(pathname)); } catch (MalformedURLException e) { log().trace("Location is not a URL", e); isURL = false; } if (!isURL) file = new File(scifio().location().getMappedId(pathname)); } public Location(Context context, File file) { this(context); log().trace("Location(" + file + ")"); isURL = false; this.file = file; } public Location(Context context, String parent, String child) { this(context, parent + File.separator + child); } public Location(Context context, Location parent, String child) { this(context, parent.getAbsolutePath(), child); } /** * Return a list of all of the files in this directory. If 'noHiddenFiles' is * set to true, then hidden files are omitted. * * @see java.io.File#list() */ public String[] list(boolean noHiddenFiles) { String key = getAbsolutePath() + Boolean.toString(noHiddenFiles); String [] result = null; result = scifio().location().getCachedListing(key); if (result != null) return result; ArrayList<String> files = new ArrayList<String>(); if (isURL) { try { URLConnection c = url.openConnection(); InputStream is = c.getInputStream(); boolean foundEnd = false; while (!foundEnd) { byte[] b = new byte[is.available()]; is.read(b); String s = new String(b, Constants.ENCODING); if (s.toLowerCase().indexOf("</html>") != -1) foundEnd = true; while (s.indexOf("a href") != -1) { int ndx = s.indexOf("a href") + 8; int idx = s.indexOf("\"", ndx); if (idx < 0) break; String f = s.substring(ndx, idx); if (files.size() > 0 && f.startsWith("/")) { return null; } s = s.substring(idx + 1); if (f.startsWith("?")) continue; Location check = new Location(getContext(), getAbsolutePath(), f); if (check.exists() && (!noHiddenFiles || !check.isHidden())) { files.add(check.getName()); } } } } catch (IOException e) { log().trace("Could not retrieve directory listing", e); return null; } } else { if (file == null) return null; String[] f = file.list(); if (f == null) return null; for (String name : f) { if (!noHiddenFiles || !(name.startsWith(".") || new Location(getContext(), file.getAbsolutePath(), name).isHidden())) { files.add(name); } } } result = files.toArray(new String[files.size()]); scifio().location().putCachedListing(key, result); return result; } // -- File API methods -- /** * If the underlying location is a URL, this method will return true if * the URL exists. * Otherwise, it will return true iff the file exists and is readable. * * @see java.io.File#canRead() */ public boolean canRead() { return isURL ? (isDirectory() || isFile()) : file.canRead(); } /** * If the underlying location is a URL, this method will always return false. * Otherwise, it will return true iff the file exists and is writable. * * @see java.io.File#canWrite() */ public boolean canWrite() { return isURL ? false : file.canWrite(); } /** * Creates a new empty file named by this Location's path name iff a file * with this name does not already exist. Note that this operation is * only supported if the path name can be interpreted as a path to a file on * disk (i.e. is not a URL). * * @return true if the file was created successfully * @throws IOException if an I/O error occurred, or the * abstract pathname is a URL * @see java.io.File#createNewFile() */ public boolean createNewFile() throws IOException { if (isURL) throw new IOException("Unimplemented"); return file.createNewFile(); } /** * Deletes this file. If {@link #isDirectory()} returns true, then the * directory must be empty in order to be deleted. URLs cannot be deleted. * * @return true if the file was successfully deleted * @see java.io.File#delete() */ public boolean delete() { return isURL ? false : file.delete(); } /** * Request that this file be deleted when the JVM terminates. * This method will do nothing if the pathname represents a URL. * * @see java.io.File#deleteOnExit() */ public void deleteOnExit() { if (!isURL) file.deleteOnExit(); } /** * @see java.io.File#equals(Object) * @see java.net.URL#equals(Object) */ public boolean equals(Object obj) { String absPath = getAbsolutePath(); String thatPath = null; if (obj instanceof Location) { thatPath = ((Location) obj).getAbsolutePath(); } else { thatPath = obj.toString(); } return absPath.equals(thatPath); } public int hashCode() { return getAbsolutePath().hashCode(); } /** * Returns whether or not the pathname exists. * If the pathname is a URL, then existence is determined based on whether * or not we can successfully read content from the URL. * * @see java.io.File#exists() */ public boolean exists() { if (isURL) { try { url.getContent(); return true; } catch (IOException e) { log().trace("Failed to retrieve content from URL", e); return false; } } if (file.exists()) return true; if (scifio().location().getMappedFile(file.getPath()) != null) return true; String mappedId = scifio().location().getMappedId(file.getPath()); return mappedId != null && new File(mappedId).exists(); } /* @see java.io.File#getAbsoluteFile() */ public Location getAbsoluteFile() { return new Location(getContext(), getAbsolutePath()); } /* @see java.io.File#getAbsolutePath() */ public String getAbsolutePath() { return isURL ? url.toExternalForm() : file.getAbsolutePath(); } /* @see java.io.File#getCanonicalFile() */ public Location getCanonicalFile() throws IOException { return isURL ? getAbsoluteFile() : new Location(getContext(), file.getCanonicalFile()); } /** * Returns the canonical path to this file. * If the file is a URL, then the canonical path is equivalent to the * absolute path ({@link #getAbsolutePath()}). Otherwise, this method * will delegate to {@link java.io.File#getCanonicalPath()}. */ public String getCanonicalPath() throws IOException { return isURL ? getAbsolutePath() : file.getCanonicalPath(); } /** * Returns the name of this file, i.e. the last name in the path name * sequence. * * @see java.io.File#getName() */ public String getName() { if (isURL) { String name = url.getFile(); name = name.substring(name.lastIndexOf("/") + 1); return name; } return file.getName(); } /** * Returns the name of this file's parent directory, i.e. the path name prefix * and every name in the path name sequence except for the last. * If this file does not have a parent directory, then null is returned. * * @see java.io.File#getParent() */ public String getParent() { if (isURL) { String absPath = getAbsolutePath(); absPath = absPath.substring(0, absPath.lastIndexOf("/")); return absPath; } return file.getParent(); } /* @see java.io.File#getParentFile() */ public Location getParentFile() { return new Location(getContext(), getParent()); } /* @see java.io.File#getPath() */ public String getPath() { return isURL ? url.getHost() + url.getPath() : file.getPath(); } /** * Tests whether or not this path name is absolute. * If the path name is a URL, this method will always return true. * * @see java.io.File#isAbsolute() */ public boolean isAbsolute() { return isURL ? true : file.isAbsolute(); } /** * Returns true if this pathname exists and represents a directory. * * @see java.io.File#isDirectory() */ public boolean isDirectory() { if (isURL) { String[] list = list(); return list != null; } return file.isDirectory(); } /** * Returns true if this pathname exists and represents a regular file. * * @see java.io.File#exists() */ public boolean isFile() { return isURL ? (!isDirectory() && exists()) : file.isFile(); } /** * Returns true if the pathname is 'hidden'. This method will always * return false if the pathname corresponds to a URL. * * @see java.io.File#isHidden() */ public boolean isHidden() { return isURL ? false : file.isHidden(); } /** * Return the last modification time of this file, in milliseconds since * the UNIX epoch. * If the file does not exist, 0 is returned. * * @see java.io.File#lastModified() * @see java.net.URLConnection#getLastModified() */ public long lastModified() { if (isURL) { try { return url.openConnection().getLastModified(); } catch (IOException e) { log().trace("Could not determine URL's last modification time", e); return 0; } } return file.lastModified(); } /** * @see java.io.File#length() * @see java.net.URLConnection#getContentLength() */ public long length() { if (isURL) { try { return url.openConnection().getContentLength(); } catch (IOException e) { log().trace("Could not determine URL's content length", e); return 0; } } return file.length(); } /** * Return a list of file names in this directory. Hidden files will be * included in the list. * If this is not a directory, return null. */ public String[] list() { return list(false); } /** * Return a list of absolute files in this directory. Hidden files will * be included in the list. * If this is not a directory, return null. */ public Location[] listFiles() { String[] s = list(); if (s == null) return null; Location[] f = new Location[s.length]; for (int i=0; i<f.length; i++) { f[i] = new Location(getContext(), getAbsolutePath(), s[i]); f[i] = f[i].getAbsoluteFile(); } return f; } /** * Return the URL corresponding to this pathname. * * @see java.io.File#toURL() */ public URL toURL() throws MalformedURLException { return isURL ? url : file.toURI().toURL(); } /** * @see java.io.File#toString() * @see java.net.URL#toString() */ public String toString() { return isURL ? url.toString() : file.toString(); } }
package water.api; import water.H2O; import water.Key; import water.api.schemas3.*; import water.api.schemas3.RapidsHelpV3.RapidsExpressionV3; import water.api.schemas4.InputSchemaV4; import water.api.schemas4.SessionIdV4; import water.exceptions.H2OIllegalArgumentException; import water.rapids.Rapids; import water.rapids.Session; import water.rapids.Val; import water.rapids.ast.AstRoot; import water.util.Log; import water.util.StringUtils; import java.util.*; public class RapidsHandler extends Handler { public RapidsSchemaV3 exec(int version, RapidsSchemaV3 rapids) { if (rapids == null) return null; if (!StringUtils.isNullOrEmpty(rapids.id)) throw new H2OIllegalArgumentException("Field RapidsSchemaV3.id is deprecated and should not be set " + rapids.id); if (StringUtils.isNullOrEmpty(rapids.ast)) return rapids; if (StringUtils.isNullOrEmpty(rapids.session_id)) rapids.session_id = "_specialSess"; Session ses = RapidsHandler.SESSIONS.get(rapids.session_id); if (ses == null) { ses = new Session(rapids.session_id); RapidsHandler.SESSIONS.put(rapids.session_id, ses); } Val val; try { // This call is synchronized on the session instance val = Rapids.exec(rapids.ast, ses); } catch (IllegalArgumentException e) { throw e; } catch (Throwable e) { Log.err(e); e.printStackTrace(); throw e; } switch (val.type()) { case Val.NUM: return new RapidsNumberV3(val.getNum()); case Val.NUMS: return new RapidsNumbersV3(val.getNums()); case Val.ROW: return new RapidsNumbersV3(val.getRow()); case Val.STR: return new RapidsStringV3(val.getStr()); case Val.STRS: return new RapidsStringsV3(val.getStrs()); case Val.FRM: return new RapidsFrameV3(val.getFrame()); case Val.FUN: return new RapidsFunctionV3(val.getFun().toString()); default: throw H2O.fail(); } } public RapidsHelpV3 genHelp(int version, SchemaV3 noschema) { Iterator<AstRoot> iterator = ServiceLoader.load(AstRoot.class).iterator(); List<AstRoot> rapids = new ArrayList<>(); while (iterator.hasNext()) { rapids.add(iterator.next()); } ArrayList<RapidsExpressionV3> expressions = new ArrayList<>(); for(AstRoot expr: rapids){ expressions.add(processAstClass(expr)); } RapidsHelpV3 res = new RapidsHelpV3(); res.expressions = expressions.toArray(new RapidsExpressionV3[expressions.size()]); return res; } private RapidsExpressionV3 processAstClass(AstRoot expr) { RapidsExpressionV3 target = new RapidsExpressionV3(); target.name = expr.getClass().getSimpleName(); target.pattern = expr.example(); target.description = expr.description(); return target; } /** Map of session-id (sent by the client) to the actual session instance. */ public static HashMap<String, Session> SESSIONS = new HashMap<>(); @SuppressWarnings("unused") // called through reflection by RequestServer public InitIDV3 startSession(int version, InitIDV3 p) { p.session_key = "_sid" + Key.make().toString().substring(0,5); return p; } @SuppressWarnings("unused") // called through reflection by RequestServer public InitIDV3 endSession(int version, InitIDV3 p) { if (SESSIONS.get(p.session_key) != null) { try { SESSIONS.get(p.session_key).end(null); SESSIONS.remove(p.session_key); } catch (Throwable ex) { throw SESSIONS.get(p.session_key).endQuietly(ex); } } return p; } public static class StartSession4 extends RestApiHandler<InputSchemaV4, SessionIdV4> { @Override public String name() { return "newSession4"; } @Override public String help() { return "Start a new Rapids session, and return the session id."; } @Override public SessionIdV4 exec(int ignored, InputSchemaV4 input) { SessionIdV4 out = new SessionIdV4(); out.session_key = "_sid" + Key.make().toString().substring(0, 5); return out; } } }
package water.parser; import java.util.ArrayList; import java.util.List; import water.Key; import water.exceptions.H2OUnsupportedDataFileException; import water.fvec.ByteVec; import water.fvec.Vec; import water.util.ArrayUtils; import static water.parser.DefaultParserProviders.ARFF_INFO; class ARFFParser extends CsvParser { private static final String INCOMPLETE_HEADER = "@H20_INCOMPLETE_HEADER@"; private static final String SKIP_NEXT_HEADER = "@H20_SKIP_NEXT_HEADER@"; private static final String TAG_ATTRIBUTE = "@ATTRIBUTE"; private static final String NA = "?"; //standard NA in Arff format private static final byte GUESS_SEP = ParseSetup.GUESS_SEP; private static final byte[] NON_DATA_LINE_MARKERS_DEFAULT = {'%', '@'}; ARFFParser(ParseSetup ps, Key jobKey) { super(ps, jobKey); } @Override protected byte[] nonDataLineMarkersDefault() { return NON_DATA_LINE_MARKERS_DEFAULT; } /** Try to parse the bytes as ARFF format */ static ParseSetup guessSetup(ByteVec bv, byte[] bits, byte sep, boolean singleQuotes, String[] columnNames, String[][] naStrings, byte[] nonDataLineMarkers) { if (columnNames != null) throw new UnsupportedOperationException("ARFFParser doesn't accept columnNames."); if (nonDataLineMarkers == null) nonDataLineMarkers = NON_DATA_LINE_MARKERS_DEFAULT; // Parse all lines starting with @ until EOF or @DATA boolean haveData = false; String[][] data = new String[0][]; String[] labels; String[][] domains; String[] headerlines = new String[0]; byte[] ctypes; // header section ArrayList<String> header = new ArrayList<>(); int offset = 0; int chunk_idx = 0; //relies on the assumption that bits param have been extracted from first chunk: cf. ParseSetup#map boolean readHeader = true; while (readHeader) { offset = readArffHeader(0, header, bits, singleQuotes); if (isValidHeader(header)) { String lastHeader = header.get(header.size() - 1); if (INCOMPLETE_HEADER.equals(lastHeader) || SKIP_NEXT_HEADER.equals(lastHeader)) { bits = bv.chunkForChunkIdx(++chunk_idx).getBytes(); continue; } } else if (chunk_idx > 0) { //first chunk parsed correctly, but not the next => formatting issue throw new H2OUnsupportedDataFileException( "Arff parsing: Invalid header. If compressed file, please try without compression", "First chunk was parsed correctly, but a following one failed, common with archives as only first chunk in decompressed"); } readHeader = false; } if (offset < bits.length && !CsvParser.isEOL(bits[offset])) haveData = true; //more than just the header if (header.size() == 0) throw new ParseDataset.H2OParseException("No data!"); headerlines = header.toArray(headerlines); // process header int ncols = headerlines.length; labels = new String[ncols]; domains = new String[ncols][]; ctypes = new byte[ncols]; processArffHeader(ncols, headerlines, labels, domains, ctypes); // data section (for preview) if (haveData) { final int preview_max_length = 10; ArrayList<String> datablock = new ArrayList<>(); //Careful! the last data line could be incomplete too (cf. readArffHeader) while (offset < bits.length && datablock.size() < preview_max_length) { int lineStart = offset; while (offset < bits.length && !CsvParser.isEOL(bits[offset])) ++offset; int lineEnd = offset; ++offset; // For Windoze, skip a trailing LF after CR if ((offset < bits.length) && (bits[offset] == CsvParser.CHAR_LF)) ++offset; if (ArrayUtils.contains(nonDataLineMarkers, bits[lineStart])) continue; if (lineEnd > lineStart) { String str = new String(bits, lineStart, lineEnd - lineStart).trim(); if (!str.isEmpty()) datablock.add(str); } } if (datablock.size() == 0) throw new ParseDataset.H2OParseException("Unexpected line."); // process data section String[] datalines = datablock.toArray(new String[datablock.size()]); data = new String[datalines.length][]; // First guess the field separator by counting occurrences in first few lines if (datalines.length == 1) { if (sep == GUESS_SEP) { //could be a bit more robust than just counting commas? if (datalines[0].split(",").length > 2) sep = ','; else if (datalines[0].split(" ").length > 2) sep = ' '; else throw new ParseDataset.H2OParseException("Failed to detect separator."); } data[0] = determineTokens(datalines[0], sep, singleQuotes); ncols = (ncols > 0) ? ncols : data[0].length; labels = null; } else { // 2 or more lines if (sep == GUESS_SEP) { // first guess the separator //FIXME if last line is incomplete, this logic fails sep = guessSeparator(datalines[0], datalines[1], singleQuotes); if (sep == GUESS_SEP && datalines.length > 2) { sep = guessSeparator(datalines[1], datalines[2], singleQuotes); if (sep == GUESS_SEP) sep = guessSeparator(datalines[0], datalines[2], singleQuotes); } if (sep == GUESS_SEP) sep = (byte) ' '; // Bail out, go for space } for (int i = 0; i < datalines.length; ++i) { data[i] = determineTokens(datalines[i], sep, singleQuotes); } } } naStrings = addDefaultNAs(naStrings, ncols); // Return the final setup return new ParseSetup(ARFF_INFO, sep, singleQuotes, ParseSetup.NO_HEADER, ncols, labels, ctypes, domains, naStrings, data, nonDataLineMarkers); } private static String[][] addDefaultNAs(String[][] naStrings, int nCols) { final String[][] nas = naStrings == null ? new String[nCols][] : naStrings; for (int i = 0; i < nas.length; i++) { String [] colNas = nas[i]; if (!ArrayUtils.contains(colNas, NA)) { nas[i] = colNas = ArrayUtils.append(colNas, NA); } } return nas; } private static boolean isValidHeader(List<String> header) { for (String line : header) { if (!isValidHeaderLine(line)) return false; } return header.size() > 0; } private static boolean isValidHeaderLine(String str) { return str != null && str.startsWith("@"); } private static int readArffHeader(int offset, List<String> header, byte[] bits, boolean singleQuotes) { String lastHeader = header.size() > 0 ? header.get(header.size() - 1) : null; boolean lastHeaderIncomplete = INCOMPLETE_HEADER.equals(lastHeader); boolean skipFirstLine = SKIP_NEXT_HEADER.equals(lastHeader); if (lastHeaderIncomplete || skipFirstLine) header.remove(header.size() - 1); //remove fake header lastHeader = lastHeaderIncomplete ? header.remove(header.size() - 1) : null; //remove incomplete header for future concatenation while (offset < bits.length) { int lineStart = offset; while (offset < bits.length && !CsvParser.isEOL(bits[offset])) ++offset; int lineEnd = offset; ++offset; // For Windoze, skip a trailing LF after CR if ((offset < bits.length) && (bits[offset] == CsvParser.CHAR_LF)) ++offset; boolean lastLineIncomplete = lineEnd == bits.length && !CsvParser.isEOL(bits[lineEnd-1]); if (skipFirstLine) { skipFirstLine = false; if (lastLineIncomplete) header.add(SKIP_NEXT_HEADER); continue; } if (bits[lineStart] == '%') { //skip comment lines if (!lastHeaderIncomplete) { if (lastLineIncomplete) header.add(SKIP_NEXT_HEADER); continue; } } String str = new String(bits, lineStart, lineEnd - lineStart).trim(); if (lastHeaderIncomplete) { str = lastHeader + str; //add current line portion to last header portion from previous chunk lastHeaderIncomplete = false; } else if (str.matches("(?i)^@relation\\s?.*$")) { //ignore dataset name continue; } else if (str.matches("(?i)^@data\\s?.*$")) { //stop header parsing as soon as we encounter data break; } if (!str.isEmpty()) { header.add(str); if (lastLineIncomplete) header.add(INCOMPLETE_HEADER); } } return offset; } static void processArffHeader(int ncols, String[] headerlines, String[] labels, String[][] domains, byte[] ctypes) { for (int i=0; i<ncols; ++i) { String[] line = headerlines[i].split("\\s+", 2); if (!line[0].equalsIgnoreCase(TAG_ATTRIBUTE)) { throw new ParseDataset.H2OParseException("Expected line to start with @ATTRIBUTE."); } else { final String spec = (line.length == 2) ? line[1].replaceAll("\\s", " ") : ""; // normalize separators int sepIdx = spec.lastIndexOf(' '); if (sepIdx < 0) { throw new ParseDataset.H2OParseException("Expected @ATTRIBUTE to be followed by <attribute-name> <datatype>"); } final String type = spec.substring(sepIdx + 1).trim(); domains[i] = null; ctypes[i] = Vec.T_BAD; if (type.equalsIgnoreCase("NUMERIC") || type.equalsIgnoreCase("REAL") || type.equalsIgnoreCase("INTEGER") || type.equalsIgnoreCase("INT")) { ctypes[i] = Vec.T_NUM; } else if (type.equalsIgnoreCase("DATE") || type.equalsIgnoreCase("TIME")) { ctypes[i] = Vec.T_TIME; } else if (type.equalsIgnoreCase("ENUM")) { ctypes[i] = Vec.T_CAT; } else if (type.equalsIgnoreCase("STRING")) { ctypes[i] = Vec.T_STR; } else if (type.equalsIgnoreCase("UUID")) { //extension of ARFF ctypes[i] = Vec.T_UUID; } else if (type.equalsIgnoreCase("RELATIONAL")) { throw new UnsupportedOperationException("Relational ARFF format is not supported."); } else if (type.endsWith("}")) { int domainSpecStart = spec.lastIndexOf('{'); if (domainSpecStart < 0) throw new ParseDataset.H2OParseException("Invalid type specification."); sepIdx = domainSpecStart - 1; String domainSpec = spec.substring(domainSpecStart + 1, line[1].length() - 1); domains[i] = domainSpec.split(","); for (int j = 0; j < domains[i].length; j++) domains[i][j] = domains[i][j].trim(); if (domains[i][0].length() > 0) ctypes[i] = Vec.T_CAT; // case of {A,B,C} (valid list of factors) } if (ctypes[i] == Vec.T_BAD) throw new ParseDataset.H2OParseException("Unexpected line, type not recognized. Attribute specification: " + type); // remove the whitespaces separating the label and the type specification while ((sepIdx > 0) && (spec.charAt(sepIdx - 1) == ' ')) sepIdx String label = line[1].substring(0, sepIdx); // use the raw string before whitespace normalization // remove quotes if (label.length() >= 2 && label.startsWith("'") && label.endsWith("'")) label = label.substring(1, label.length() - 1); labels[i] = label; } } } }
package control; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.health.control.*; public class ControlModuleTest { private ControlModule cm; @Before public void setUp() { cm = new ControlModule(); } @Test public void setData() { InputData id1 = new InputData("path/to/xml1.xml", "path/to/data1.txt"); InputData id2 = new InputData("path/to/xml2.xml", "path/to/data2.txt"); InputData id3 = new InputData("path/to/xml3.xml", "path/to/data3.txt"); InputData[] id = {id1, id2, id3}; cm.setData(id); InputData[] expected = {id1, id2, id3}; assertArrayEquals(expected, cm.getScript()); } @Test public void setScript() { cm.setScript("hist('histogram.png', avgByDay.AvgCreatinine, avgByDay.DateTime.DayOfYear, 365);"); String expected = "hist('histogram.png', avgByDay.AvgCreatinine, avgByDay.DateTime.DayOfYear, 365);"; assertEquals(expected, cm.getScript()); } @Test public void getData() { } }
package ch.sharpsoft.hexapod; import java.util.ArrayList; import java.util.List; public class Leg { private final static double width = 5.5; private final static double height = 4; private final int id; private final Vector3 startPoint; private final Quaternion startOrientation; private final LegSegment startSegment; private final LegSegment segment1; private final LegSegment segment2; private final LegSegment endSegment; private final Knee k1; private final Knee k2; private final Knee k3; private final double startYaw; public Leg(final int id, final Vector3 startPoint, final double startYaw) { this.id = id; this.startYaw = startYaw; this.startOrientation = Quaternion.fromEuler(0.0, 0.0, startYaw); this.startPoint = startPoint; startSegment = new LegSegment(startPoint, 0.0, startOrientation); segment1 = new LegSegment(startPoint.add(startSegment.getVector()), 5, startOrientation); segment2 = new LegSegment(segment1.getStartPoint().add(segment1.getVector()), 7, startOrientation); endSegment = new LegSegment(segment2.getStartPoint().add(segment2.getVector()), 13, startOrientation); k1 = new Knee(startSegment, segment1, true); k2 = new Knee(segment1, segment2, false); k3 = new Knee(segment2, endSegment, false); } public void setAngles(final double k1, final double k2, final double k3) { this.k1.setAngle(k1); this.k2.setAngle(k2); this.k3.setAngle(k3); final Quaternion o1 = startOrientation.multiply(Quaternion.fromEuler(0.0, 0.0, k1)); final Quaternion o2 = o1.multiply(Quaternion.fromEuler(0.0, k2, 0.0)); final Quaternion o3 = o2.multiply(Quaternion.fromEuler(0.0, k3, 0.0)); segment1.setOrientation(o1); segment2.setOrientation(o2); endSegment.setOrientation(o3); segment2.setStartPoint(segment1.getEndPoint()); endSegment.setStartPoint(segment2.getEndPoint()); } public double[] getAngles() { return new double[] { k1.getAngle(), k2.getAngle(), k3.getAngle() }; } public boolean intercept(final Leg leg) { return false; } public List<List<Vector3>> getBoundingBoxes() { List<List<Vector3>> result = new ArrayList<>(); Vector3 s = startSegment.getStartPoint(); Vector3 e = startSegment.getEndPoint(); Vector3 v = e.substract(s); Quaternion.fromAxis(v, -1.0 * (Math.PI / 4)); Quaternion.fromAxis(v, 3.0 * (Math.PI / 4)); Quaternion.fromAxis(v, -3.0 * (Math.PI / 4)); Quaternion.fromAxis(v, -1.0 * (Math.PI / 4)); return result; } public void setEndpoint(final Vector3 vector3) { final Vector3 legframe = vector3.substract(startPoint); final double alpha = atan2(-legframe.getY(), legframe.getX()) - startYaw; k1.setAngle(alpha); final Quaternion o1 = startOrientation.multiply(Quaternion.fromEuler(0.0, 0.0, alpha)); segment1.setOrientation(o1); final Vector3 rest = o1.conjugate().multiply(vector3.substract(segment1.getEndPoint())); if (rest.norm() > segment2.getLength() + endSegment.getLength()) { throw new IllegalArgumentException("Legs too short for this point " + vector3); } final double r0 = getSegment2().getLength(); final double r1 = getEndSegment().getLength(); final double phi = atan2(Math.sqrt(1 - pow2((pow2(rest.getX()) + pow2(rest.getZ()) - pow2(r0) - pow2(r1)) / (2 * r0 * r1))), (pow2(rest.getX()) + pow2(rest.getZ()) - pow2(r0) - pow2(r1)) / (2 * r0 * r1)); final double beta = atan2(-rest.getZ(), rest.getX()) - atan2(r1 * Math.sin(phi), r0 + r1 * Math.cos(phi)); k2.setAngle(beta); final Quaternion o2 = o1.multiply(Quaternion.fromEuler(0.0, beta, 0.0)); segment2.setOrientation(o2); segment2.setStartPoint(segment1.getEndPoint()); k3.setAngle(phi); final Quaternion o3 = o2.multiply(Quaternion.fromEuler(0.0, phi, 0.0)); endSegment.setOrientation(o3); endSegment.setStartPoint(segment2.getEndPoint()); } private double pow2(double x) { return x * x; } private double atan2(double x, double y) { double angle = Math.atan2(x, y); if (angle < -Math.PI + 0.01) { return 0; } if (angle > Math.PI - 0.01) { return 0; } return angle; } public Vector3 getEndpoint() { return getEndSegment().getEndPoint(); } public int getId() { return id; } public Vector3 getStartPoint() { return startPoint; } public Quaternion getStartOrientation() { return startOrientation; } public LegSegment getStartSegment() { return startSegment; } public LegSegment getSegment1() { return segment1; } public LegSegment getSegment2() { return segment2; } public LegSegment getEndSegment() { return endSegment; } public Knee getK1() { return k1; } public Knee getK2() { return k2; } public Knee getK3() { return k3; } @Override public String toString() { return "\nLeg [id=" + id + ", startPoint=" + startPoint + ", startOrientation=" + startOrientation + ", startSegment=" + startSegment + ", segment1=" + segment1 + ", segment2=" + segment2 + ", endSegment=" + endSegment + ", k1=" + k1 + ", k2=" + k2 + ", k3=" + k3 + "]"; } }
package orufeo.ia; public class ConfigurationObject { public static final String MY_APP_ID ="YOURAPPID"; public static final String MY_APP_SECRET="YOURAPPSECRET"; public static final String TOKEN="test"; }
package net.bootsfaces.listeners; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.application.Application; import javax.faces.application.ProjectStage; import javax.faces.application.Resource; import javax.faces.application.ResourceHandler; import javax.faces.component.UIComponent; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; import javax.faces.component.html.HtmlBody; import javax.faces.component.html.HtmlHead; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.event.AbortProcessingException; import javax.faces.event.SystemEvent; import javax.faces.event.SystemEventListener; import net.bootsfaces.C; /** * This class adds the resource needed by BootsFaces and ensures that they are loaded in the correct order. It replaces the former * HeadListener. * * @author Stephan Rauh */ public class AddResourcesListener implements SystemEventListener { private static final Logger LOGGER = Logger.getLogger("net.bootsfaces.listeners.AddResourcesListener"); /** Components can request resources by registering them in the ViewMap, using the RESOURCE_KEY. */ private static final String RESOURCE_KEY = "net.bootsfaces.listeners.AddResourcesListener.ResourceFiles"; static { LOGGER.info("Running on BootsFaces 0.7.0-SNAPSHOT."); } /** * Trigger adding the resources if and only if the event has been fired by UIViewRoot. */ public void processEvent(SystemEvent event) throws AbortProcessingException { Object source = event.getSource(); if (source instanceof UIViewRoot) { final FacesContext context = FacesContext.getCurrentInstance(); boolean isProduction = context.isProjectStage(ProjectStage.Production); addJavascript((UIViewRoot) source, context, isProduction); } } /** * Add the required Javascript files and the FontAwesome CDN link. * * @param root * The UIViewRoot of the JSF tree. * @param context * The current FacesContext * @param isProduction * This flag can be used to deliver different version of the JS library, optimized for debugging or production. */ private void addJavascript(UIViewRoot root, FacesContext context, boolean isProduction) { Application app = context.getApplication(); ResourceHandler rh = app.getResourceHandler(); // If the BootsFaces_USETHEME parameter is true, render Theme CSS link String theme = null; theme = context.getExternalContext().getInitParameter(C.P_USETHEME); if (isFontAwesomeComponentUsedAndRemoveIt() || (theme != null && theme.equals(C.TRUE))) { Resource themeResource = rh.createResource(C.BSF_CSS_TBSTHEME, C.BSF_LIBRARY); if (themeResource == null) { throw new FacesException("Error loading theme, cannot find \"" + C.BSF_CSS_TBSTHEME + "\" resource of \"" + C.BSF_LIBRARY + "\" library"); } else { UIOutput output = new UIOutput(); output.setRendererType("javax.faces.resource.Stylesheet"); output.getAttributes().put("name", C.BSF_CSS_TBSTHEME); output.getAttributes().put("library", C.BSF_LIBRARY); output.getAttributes().put("target", "head"); addResourceIfNecessary(root, context, output); } } // deactive FontAwesome support if the no-fa facet is found in the h:head tag UIComponent header = findHeader(root); boolean useCDNImportForFontAwesome = (null == header) || (null == header.getFacet("no-fa")); if (useCDNImportForFontAwesome) { String useCDN = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("net.bootsfaces.get_fontawesome_from_cdn"); if (null != useCDN) if (useCDN.equalsIgnoreCase("false") || useCDN.equals("no")) useCDNImportForFontAwesome=false; } // Do we have to add font-awesome and jQuery, or are the resources already there? boolean loadJQuery = true; List<UIComponent> availableResources = root.getComponentResources(context, "head"); for (UIComponent ava : availableResources) { String name = (String) ava.getAttributes().get("name"); if (null != name) { name = name.toLowerCase(); if ((name.contains("font-awesome") || name.contains("fontawesome")) && name.endsWith("css")) useCDNImportForFontAwesome=false; if (name.contains("jquery-ui") && name.endsWith(".js")) { // do nothing - the if is needed to avoid confusion between jQuery and jQueryUI } else if (name.contains("jquery") && name.endsWith(".js")) { loadJQuery = false; } } } // Font Awesome if (useCDNImportForFontAwesome) { // !=null && usefa.equals(C.TRUE)) { InternalFALink output = new InternalFALink(); output.getAttributes().put("src", C.FONTAWESOME_CDN_URL); addResourceIfNecessary(root, context, output); } Map<String, Object> viewMap = root.getViewMap(); @SuppressWarnings("unchecked") Map<String, String> resourceMap = (Map<String, String>) viewMap.get(RESOURCE_KEY); if (null != resourceMap) { if (loadJQuery) { boolean needsJQuery = false; for (Entry<String, String> entry : resourceMap.entrySet()) { String file = entry.getValue(); if ("jq/jquery.js".equals(file)) { needsJQuery = true; } } if (needsJQuery) { UIOutput output = new UIOutput(); output.setRendererType("javax.faces.resource.Script"); output.getAttributes().put("name", "jq/jquery.js"); output.getAttributes().put("library", C.BSF_LIBRARY); output.getAttributes().put("target", "head"); addResourceIfNecessary(root, context, output); } } for (Entry<String, String> entry : resourceMap.entrySet()) { String file = entry.getValue(); String library = entry.getKey().substring(0, entry.getKey().length() - file.length() - 1); if (!"jq/jquery.js".equals(file)) { UIOutput output = new UIOutput(); output.setRendererType("javax.faces.resource.Script"); output.getAttributes().put("name", file); output.getAttributes().put("library", library); output.getAttributes().put("target", "head"); addResourceIfNecessary(root, context, output); } } } enforceCorrectLoadOrder(root, context); { InternalIE8CompatiblityLinks output = new InternalIE8CompatiblityLinks(); addResourceIfNecessary(root, context, output); } } private void addResourceIfNecessary(UIViewRoot root, FacesContext context, InternalIE8CompatiblityLinks output) { for (UIComponent c : root.getComponentResources(context, "head")) { if (c instanceof InternalIE8CompatiblityLinks) return; } root.addComponentResource(context, output, "head"); } private void addResourceIfNecessary(UIViewRoot root, FacesContext context, InternalFALink output) { for (UIComponent c : root.getComponentResources(context, "head")) { if (c instanceof InternalFALink) return; } root.addComponentResource(context, output, "head"); } private void addResourceIfNecessary(UIViewRoot root, FacesContext context, UIOutput output) { for (UIComponent c : root.getComponentResources(context, "head")) { String library = (String)c.getAttributes().get("library"); String name = (String) c.getAttributes().get("name"); if (library!=null && library.equals(output.getAttributes().get("library"))) { if (name!=null && name.equals(output.getAttributes().get("name"))) { return; } } } root.addComponentResource(context, output, "head"); } /** * Make sure jQuery is loaded before jQueryUI, and that every other Javascript is loaded later. * Also make sure that the BootsFaces resource files are loaded prior to other resource files, * giving the developer the opportunity to overwrite a CSS or JS file. * @param root The current UIViewRoot * @param context The current FacesContext */ private void enforceCorrectLoadOrder(UIViewRoot root, FacesContext context) { List<UIComponent> resources = new ArrayList<UIComponent>(root.getComponentResources(context, "head")); for (UIComponent c : resources) { root.removeComponentResource(context, c); } for (UIComponent c : resources) { String name = (String) c.getAttributes().get("name"); if (name != null) { name = name.toLowerCase(); if (name.contains("jquery") && name.endsWith(".js") && (!name.contains("jquery-ui"))) { root.addComponentResource(context, c, "head"); } } } for (UIComponent c : resources) { String name = (String) c.getAttributes().get("name"); if (name != null) { name = name.toLowerCase(); if (name.contains("jquery-ui") && name.endsWith(".js")) { root.addComponentResource(context, c, "head"); } } } for (UIComponent c : resources) { String library = (String) c.getAttributes().get("library"); if (library != null) { if (library.equals("bsf")) { String name = (String) c.getAttributes().get("name"); if (name != null) { name = name.toLowerCase(); if ((name.contains("jquery") && name.endsWith(".js"))) { continue; } } root.addComponentResource(context, c, "head"); } } } for (UIComponent c : resources) { String name = (String) c.getAttributes().get("name"); String library = (String) c.getAttributes().get("library"); if (library != null) { if (library.equals("bsf")) continue; } if (name != null) { name = name.toLowerCase(); if (!(name.contains("jquery") && name.endsWith(".js"))) { root.addComponentResource(context, c, "head"); } } else // add resources loaded from a CDN root.addComponentResource(context, c, "head"); } } /** * Look whether a b:iconAwesome component is used. If so, the font-awesome.css is removed from the resource list because it's loaded * from the CDN. * * @return true, if the font-awesome.css is found in the resource list. Note the side effect of this method! */ private boolean isFontAwesomeComponentUsedAndRemoveIt() { FacesContext fc = FacesContext.getCurrentInstance(); UIViewRoot viewRoot = fc.getViewRoot(); ListIterator<UIComponent> resourceIterator = (viewRoot.getComponentResources(fc, "head")).listIterator(); UIComponent fontAwesomeResource = null; while (resourceIterator.hasNext()) { UIComponent resource = (UIComponent) resourceIterator.next(); String name = (String) resource.getAttributes().get("name"); // rw.write("\n<!-- res: '"+name+"' -->" ); if (name != null) { if (name.endsWith("font-awesome.css")) fontAwesomeResource = resource; } } if (null != fontAwesomeResource) { viewRoot.removeComponentResource(fc, fontAwesomeResource); return true; } return false; } /** * Looks for the header in the JSF tree. * * @param root * The root of the JSF tree. * @return null, if the head couldn't be found. */ private UIComponent findHeader(UIViewRoot root) { for (UIComponent c : root.getChildren()) { if (c instanceof HtmlHead) return c; } for (UIComponent c : root.getChildren()) { if (c instanceof HtmlBody) return null; if (c instanceof UIOutput) if (c.getFacets()!=null) return c; } return null; } /** * Which JSF elements do we listen to? */ @Override public boolean isListenerForSource(Object source) { if (source instanceof UIComponent) { return true; } return false; } /** * Registers a JS file that needs to be include in the header of the HTML file, but after jQuery and AngularJS. * * @param library * The name of the sub-folder of the resources folder. * @param resource * The name of the resource file within the library folder. */ public static void addResourceToHeadButAfterJQuery(String library, String resource) { FacesContext ctx = FacesContext.getCurrentInstance(); UIViewRoot v = ctx.getViewRoot(); Map<String, Object> viewMap = v.getViewMap(); @SuppressWarnings("unchecked") Map<String, String> resourceMap = (Map<String, String>) viewMap.get(RESOURCE_KEY); if (null == resourceMap) { resourceMap = new HashMap<String, String>(); viewMap.put(RESOURCE_KEY, resourceMap); } String key = library + "#" + resource; if (!resourceMap.containsKey(key)) { resourceMap.put(key, resource); } } }
/* * Thibaut Colar Feb 5, 2010 */ package net.colar.netbeans.fan.parboiled; import org.parboiled.BaseParser; import org.parboiled.Rule; import org.parboiled.support.Cached; import org.parboiled.support.Leaf; @SuppressWarnings( { "InfiniteRecursion" }) public class FantomParser extends BaseParser<Object> { public boolean inFieldInit = false; // to help with differentiation of field accesor & itBlock public boolean inEnum = false; // so we know whether to allow enumDefs public boolean noSimpleMap = false; // to disallow ambigous simpleMaps in certain situations (within another map, ternaryExpr) public Rule compilationUnit() { return sequence( OPT_LF(), // Missing from grammar: Optional unix env line optional(sequence("#!", zeroOrMore(sequence(testNot("\n"), any())), "\n")), zeroOrMore(firstOf(using(), incUsing())), // staticBlock is missing from Fantom grammar page zeroOrMore(firstOf(staticBlock(), typeDef())), OPT_LF(), zeroOrMore(doc()), // allow for extra docs at end of file (if last type commented out) OPT_LF(), eoi()); } public Rule using() { return sequence(OPT_LF(), enforcedSequence( KW_USING, optional(ffi()), id(), zeroOrMore(enforcedSequence(DOT, id())), optional(enforcedSequence(SP_COLCOL, id())), optional(usingAs()), eos()), OPT_LF()); } // Inconplete using - to allow completion public Rule incUsing() { return enforcedSequence( KW_USING, optional(ffi()), optional(id()), // Not optional, but we want a valid ast for completion if missing zeroOrMore(sequence(DOT, id())),// not enforced to allow completion optional(sequence(SP_COLCOL, id())),// not enforced to allow completion optional(usingAs()), optional(eos()), OPT_LF()); } public Rule ffi() { return enforcedSequence(SQ_BRACKET_L, id(), SQ_BRACKET_R); } public Rule usingAs() { return enforcedSequence(KW_AS, id()); } public Rule staticBlock() { return sequence(KW_STATIC, OPT_LF(), enforcedSequence(BRACKET_L, zeroOrMore(stmt()), OPT_LF(), BRACKET_R)); } public Rule typeDef() { // grouped together classdef, enumDef, mixinDef & facetDef as they are grammatically very similar (optimized) return sequence( setInEnum(false), OPT_LF(), optional(doc()), zeroOrMore(facet()), optional(protection()), enforcedSequence( firstOf( sequence(zeroOrMore(firstOf(KW_ABSTRACT, KW_FINAL, KW_CONST)), KW_CLASS), // standard class enforcedSequence(ENUM, KW_CLASS, setInEnum(true)), // enum class enforcedSequence(FACET, KW_CLASS), // facet class sequence(optional(KW_CONST), KW_MIXIN) ), id(), optional(inheritance()), OPT_LF(), BRACKET_L, OPT_LF(), optional(sequence(peekTest(inEnum),optional(enumValDefs()))), // only valid for enums, but simplifying zeroOrMore(slotDef()), BRACKET_R, OPT_LF())); } public Rule protection() { return firstOf(KW_PUBLIC, KW_PROTECTED, KW_INTERNAL, KW_PRIVATE); } public Rule inheritance() { return enforcedSequence(SP_COL, typeList()); } public Rule facet() { return enforcedSequence(AT, simpleType(), optional(facetVals()), OPT_LF()); } public Rule facetVals() { return enforcedSequence( BRACKET_L, facetVal(), zeroOrMore(sequence(eos(), facetVal())), BRACKET_R); } public Rule facetVal() { return enforcedSequence(id(), AS_EQUAL, expr()); } public Rule enumValDefs() { return sequence(enumValDef(), zeroOrMore(sequence(SP_COMMA, enumValDef())), OPT_LF(), eos()); } public Rule enumValDef() { // Fantom grammar is missing "doc" return sequence(OPT_LF(), optional(doc()), id(), optional(enforcedSequence(PAR_L, optional(args()), PAR_R))); } public Rule slotDef() { // Rewrote this to "unify" slots common parts (for better performance) return sequence( OPT_LF(), optional(doc()),// common to all slots zeroOrMore(facet()),// common to all slots optional(protection()),// common to all slots firstOf( ctorDef(), // look for 'new' methodDef(), // look for params : '(' fieldDef()), // others OPT_LF()); } public Rule fieldDef() { return sequence( zeroOrMore(firstOf(KW_ABSTRACT, KW_CONST, KW_FINAL, KW_STATIC, KW_NATIVE, KW_OVERRIDE, KW_READONLY, KW_VIRTUAL)), /*typeAndOrId(),*/ type(), id(), // Type required for fields(no infered) (Grammar does not say so) setFieldInit(true), optional(enforcedSequence(OP_ASSIGN, OPT_LF(), expr())), optional(fieldAccessor()), setFieldInit(false), eos()); } public Rule methodDef() { return enforcedSequence( sequence( // Fan grammar misses 'final' zeroOrMore(firstOf(KW_ABSTRACT, KW_NATIVE, KW_ONCE, KW_STATIC, KW_OVERRIDE, KW_VIRTUAL, KW_FINAL)), type(), id(), PAR_L), optional(params()), PAR_R, methodBody()); } public Rule ctorDef() { return enforcedSequence(KW_NEW, id(), PAR_L, optional(params()), PAR_R, optional( // ctorChain // Fantom Grammar page is missing the ':' enforcedSequence(sequence(OPT_LF(), SP_COL), firstOf( enforcedSequence(KW_THIS, DOT, id(), enforcedSequence(PAR_L, optional(args()), PAR_R)), enforcedSequence(KW_SUPER, optional(enforcedSequence(DOT, id())), enforcedSequence(PAR_L, optional(args()), PAR_R))))), methodBody()); } public Rule methodBody() { return sequence(firstOf( enforcedSequence(sequence(OPT_LF(), BRACKET_L), zeroOrMore(stmt()), OPT_LF(), BRACKET_R), eos()), OPT_LF()); // method with no body } public Rule params() { return sequence(param(), zeroOrMore(enforcedSequence(SP_COMMA, params()))); } public Rule param() { return sequence(OPT_LF(), type(), id(), optional(enforcedSequence(OP_ASSIGN, expr())), OPT_LF()); } public Rule fieldAccessor() { return sequence(OPT_LF(), enforcedSequence( BRACKET_L, optional(sequence(OPT_LF(), enforcedSequence(GET, firstOf(block(), eos())))), optional(sequence(OPT_LF(), optional(protection()), enforcedSequence(SET, firstOf(block(), eos())))), BRACKET_R), OPT_LF()); } public Rule args() { return sequence(expr(), zeroOrMore(sequence(OPT_LF(), enforcedSequence(SP_COMMA, OPT_LF(), expr()))), OPT_LF()); } public Rule block() { return sequence(OPT_LF(), firstOf( enforcedSequence(BRACKET_L, zeroOrMore(stmt()), OPT_LF(), BRACKET_R), // block stmt() // single statement ), OPT_LF()); } public Rule stmt() { return sequence(testNot(BRACKET_R), OPT_LF(), firstOf( sequence(KW_BREAK, eos()), sequence(KW_CONTINUE, eos()), sequence(KW_RETURN, sequence(optional(expr()), eos())).label("MY_RT_STMT"), sequence(KW_THROW, expr(), eos()), if_(), for_(), switch_(), while_(), try_(), // check local var definition as it's faster to parse ':=' localDef(), // otherwise expression (optional Comma for itAdd expression) // using firstOf, because "," in this case can be considered an end of statement sequence(expr(), firstOf(sequence(SP_COMMA, optional(eos())), eos()))), OPT_LF()); } public Rule for_() { return enforcedSequence(KW_FOR, PAR_L, // LocalDef consumes the SEMI as part of loking for EOS, so rewrote to deal with this firstOf(SP_SEMI, firstOf(localDef(), sequence(expr(), SP_SEMI))), firstOf(SP_SEMI, sequence(expr(), SP_SEMI)), optional(expr()), PAR_R, block()); } public Rule if_() { // using condExpr rather than expr return enforcedSequence(KW_IF, PAR_L, condOrExpr()/*was expr*/, PAR_R, block(), optional(enforcedSequence(KW_ELSE, block()))); } public Rule while_() { // using condExpr rather than expr return enforcedSequence(KW_WHILE, PAR_L, condOrExpr()/*was expr*/, PAR_R, block()); } public Rule localDef() { // slight chnage from teh grammar to match either: // 'Int j', 'j:=27', 'Int j:=27' return sequence( firstOf( // fan parser says if it's start with "id :=" or "Type, id", then it gotta be a localDef (enforce) enforcedSequence(sequence(type(), id(), OP_ASSIGN), OPT_LF(), expr()), // same if it starts with "id :=" enforcedSequence(sequence(id(), OP_ASSIGN), OPT_LF(), expr()), // var def with no value sequence(type(), id())), eos()); } public Rule try_() { return enforcedSequence(KW_TRY, block(), zeroOrMore(catch_()), optional(sequence(KW_FINALLY, block()))); } public Rule catch_() { return enforcedSequence(KW_CATCH, optional(enforcedSequence(PAR_L, type(), id(), PAR_R)), block()); } public Rule switch_() { return enforcedSequence(KW_SWITCH, PAR_L, expr(), PAR_R, OPT_LF(), BRACKET_L, OPT_LF(), zeroOrMore(enforcedSequence(KW_CASE, expr(), SP_COL, zeroOrMore(firstOf(stmt(), LF())))), optional(enforcedSequence(KW_DEFAULT, SP_COL, zeroOrMore(firstOf(stmt(), LF())))), OPT_LF(), BRACKET_R); } public Rule expr() { return assignExpr(); } public Rule assignExpr() { // check '=' first as is most common // moved localDef to statement since it can't be on the right hand side return sequence(ifExpr(), optional(enforcedSequence(firstOf(AS_EQUAL, AS_ASSIGN_OPS), OPT_LF(), assignExpr()))); } public Rule ifExpr() { // rewritten (together with ternaryTail, elvisTail) such as we check condOrExpr only once // this makes a gigantic difference in parser speed form original grammar return sequence(condOrExpr(), optional(firstOf(elvisTail(), ternaryTail()))); } public Rule ternaryTail() { return enforcedSequence(SP_QMARK, OPT_LF(), setNoSimpleMap(true), ifExprBody(), setNoSimpleMap(false), SP_COL, OPT_LF(), ifExprBody()); } public Rule elvisTail() { return enforcedSequence(OP_ELVIS, OPT_LF(), ifExprBody()); } public Rule ifExprBody() { return firstOf(enforcedSequence(KW_THROW, expr()), condOrExpr()); } public Rule condOrExpr() { return sequence(condAndExpr(), zeroOrMore(enforcedSequence(OP_OR, OPT_LF(), condAndExpr()))); } public Rule condAndExpr() { return sequence(equalityExpr(), zeroOrMore(enforcedSequence(OP_AND, OPT_LF(), equalityExpr()))); } public Rule equalityExpr() { return sequence(relationalExpr(), zeroOrMore(enforcedSequence(CP_EQUALITY, OPT_LF(), relationalExpr()))); } public Rule relationalExpr() { // Changed (with typeCheckTail, compareTail) to check for rangeExpr only once (way faster) return sequence(rangeExpr(), optional(firstOf(typeCheckTail(), compareTail()))); } public Rule typeCheckTail() { // changed to required, otherwise consumes all rangeExpr and compare never gets evaled return enforcedSequence(firstOf(KW_IS, KW_ISNOT, KW_AS), type()); } public Rule compareTail() { // changed to not be zeroOrMore as there can be only one comparaison check in an expression (no 3< x <5) return /*zeroOrMore(*/enforcedSequence(CP_COMPARATORS, OPT_LF(), rangeExpr())/*)*/; } public Rule rangeExpr() { // changed to not be zeroOrMore(opt instead) as there can be only one range in an expression (no [1..3..5]) return sequence(addExpr(), optional(enforcedSequence(firstOf(OP_RANGE_EXCL, OP_RANGE), OPT_LF(), addExpr()))); } public Rule addExpr() { return sequence(multExpr(), // checking it's not '+=' or '-=', so we can let assignExpr happen zeroOrMore(enforcedSequence(sequence(firstOf(OP_PLUS, OP_MINUS), testNot(AS_EQUAL)), OPT_LF(), multExpr()))); } public Rule multExpr() { return sequence(parExpr(), // checking it's not '*=', '/=' or '%=', so we can let assignExpr happen zeroOrMore(enforcedSequence(sequence(firstOf(OP_MULT, OP_DIV, OP_MODULO), testNot(AS_EQUAL)), OPT_LF(), parExpr()))); } public Rule parExpr() { return firstOf(castExpr(), groupedExpr(), unaryExpr()); } public Rule castExpr() { return sequence(PAR_L, type(), PAR_R, parExpr()); } public Rule groupedExpr() { return sequence(PAR_L, OPT_LF(), expr(), OPT_LF(), PAR_R, zeroOrMore(termChain())); } public Rule unaryExpr() { // grouped with postfixEpr to avoid looking for termExpr twice (very slow parsing !) return firstOf(prefixExpr(), sequence(termExpr(), optional(firstOf(OP_2MINUS, OP_2PLUS)))); } public Rule prefixExpr() { return sequence( firstOf(OP_CURRY, OP_BANG, OP_2PLUS, OP_2MINUS, OP_PLUS, OP_MINUS), parExpr()); } public Rule termExpr() { return sequence(termBase(), zeroOrMore(termChain())); } public Rule termBase() { // check for ID alone last (and not as part of idExpr) otherwise it would never check literal & typebase ! return firstOf(idExprReq(), litteral(), typeBase(), id()); } public Rule typeBase() { return firstOf( enforcedSequence(OP_POUND, id()), // slot litteral (without type) closure(), dsl(), // DSL // Optimized by grouping all the items that start with "type" (since looking for type if resource intensive) sequence(type(), firstOf( sequence(OP_POUND, optional(id())), // type/slot litteral sequence(DOT, KW_SUPER), // named super sequence(DOT, /*OPT_LF(),*/ idExpr()), // static call sequence(PAR_L, expr(), PAR_R), // "simple" itBlock() // ctor block ))); } public Rule dsl() { //TODO: unclosed DSL ? return sequence(simpleType(), enforcedSequence(DSL_OPEN, OPT_LF(), zeroOrMore(sequence(testNot(DSL_CLOSE), any())), OPT_LF(), DSL_CLOSE)); } public Rule closure() { return sequence(funcType(), OPT_LF(), enforcedSequence(BRACKET_L, zeroOrMore(stmt()), BRACKET_R)); } public Rule itBlock() { return sequence( OPT_LF(), enforcedSequence(sequence(BRACKET_L, // Note, don't allow field accesors to be parsed as itBlock peekTestNot(sequence(inFieldInit, OPT_LF(), firstOf(protection(), KW_STATIC, KW_READONLY, GET, SET, GET, SET)/*, echo("Skipping itBlock")*/))), zeroOrMore(stmt()), BRACKET_R)); } public Rule termChain() { return sequence(OPT_LF(), firstOf(safeDotCall(), safeDynCall(), dotCall(), dynCall(), indexExpr(), callOp(), itBlock()/*, incDotCall()*/)); } public Rule dotCall() { // test not "..", as this would be a range return enforcedSequence(sequence(DOT, testNot(DOT)), idExpr()); } public Rule dynCall() { return enforcedSequence(OP_ARROW, idExpr()); } public Rule safeDotCall() { return enforcedSequence(OP_SAFE_CALL, idExpr()); } public Rule safeDynCall() { return enforcedSequence(OP_SAFE_DYN_CALL, idExpr()); } // incomplete dot call, make valid to allow for completion public Rule incDotCall() { return DOT; } public Rule idExpr() { // this can be either a local def(toto.value) or a call(toto.getValue or toto.getValue(<params>)) + opt. closure return firstOf(idExprReq(), id()); } public Rule idExprReq() { // Same but without matching ID by itself (this would prevent termbase from checking literals). return firstOf(field(), call()); } // require '*' otherwise it's just and ID (this would prevent termbase from checking literals) public Rule field() { return sequence(OP_MULT, id()); } // require params or/and closure, otherwise it's just and ID (this would prevent termbase from checking literals) public Rule call() { return sequence(id(), firstOf( sequence(enforcedSequence(PAR_L, OPT_LF(), optional(args()), PAR_R), optional(closure())), //params & opt. closure closure())); // closure only } public Rule indexExpr() { return sequence(SQ_BRACKET_L, expr(), SQ_BRACKET_R); } public Rule callOp() { return enforcedSequence(PAR_L, optional(args()), PAR_R, optional(closure())); } public Rule litteral() { return firstOf(litteralBase(), list(), map()); } public Rule litteralBase() { return firstOf(KW_NULL, KW_THIS, KW_SUPER, KW_IT, KW_TRUE, KW_FALSE, strs(), uri(), number(), char_()); } public Rule list() { return sequence( optional(type()), OPT_LF(), SQ_BRACKET_L, OPT_LF(), listItems(), OPT_LF(), SQ_BRACKET_R); } public Rule listItems() { return firstOf( SP_COMMA, // allow extra comma sequence(expr(), zeroOrMore(sequence(SP_COMMA, OPT_LF(), expr())), optional(SP_COMMA))); } public Rule map() { return sequence( optional(firstOf(mapType(), simpleMapType())), // Not enforced to allow resolving list of typed maps like [Str:Int][] sequence(SQ_BRACKET_L, OPT_LF(), mapItems(), OPT_LF(), SQ_BRACKET_R)); } public Rule mapItems() { return firstOf(SP_COL,//empty map // allow extra comma sequence(mapPair(), zeroOrMore(sequence(SP_COMMA, OPT_LF(), mapPair())), optional(SP_COMMA))); } public Rule mapPair() { // allowing all expressions is probably more than really needed return sequence(expr(), enforcedSequence(SP_COL, expr())); } public Rule mapItem() { return expr(); } public Rule strs() { return firstOf( enforcedSequence("\"\"\"", // triple quoted string, // (not using 3QUOTE terminal, since it could eat empty space inside the string) zeroOrMore(firstOf( unicodeChar(), escapedChar(), sequence(testNot(QUOTES3), any()))), QUOTES3), enforcedSequence("\"", // simple string, (not using QUOTE terminal, since it could eat empty space inside the string) zeroOrMore(firstOf( unicodeChar(), escapedChar(), sequence(testNot(QUOTE), any()))), QUOTE)); } public Rule uri() { return enforcedSequence("`",// (not using TICK terminal, since it could eat empty space inside the string) zeroOrMore(firstOf( unicodeChar(), escapedChar(), sequence(testNot(TICK), any()))), TICK); } public Rule char_() { return firstOf( "' '", enforcedSequence('\'',// (not using SINGLE_Q terminal, since it could eat empty space inside the char) firstOf( unicodeChar(), escapedChar(), any()), //all else SINGLE_Q)); } public Rule escapedChar() { return enforcedSequence('\\', firstOf('b', 'f', 'n', 'r', 't', '"', '\'', '`', '$', '\\')); } public Rule unicodeChar() { return enforcedSequence("\\u", hexDigit(), hexDigit(), hexDigit(), hexDigit()); } public Rule hexDigit() { return firstOf(digit(), charRange('a', 'f'), charRange('A', 'F')); } public Rule digit() { return charRange('0', '9'); } public Rule number() { return sequence( optional(OP_MINUS), firstOf( // hex number enforcedSequence(firstOf("0x", "0X"), oneOrMore(firstOf("_", hexDigit()))), // decimal // fractional enforcedSequence(fraction(), optional(exponent())), enforcedSequence(digit(), zeroOrMore(sequence(zeroOrMore("_"), digit())), optional(fraction()), optional(exponent()))), optional(nbType()), OPT_SP); } public Rule fraction() { // not enfored to allow: "3.times ||" constructs as well as ranges 3..5 return sequence(DOT, digit(), zeroOrMore(sequence(zeroOrMore("_"), digit()))); } public Rule exponent() { return enforcedSequence(charSet("eE"), optional(firstOf(OP_PLUS, OP_MINUS)), digit(), zeroOrMore(sequence(zeroOrMore("_"), digit()))); } public Rule nbType() { return firstOf( "day", "hr", "min", "sec", "ms", "ns", //durations "f", "F", "D", "d" // float / decimal ); } /** Rewrote more like Fantom Parser (simpler & faster) - lokffor type base then listOfs, mapOfs notations * Added check so that the "?" (nullable type indicator) cannot be separated from it's type (noSpace) * @return */ public Rule type() { return sequence( firstOf( mapType(), funcType(), sequence(id(), optional(sequence(noSpace(), SP_COLCOL, noSpace(), id()))) ), // Look for optional map/list/nullable items optional(sequence(noSpace(), SP_QMARK)), //nullable zeroOrMore(sequence(noSpace(),SQ_BRACKET_L, SQ_BRACKET_R)),//list(s) // Do not allow simple maps within left side of expressions ... this causes issues with ":" optional(sequence(peekTestNot(noSimpleMap), SP_COL, type())),//simple map Int:Str optional(sequence(noSpace(), SP_QMARK)) // nullable list/map ); } public Rule simpleMapType() { // It has to be other nonSimpleMapTypes, otherwise it's left recursive (loops forever) return sequence(nonSimpleMapTypes(), SP_COL, nonSimpleMapTypes(), optional( // Not enforcing [] because of problems with maps like this Str:int["":5] sequence(optional(SP_QMARK), SQ_BRACKET_L, SQ_BRACKET_R)), // list of '?[]' optional(SP_QMARK)); // nullable } // all types except simple map public Rule nonSimpleMapTypes() { return sequence( firstOf(funcType(), mapType(), simpleType()), optional( // Not enforcing [] because of problems with maps like this Str:int["":5] sequence(optional(SP_QMARK), SQ_BRACKET_L, SQ_BRACKET_R)), // list of '?[]' optional(SP_QMARK)); // nullable } public Rule simpleType() { return sequence( id(), optional(enforcedSequence(SP_COLCOL, id()))); } public Rule mapType() { // We use nonSimpleMapTypes here as well, because [Str:Int:Str] would be confusing // not enforced to allow map rule to work ([Int:Str][5,""]) return sequence(SQ_BRACKET_L, nonSimpleMapTypes(), SP_COL, nonSimpleMapTypes(), SQ_BRACKET_R); } public Rule funcType() { return sequence( testNot(OP_OR), // '||' that's a logical OR not a function type // '|' could be the closing pipe so we can't enforce sequence(SP_PIPE, firstOf( // First we check for one with no formals |->| or |->Str| enforcedSequence(OP_ARROW, optional(type())), // Then we check for one with formals |Int i| or maybe full: |Int i -> Str| sequence(formals(), optional(enforcedSequence(OP_ARROW, optional(type()))))), SP_PIPE)); } public Rule formals() { // Allowing funcType within formals | |Int-Str a| -> Str| return sequence( typeAndOrId(), zeroOrMore(enforcedSequence(SP_COMMA, typeAndOrId()))); } public Rule typeList() { return sequence(type(), zeroOrMore(enforcedSequence(SP_COMMA, type()))); } public Rule typeAndOrId() { // Note it can be "type id", "type" or "id" // but parser can't know if it's "type" or "id" so always recognize as type // so would never actually hit id() return firstOf(sequence(type(), id()), type()); } public Rule id() { return sequence(testNot(keyword()), firstOf(charRange('A', 'Z'), charRange('a', 'z'), "_"), zeroOrMore(firstOf(charRange('A', 'Z'), charRange('a', 'z'), '_', charRange('0', '9'))), OPT_SP); } public Rule doc() { // In theory there are no empty lines betwen doc and type ... but thta does happen so alowing it return oneOrMore(sequence(OPT_SP, "**", zeroOrMore(sequence(testNot("\n"), any())), OPT_LF())); } @Leaf public Rule spacing() { return oneOrMore(firstOf( // whitespace (Do NOT eat \n since it can be meaningful) oneOrMore(charSet(" \t\u000c")), // multiline comment sequence("/*", zeroOrMore(sequence(testNot("*/"), any())), "*/"), // normal comment // if incomplete multiline comment, then end at end of line sequence("/*", zeroOrMore(sequence(testNot(charSet("\r\n")), any()))/*, charSet("\r\n")*/), // single line comment sequence("//", zeroOrMore(sequence(testNot(charSet("\r\n")), any()))/*, charSet("\r\n")*/))); } public Rule LF() { return sequence(oneOrMore(sequence(OPT_SP, charSet("\n\r"))), OPT_SP); } public Rule OPT_LF() { return optional(LF()); } @Leaf public Rule keyword(String string) { // Makes sure not to match things that START with a keyword like "thisisatest" return sequence(string, testNot(firstOf(digit(), charRange('A', 'Z'), charRange('a', 'z'), "_")), optional(spacing())).label(string); } @Leaf public Rule terminal(String string) { return sequence(string, optional(spacing())).label(string); } @Leaf public Rule terminal(String string, Rule mustNotFollow) { return sequence(string, testNot(mustNotFollow), optional(spacing())).label(string); } public Rule keyword() { return sequence( // don't bother unless it starts with 'a'-'z' test(charRange('a', 'z')), firstOf(KW_ABSTRACT, KW_AS, KW_ASSERT, KW_BREAK, KW_CATCH, KW_CASE, KW_CLASS, KW_CONST, KW_CONTINUE, KW_DEFAULT, KW_DO, KW_ELSE, KW_FALSE, KW_FINAL, KW_FINALLY, KW_FOR, KW_FOREACH, KW_IF, KW_INTERNAL, KW_IS, KW_ISNOT, KW_IT, KW_MIXIN, KW_NATIVE, KW_NEW, KW_NULL, KW_ONCE, KW_OVERRIDE, KW_PRIVATE, KW_PROTECTED, KW_PUBLIC, KW_READONLY, KW_RETURN, KW_STATIC, KW_SUPER, KW_SWITCH, KW_THIS, KW_THROW, KW_TRUE, KW_TRY, KW_USING, KW_VIRTUAL, KW_VOID, KW_VOLATILE, KW_WHILE)); } // -- Keywords -- public final Rule KW_ABSTRACT = keyword("abstract"); public final Rule KW_AS = keyword("as"); public final Rule KW_ASSERT = keyword("assert"); // not a grammar kw public final Rule KW_BREAK = keyword("break"); public final Rule KW_CATCH = keyword("catch"); public final Rule KW_CASE = keyword("case"); public final Rule KW_CLASS = keyword("class"); public final Rule KW_CONST = keyword("const"); public final Rule KW_CONTINUE = keyword("continue"); public final Rule KW_DEFAULT = keyword("default"); public final Rule KW_DO = keyword("do"); // unused, reserved public final Rule KW_ELSE = keyword("else"); public final Rule KW_FALSE = keyword("false"); public final Rule KW_FINAL = keyword("final"); public final Rule KW_FINALLY = keyword("finally"); public final Rule KW_FOR = keyword("for"); public final Rule KW_FOREACH = keyword("foreach"); // unused, reserved public final Rule KW_IF = keyword("if"); public final Rule KW_INTERNAL = keyword("internal"); public final Rule KW_IS = keyword("is"); public final Rule KW_IT = keyword("ii"); public final Rule KW_ISNOT = keyword("isnot"); public final Rule KW_MIXIN = keyword("mixin"); public final Rule KW_NATIVE = keyword("native"); public final Rule KW_NEW = keyword("new"); public final Rule KW_NULL = keyword("null"); public final Rule KW_ONCE = keyword("once"); public final Rule KW_OVERRIDE = keyword("override"); public final Rule KW_PRIVATE = keyword("private"); public final Rule KW_PUBLIC = keyword("public"); public final Rule KW_PROTECTED = keyword("protected"); public final Rule KW_READONLY = keyword("readonly"); public final Rule KW_RETURN = keyword("return"); public final Rule KW_STATIC = keyword("static"); public final Rule KW_SUPER = keyword("super"); public final Rule KW_SWITCH = keyword("switch"); public final Rule KW_THIS = keyword("this"); public final Rule KW_THROW = keyword("throw"); public final Rule KW_TRUE = keyword("true"); public final Rule KW_TRY = keyword("try"); public final Rule KW_USING = keyword("using"); public final Rule KW_VIRTUAL = keyword("virtual"); public final Rule KW_VOID = keyword("void"); // unused, reserved public final Rule KW_VOLATILE = keyword("volatile"); // unused, reserved public final Rule KW_WHILE = keyword("while"); // Non keyword meningful items public final Rule ENUM = keyword("enum"); public final Rule FACET = keyword("facet"); public final Rule GET = keyword("get"); public final Rule SET = keyword("set"); // operators public final Rule OP_SAFE_CALL = terminal("?."); public final Rule OP_SAFE_DYN_CALL = terminal("?->"); public final Rule OP_ARROW = terminal("->"); public final Rule OP_ASSIGN = terminal(":="); public final Rule OP_ELVIS = terminal("?:"); public final Rule OP_OR = terminal("||"); public final Rule OP_AND = terminal("&&"); public final Rule OP_RANGE = terminal(".."); public final Rule OP_RANGE_EXCL = terminal("..<"); public final Rule OP_CURRY = terminal("&"); public final Rule OP_BANG = terminal("!"); public final Rule OP_2PLUS = terminal("++"); public final Rule OP_2MINUS = terminal(" public final Rule OP_PLUS = terminal("+"); public final Rule OP_MINUS = terminal("-"); public final Rule OP_MULT = terminal("*"); public final Rule OP_DIV = terminal("/"); public final Rule OP_MODULO = terminal("%"); public final Rule OP_POUND = terminal(" // comparators public final Rule CP_EQUALITY = firstOf(terminal("==="), terminal("!=="), terminal("=="), terminal("!=")); public final Rule CP_COMPARATORS = firstOf(terminal("<=>"), terminal("<="), terminal(">="), terminal("<"), terminal(">")); // separators public final Rule SP_PIPE = terminal("|"); public final Rule SP_QMARK = terminal("?"); public final Rule SP_COLCOL = terminal("::"); public final Rule SP_COL = terminal(":"); public final Rule SP_COMMA = terminal(","); public final Rule SP_SEMI = terminal(";"); // assignment public final Rule AS_EQUAL = terminal("="); public final Rule AS_ASSIGN_OPS = firstOf(terminal("*="), terminal("/="), terminal("%="), terminal("+="), terminal("-=")); // others public final Rule QUOTES3 = terminal("\"\"\""); public final Rule QUOTE = terminal("\""); public final Rule TICK = terminal("`"); public final Rule SINGLE_Q = terminal("'"); public final Rule DOT = terminal("."); public final Rule AT = terminal("@"); public final Rule DSL_OPEN = terminal("<|"); public final Rule DSL_CLOSE = terminal("|>"); public final Rule SQ_BRACKET_L = terminal("["); public final Rule SQ_BRACKET_R = terminal("]"); public final Rule BRACKET_L = terminal("{"); public final Rule BRACKET_R = terminal("}"); public final Rule PAR_L = terminal("("); public final Rule PAR_R = terminal(")"); // shortcut for optional spacing public final Rule OPT_SP = optional(spacing()); /** * Override because sandard firstOf() complains about empty matches * and we allow empty matches in peekTest * @param rules * @return */ @Override @Cached public Rule firstOf(Object[] rules) { return new PeekFirstOfMatcher(toRules(rules)); } /** * Custom test matchers which allow result without matching any data (boolean check) * @param rule * @return */ @Cached public Rule peekTestNot(Object rule) { return new PeekTestMatcher(toRule(rule), true); } @Cached public Rule peekTest(Object rule) { return new PeekTestMatcher(toRule(rule), false); } /** * Custom action to find an end of statement * @return */ public Rule eos() { return sequence(OPT_SP, firstOf( SP_SEMI, LF(), peekTest(BRACKET_R), // '}' is end of statement too, but do NOT consume it ! peekTest(eoi()))); // EOI is end of statement too, but do NOT consume it ! } /**Pass if not following some whitespace*/ public Rule noSpace() { return peekTestNot(afterSpace()); } public boolean afterSpace() { char c = getContext().getCurrentLocation().lookAhead(getContext().getInputBuffer(), -1); return Character.isWhitespace(c); } public boolean setFieldInit(boolean val) { inFieldInit = val; return true; } public boolean setNoSimpleMap(boolean val) { noSimpleMap = val; return true; } public boolean setInEnum(boolean val) { inEnum = val; return true; } // Debugging utils /** System.out - eval to true*/ public boolean echo(String str) { System.out.println(str); return true; } /** System.out - eval to false*/ public boolean echof(String str) { System.out.println(str); return false; } /** System.out current node path - eval to true*/ public boolean printPath() { System.out.println(getContext().getPath()); return true; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan.project; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.spi.project.ui.LogicalViewProvider; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.nodes.AbstractNode; import org.openide.nodes.FilterNode.Children; import org.openide.nodes.Node; import org.openide.util.Exceptions; /** * Logical view for Fan project * Logical View provides the nodeTree for displaying project files tree in "project" tab of netbeans * So we can show/hide and group files ina logical way. * @author thibautc */ public class FanLogicalView implements LogicalViewProvider { public static final String REGISTERED_NODE_LOCATION = "Projects/net-colar-netbeans-fan-project-FanProject/Nodes"; private final FanProject project; public FanLogicalView(FanProject project) { this.project = project; } @Override public Node createLogicalView() { try { FileObject dir = project.getProjectDirectory(); //Get the DataObject that represents it: DataObject dobj = DataObject.find(dir); //Get its default node: we'll wrap our node around it to change the //display name, icon, etc: Node originalObj = dobj.getNodeDelegate(); //This FilterNode will be our project node: return new FanProjectNode(project, originalObj, dir); } catch (DataObjectNotFoundException donfe) { Exceptions.printStackTrace(donfe); //Fallback: the directory couldn't be created - //read-only filesystem or something evil happened: return new AbstractNode(Children.LEAF); } } /** * Find the Node for a given file * @param root * @param target * @return */ @Override public Node findPath(Node root, Object target) { Project prj = root.getLookup().lookup(Project.class); if (prj == null) { return null; } if (target instanceof FileObject) { FileObject fo = (FileObject) target; Project owner = FileOwnerQuery.getOwner(fo); if (!prj.equals(owner)) { return null; } String relativePath = FileUtil.getRelativePath(prj.getProjectDirectory(), fo); return findMatchingNode(root, relativePath); } return null; } /** * Find the subNode within the node that matches the path (relative path) * Note: recursive * @param node * @param path * @return */ public static Node findMatchingNode(Node node, String path) { if (path == null) { return null; } String[] parts = path.split("/"); if (parts.length == 0) { return null; } for (Node nd : node.getChildren().getNodes(true)) { String name = nd.getDisplayName(); if (name.equals(parts[0])) { if (parts.length == 1) { // that was the last part of the path to match -> we found our node. return nd; } else { if (path.indexOf("/") == path.length()) { return nd; // directory, ignore extra slash } else { // matches so far, keep digging down the path (recurse) return findMatchingNode(nd, path.substring(path.indexOf("/") + 1)); } } } } // not found return null; } }
package net.maizegenetics.pal.report; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import net.maizegenetics.util.DoubleFormat; public class TableReportUtils { public static String toDelimitedString(TableReport theTableSource, String delimit, String headerName, String headerValue) { Object[] colNames = theTableSource.getTableColumnNames(); StringBuilder sb = new StringBuilder(); int cols; cols = colNames.length; int rows = theTableSource.getRowCount(); if (headerName != null) { sb.append(headerName + delimit); } for (int j = 0; j < cols; j++) { sb.append(colNames[j]); if (j < (cols - 1)) { sb.append(delimit); } } sb.append("\n"); if (headerValue != null) { sb.append(headerValue + delimit); } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { sb.append(theTableSource.getValueAt(i, j)); if (j < (cols - 1)) { sb.append(delimit); } } sb.append("\n"); } return sb.toString(); } public static String toDelimitedString(TableReport theTableSource, String delimit) { return toDelimitedString(theTableSource, delimit, null, null); } public static void saveDelimitedTableReport(TableReport theTableSource, String delimit, File saveFile) { if (saveFile == null) { return; } FileWriter fw = null; BufferedWriter bw = null; try { fw = new FileWriter(saveFile); bw = new BufferedWriter(fw); Object[] colNames = theTableSource.getTableColumnNames(); for (int j = 0; j < colNames.length; j++) { if (j != 0) { bw.write(delimit); } bw.write(colNames[j].toString()); } bw.write("\n"); for (int r = 0, n = theTableSource.getRowCount(); r < n; r++) { Object[] theRow = theTableSource.getRow(r); for (int i = 0; i < theRow.length; i++) { if (i != 0) { bw.write(delimit); } if (theRow[i] == null) { // do nothing } else if (theRow[i] instanceof Double) { bw.write(DoubleFormat.format((Double) theRow[i])); } else { bw.write(theRow[i].toString()); } } bw.write("\n"); } } catch (Exception e) { e.printStackTrace(); System.out.println("TableReportUtils: writeReport: problem writing file: " + e.getMessage()); } finally { try { bw.close(); fw.close(); } catch (Exception e) { // do nothing } } } }
package net.maizegenetics.pal.report; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import net.maizegenetics.util.DoubleFormat; import net.maizegenetics.util.ExceptionUtils; import net.maizegenetics.util.Utils; /** * @author terry */ public class TableReportUtils { public static void saveDelimitedTableReport(TableReport theTableSource, String delimit, File saveFile) { if (saveFile == null) { return; } BufferedWriter bw = null; try { bw = Utils.getBufferedWriter(saveFile); Object[] colNames = theTableSource.getTableColumnNames(); for (int j = 0; j < colNames.length; j++) { if (j != 0) { bw.write(delimit); } bw.write(colNames[j].toString()); } bw.write("\n"); for (int r = 0, n = theTableSource.getRowCount(); r < n; r++) { Object[] theRow = theTableSource.getRow(r); for (int i = 0; i < theRow.length; i++) { if (i != 0) { bw.write(delimit); } if (theRow[i] == null) { // do nothing } else if (theRow[i] instanceof Double) { bw.write(DoubleFormat.format((Double) theRow[i])); } else { bw.write(theRow[i].toString()); } } bw.write("\n"); } } catch (Exception e) { e.printStackTrace(); System.out.println("TableReportUtils: writeReport: problem writing file: " + e.getMessage()); } finally { try { bw.close(); } catch (Exception e) { // do nothing } } } public static TableReport readDelimitedTableReport(String saveFile, String delimit) { int numLines = -1; BufferedReader reader = null; try { reader = Utils.getBufferedReader(saveFile, 1000000); while (reader.readLine() != null) { numLines++; } } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("Problem creating TableReport: " + saveFile + ": " + ExceptionUtils.getExceptionCauses(e)); } finally { try { reader.close(); } catch (Exception ex) { // do nothing } } BufferedReader br = null; try { br = Utils.getBufferedReader(saveFile); String[] columnHeaders = br.readLine().trim().split(delimit); String[][] data = new String[numLines][]; for (int i = 0; i < numLines; i++) { data[i] = br.readLine().trim().split(delimit); } return new SimpleTableReport(saveFile, columnHeaders, data); } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("Problem creating TableReport: " + saveFile + ": " + ExceptionUtils.getExceptionCauses(e)); } finally { try { br.close(); } catch (Exception ex) { // do nothing } } } }
package net.sf.jaer.eventio.ros; import com.github.swrirobotics.bags.reader.BagFile; import com.github.swrirobotics.bags.reader.BagReader; import com.github.swrirobotics.bags.reader.TopicInfo; import com.github.swrirobotics.bags.reader.exceptions.BagReaderException; import com.github.swrirobotics.bags.reader.exceptions.UninitializedFieldException; import com.github.swrirobotics.bags.reader.messages.serialization.ArrayType; import com.github.swrirobotics.bags.reader.messages.serialization.BoolType; import com.github.swrirobotics.bags.reader.messages.serialization.Field; import com.github.swrirobotics.bags.reader.messages.serialization.Float32Type; import com.github.swrirobotics.bags.reader.messages.serialization.Float64Type; import com.github.swrirobotics.bags.reader.messages.serialization.Int32Type; import com.github.swrirobotics.bags.reader.messages.serialization.MessageType; import com.github.swrirobotics.bags.reader.messages.serialization.TimeType; import com.github.swrirobotics.bags.reader.messages.serialization.UInt16Type; import com.github.swrirobotics.bags.reader.messages.serialization.UInt32Type; import com.google.common.collect.HashMultimap; import eu.seebetter.ini.chips.davis.DavisBaseCamera; import eu.seebetter.ini.chips.davis.imu.IMUSample; import eu.seebetter.ini.chips.davis.imu.IMUSampleType; import java.awt.Point; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.BufferedInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.FileChannel; import java.sql.Timestamp; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ProgressMonitor; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEFileInputStreamInterface; import net.sf.jaer.eventio.AEInputStream; import org.apache.commons.lang3.mutable.MutableBoolean; public class RosbagFileInputStream implements AEFileInputStreamInterface, RosbagTopicMessageSupport { private static final Logger log = Logger.getLogger("RosbagFileInputStream"); private final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * File name extension for ROS bag files, excluding ".", i.e. "bag". Note * this lack of . is different than for AEDataFile.DATA_FILE_EXTENSION. */ public static final String DATA_FILE_EXTENSION = "bag"; // for converting ROS units to jAER units private static final float DEG_PER_RAD = 180f / (float) Math.PI, G_PER_MPS2 = 1 / 9.8f; /** * The AEChip object associated with this stream. This field was added for * supported jAER 3.0 format files to support translating bit locations in * events. */ private AEChip chip = null; private File file = null; BagFile bagFile = null; // the most recently read event timestamp and the largest one read so far in this playback cycle private int mostRecentTimestamp, largestTimestampReadSinceRewind = Integer.MIN_VALUE; // first and last timestamp in the entire recording private long firstTimestamp, lastTimestamp; private long firstTimestampUsAbsolute; // the absolute (ROS) first timestamp in us private boolean firstTimestampWasRead = false; // marks the present read time for packets private int currentStartTimestamp; private final ApsDvsEventPacket<ApsDvsEvent> eventPacket; private AEPacketRaw aePacketRawBuffered = new AEPacketRaw(), aePacketRawOutput = new AEPacketRaw(), aePacketRawTmp = new AEPacketRaw(); private AEPacketRaw emptyPacket = new AEPacketRaw(); private int nextMessageNumber = 0, numMessages = 0; private long absoluteStartingTimeMs = 0; // in system time since 1970 in ms /** * The ZoneID of this file; for ROS bag files there is no recorded time zone * so the zoneId is systemDefault() */ private ZoneId zoneId = ZoneId.systemDefault(); private FileChannel channel = null; // private static final String[] TOPICS = {"/dvs/events"};\ private static final String RPG_TOPIC_HEADER = "/dvs/", MVSEC_TOPIC_HEADER = "/davis/left/"; // TODO arbitrarily choose left camera for MVSEC for now private static final String TOPIC_EVENTS = "events", TOPIC_IMAGE = "image_raw", TOPIC_IMU = "imu", TOPIC_EXPOSURE = "exposure"; private static String[] STANARD_TOPICS = {TOPIC_EVENTS, TOPIC_IMAGE/*, TOPIC_IMU, TOPIC_EXPOSURE*/}; // tobi 4.1.21 commented out the IMU and EXPOSURE (never seen) topics since they cause problems with nonmonotonic timestamps in the MVSEC recrordings. Cause unknown. TODO fix IMU reading. // private static String[] TOPICS = {TOPIC_HEADER + TOPIC_EVENTS, TOPIC_HEADER + TOPIC_IMAGE}; private ArrayList<String> topicList = new ArrayList(); private ArrayList<String> topicFieldNames = new ArrayList(); private boolean wasIndexed = false; private List<BagFile.MessageIndex> msgIndexes = new ArrayList(); private HashMultimap<String, PropertyChangeListener> msgListeners = HashMultimap.create(); private boolean firstReadCompleted = false; private ArrayList<String> extraTopics = null; // extra topics that listeners can subscribe to private boolean nonMonotonicTimestampExceptionsChecked = true; private boolean nonMonotonicTimestampDetected = false; // flag set by nonmonotonic timestamp if detection enabled private boolean rewindFlag = false; // FIFOs to buffer data so that we only let out data from any stream if there is definitely later data from both other streams private MutableBoolean hasDvs = new MutableBoolean(false), hasAps = new MutableBoolean(false), hasImu = new MutableBoolean(false); // flags to say what data is in this stream private long lastDvsTimestamp = 0, lastApsTimestamp = 0, lastImuTimestamp = 0; // used to check monotonicity private AEFifo dvsFifo = new AEFifo(), apsFifo = new AEFifo(), imuFifo = new AEFifo(); private MutableBoolean[] hasDvsApsImu = {hasDvs, hasAps, hasImu}; private AEFifo[] aeFifos = {dvsFifo, apsFifo, imuFifo}; private int MAX_RAW_EVENTS_BUFFER_SIZE = 1000000; private enum RosbagFileType { RPG(RPG_TOPIC_HEADER), MVSEC(MVSEC_TOPIC_HEADER), Unknown("???"); private String header; private RosbagFileType(String header) { this.header = header; } } // two types of topics depending on format of rosbag RosbagFileType rosbagFileType = RosbagFileType.Unknown; /** * Interval for logging warnings about nonmonotonic timestamps. */ public static final int NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL = 1000000; private int nonmonotonicTimestampCounter = 0; private int lastExposureUs; // holds last exposure value (in us?) to use for creating SOE and EOE events for frames private int markIn = 0; private int markOut; private boolean repeatEnabled = true; /** * Makes a new instance for a file and chip. A progressMonitor can pop up a * dialog for the long indexing operation * * @param f the file * @param chip the AEChip * @param progressMonitor an optional ProgressMonitor, set to null if not * desired * @throws BagReaderException * @throws java.lang.InterruptedException if constructing the stream which * requires indexing the topics takes a long time and the operation is * canceled */ public RosbagFileInputStream(File f, AEChip chip, ProgressMonitor progressMonitor) throws BagReaderException, InterruptedException { this.eventPacket = new ApsDvsEventPacket<>(ApsDvsEvent.class); setFile(f); this.chip = chip; log.info("reading rosbag file " + f + " for chip " + chip); bagFile = BagReader.readFile(file); StringBuilder sb = new StringBuilder("Bagfile information:\n"); for (TopicInfo topic : bagFile.getTopics()) { sb.append(topic.getName() + " \t\t" + topic.getMessageCount() + " msgs \t: " + topic.getMessageType() + " \t" + (topic.getConnectionCount() > 1 ? ("(" + topic.getConnectionCount() + " connections)") : "") + "\n"); if (topic.getName().contains(RosbagFileType.MVSEC.header)) { rosbagFileType = RosbagFileType.MVSEC; } else if (topic.getName().contains(RosbagFileType.RPG.header)) { rosbagFileType = RosbagFileType.RPG; } } sb.append("Duration: " + bagFile.getDurationS() + "s\n"); sb.append("Chunks: " + bagFile.getChunks().size() + "\n"); sb.append("Num messages: " + bagFile.getMessageCount() + "\n"); sb.append("File type is detected as " + rosbagFileType); log.info(sb.toString()); for (String s : STANARD_TOPICS) { String topic = rosbagFileType.header + s; topicList.add(topic); topicFieldNames.add(topic.substring(topic.lastIndexOf("/") + 1)); // strip off header to get to field name for the ArrayType } generateMessageIndexes(progressMonitor); } @Override public Collection<String> getMessageListenerTopics() { return msgListeners.keySet(); } // // causes huge memory usage by building hashmaps internally, using index instead by prescanning file // private MsgIterator getMsgIterator() throws BagReaderException { //// messages=bagFile.getMessages(); // conns = bagFile.getConnections(); // ArrayList<Connection> myConnections = new ArrayList(); // for (Connection conn : conns) { // String topic = conn.getTopic(); //// log.info("connection "+conn+" has topic "+topic); // for (String t : TOPICS) { // if (t.equals(topic)) { //// log.info("topic matches " + t + "; adding this connection to myConnections. This message has definition " + conn.getMessageDefinition()); // log.info("topic matches " + t + "; adding this connection to myConnections"); // myConnections.appendCopy(conn); // chunkInfos = bagFile.getChunkInfos(); // try { // channel = bagFile.getChannel(); // } catch (IOException ex) { // Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex); // throw new BagReaderException(ex.toString()); // MsgIterator itr = new MsgIterator(chunkInfos, myConnections, channel); // return itr; /** * Adds information to a message from the index entry for it */ public class MessageWithIndex { public MessageType messageType; public BagFile.MessageIndex messageIndex; public int ourIndex; public MessageWithIndex(MessageType messageType, BagFile.MessageIndex messageIndex, int ourIndex) { this.messageType = messageType; this.messageIndex = messageIndex; this.ourIndex=ourIndex; } @Override public String toString() { return String.format("MessagesWithIndex with ourIndex=%d, MessageType [package=%s, name=%s, type=%s], MessageIndex %s", ourIndex, messageType.getPackage(),messageType.getName(), messageType.getType(), messageIndex.toString()); //To change body of generated methods, choose Tools | Templates. } } synchronized private MessageWithIndex getNextMsg() throws BagReaderException, EOFException { MessageType msg = null; try { if (nextMessageNumber == markOut) { // TODO check exceptions here for markOut set before markIn throw new EOFException("Hit OUT marker at messange number "+markOut); } msg = bagFile.getMessageFromIndex(msgIndexes, nextMessageNumber); } catch (ArrayIndexOutOfBoundsException e) { throw new EOFException("Hit ArrayIndexOutOfBoundsException, probably at end of file"); } catch (IOException e) { throw new EOFException("Hit IOException at end of file"); } MessageWithIndex rtn = new MessageWithIndex(msg, msgIndexes.get(nextMessageNumber), nextMessageNumber); nextMessageNumber++; return rtn; } /** * Given ROS Timestamp, this method computes the us timestamp relative to * the first timestamp in the recording * * @param timestamp a ROS Timestamp from a Message, either header or DVS * event * @param updateLargestTimestamp true if we want to update the largest * timestamp with this value, false if we leave it unchanged * * @return timestamp for jAER in us */ private int getTimestampUsRelative(Timestamp timestamp, boolean updateLargestTimestamp) { // updateLargestTimestamp = true; // TODO hack before removing long tsNs = timestamp.getNanos(); // gets the fractional seconds in ns long tsMs = timestamp.getTime(); // the time in ms including ns, i.e. time(s)*1000+ns/1000000. long timestampUsAbsolute = (1000000 * (tsMs / 1000)) + tsNs / 1000; // truncate ms back to s, then turn back to us, then appendCopy fractional part of s in us if (!firstTimestampWasRead) { firstTimestampUsAbsolute = timestampUsAbsolute; firstTimestampWasRead = true; } int ts = (int) (timestampUsAbsolute - firstTimestampUsAbsolute); // if (ts == 0) { // log.warning("zero timestamp detected for Image "); if (updateLargestTimestamp && ts >= largestTimestampReadSinceRewind) { largestTimestampReadSinceRewind = ts; } final int dt = ts - mostRecentTimestamp; if (dt < 0 && nonMonotonicTimestampExceptionsChecked) { if (nonmonotonicTimestampCounter % NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL == 0) { log.warning("Nonmonotonic timestamp=" + timestamp + " with dt=" + dt + "; replacing with largest timestamp=" + largestTimestampReadSinceRewind + "; skipping next " + NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL + " warnings"); } nonmonotonicTimestampCounter++; ts = largestTimestampReadSinceRewind; // replace actual timestamp with largest one so far nonMonotonicTimestampDetected = true; } else { nonMonotonicTimestampDetected = false; } mostRecentTimestamp = ts; return ts; } /** * Typical file info about contents of a bag file recorded on Traxxas slash * platform INFO: Bagfile information: * /davis_ros_driver/parameter_descriptions 1 msgs : * dynamic_reconfigure/ConfigDescription /davis_ros_driver/parameter_updates * 1 msgs : dynamic_reconfigure/Config /dvs/events 8991 msgs : * dvs_msgs/EventArray /dvs/exposure 4751 msgs : std_msgs/Int32 * /dvs/image_raw 4758 msgs : sensor_msgs/Image /dvs/imu 298706 msgs : * sensor_msgs/Imu /dvs_accumulated_events 124 msgs : sensor_msgs/Image * /dvs_accumulated_events_edges 124 msgs : sensor_msgs/Image /dvs_rendering * 4034 msgs : sensor_msgs/Image /events_off_mean_1 186 msgs : * std_msgs/Float32 /events_off_mean_5 56 msgs : std_msgs/Float32 * /events_on_mean_1 186 msgs : std_msgs/Float32 /events_on_mean_5 56 msgs : * std_msgs/Float32 /raw_pwm 2996 msgs : rally_msgs/Pwm /rosout 12 msgs : * rosgraph_msgs/Log (4 connections) /rosout_agg 12 msgs : rosgraph_msgs/Log * duration: 299.578s Chunks: 0 Num messages: 324994 */ /** * Gets the next raw packet. The packets are buffered to ensure that all the * data is monotonic in time. * * @return the packet */ synchronized private AEPacketRaw getNextRawPacket() throws EOFException, BagReaderException { DavisBaseCamera davisCamera = null; if (chip instanceof DavisBaseCamera) { davisCamera = (DavisBaseCamera) chip; } OutputEventIterator<ApsDvsEvent> outItr = eventPacket.outputIterator(); // to hold output events ApsDvsEvent e = new ApsDvsEvent(); try { boolean gotEventsOrFrame = false; while (!gotEventsOrFrame) { MessageWithIndex message = getNextMsg(); // send to listeners if topic is one we have subscribers for String topic = message.messageIndex.topic; Set<PropertyChangeListener> listeners = msgListeners.get(topic); if (!listeners.isEmpty()) { for (PropertyChangeListener l : listeners) { l.propertyChange(new PropertyChangeEvent(this, topic, null, message)); } } // now deal with standard DAVIS data String pkg = message.messageType.getPackage(); String type = message.messageType.getType(); switch (pkg) { case "std_msgs": { // exposure MessageType messageType = message.messageType; // List<String> fieldNames = messageType.getFieldNames(); try { int exposureUs = messageType.<Int32Type>getField("data").getValue(); lastExposureUs = (int) (exposureUs); } catch (Exception ex) { float exposureUs = messageType.<Float32Type>getField("data").getValue(); lastExposureUs = (int) (exposureUs); // hack to deal with recordings made with pre-Int32 version of rpg-ros-dvs } } break; case "sensor_msgs": switch (type) { case "Image": { // Make sure the image is from APS, otherwise some other image topic will be also processed here. if (!(topic.equalsIgnoreCase(MVSEC_TOPIC_HEADER+"image_raw") || topic.equalsIgnoreCase(RPG_TOPIC_HEADER+"image_raw"))) { continue; } hasAps.setTrue(); MessageType messageType = message.messageType; // List<String> fieldNames = messageType.getFieldNames(); MessageType header = messageType.getField("header"); ArrayType data = messageType.<ArrayType>getField("data"); // int width = (int) (messageType.<UInt32Type>getField("width").getValue()).intValue(); // int height = (int) (messageType.<UInt32Type>getField("height").getValue()).intValue(); Timestamp timestamp = header.<TimeType>getField("stamp").getValue(); int ts = getTimestampUsRelative(timestamp, true); // don't update largest timestamp with frame time gotEventsOrFrame = true; byte[] bytes = data.getAsBytes(); final int sizey1 = chip.getSizeY() - 1, sizex = chip.getSizeX(); // construct frames as events, so that reconstuction as raw packet results in frame again. // what a hack... // start of frame e.setReadoutType(ApsDvsEvent.ReadoutType.SOF); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts); maybePushEvent(e, apsFifo, outItr); // start of exposure e.setReadoutType(ApsDvsEvent.ReadoutType.SOE); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts); maybePushEvent(e, apsFifo, outItr); Point firstPixel = new Point(0, 0), lastPixel = new Point(chip.getSizeX() - 1, chip.getSizeY() - 1); if (davisCamera != null) { firstPixel.setLocation(davisCamera.getApsFirstPixelReadOut()); lastPixel.setLocation(davisCamera.getApsLastPixelReadOut()); } int xinc = firstPixel.x < lastPixel.x ? 1 : -1; int yinc = firstPixel.y < lastPixel.y ? 1 : -1; // see AEFrameChipRenderer for putting event streams into textures to be drawn, // in particular AEFrameChipRenderer.renderApsDvsEvents // and AEFrameChipRenderer.updateFrameBuffer for how cooked event stream is interpreted // see ChipRendererDisplayMethodRGBA for OpenGL drawing of textures of frames // see DavisBaseCamera.DavisEventExtractor for extraction of event stream // See specific chip classes, e.g. Davis346mini for setup of first and last pixel adddresses for readout order of APS images // The order is important because in AEFrameChipRenderer the frame buffer is cleared at the first // pixel and copied to output after the last pixel, so the pixels must be written in correct order // to the packet... // Also, y is flipped for the rpg-dvs driver which is based on libcaer where the frame starts at // upper left corner as in most computer vision, // unlike jaer that starts like in cartesian coordinates at lower left. for (int f = 0; f < 2; f++) { // reset/signal pixels samples // now we start at for (int y = firstPixel.y; (yinc > 0 ? y <= lastPixel.y : y >= lastPixel.y); y += yinc) { for (int x = firstPixel.x; (xinc > 0 ? x <= lastPixel.x : x >= lastPixel.x); x += xinc) { // above x and y are in jAER image space final int yrpg = sizey1 - y; // flips y to get to rpg from jaer coordinates (jaer uses 0,0 as lower left, rpg-dvs uses 0,0 as upper left) final int idx = yrpg * sizex + x; e.setReadoutType(f == 0 ? ApsDvsEvent.ReadoutType.ResetRead : ApsDvsEvent.ReadoutType.SignalRead); e.x = (short) x; e.y = (short) y; e.setAdcSample(f == 0 ? 255 : (255 - (0xff & bytes[idx]))); if (davisCamera == null) { e.setTimestamp(ts); } else { if (davisCamera.lastFrameAddress((short) x, (short) y)) { e.setTimestamp(ts + lastExposureUs); // set timestamp of last event written out to the frame end timestamp, TODO complete hack to have 1 pixel with larger timestamp } else { e.setTimestamp(ts); } } maybePushEvent(e, apsFifo, outItr); // debug // if(x==firstPixel.x && y==firstPixel.y){ // log.info("pushed first frame pixel event "+e); // }else if(x==lastPixel.x && y==lastPixel.y){ // log.info("pushed last frame pixel event "+e); } } } // end of exposure event // e = outItr.nextOutput(); e.setReadoutType(ApsDvsEvent.ReadoutType.EOE); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts + lastExposureUs); // TODO should really be end of exposure timestamp, have to get that from last exposure message maybePushEvent(e, apsFifo, outItr); // end of frame event // e = outItr.nextOutput(); e.setReadoutType(ApsDvsEvent.ReadoutType.EOF); e.x = (short) 0; e.y = (short) 0; e.setTimestamp(ts + lastExposureUs); maybePushEvent(e, apsFifo, outItr); } break; case "Imu": { hasImu.setTrue(); MessageType messageType = message.messageType; // List<String> fieldNames = messageType.getFieldNames(); // for(String s:fieldNames){ // System.out.println("fieldName: "+s); // List<String> fieldNames = messageType.getFieldNames(); MessageType header = messageType.getField("header"); Timestamp timestamp = header.<TimeType>getField("stamp").getValue(); int ts = getTimestampUsRelative(timestamp, false); // do update largest timestamp with IMU time MessageType angular_velocity = messageType.getField("angular_velocity"); // List<String> angvelfields=angular_velocity.getFieldNames(); // for(String s:angvelfields){ // System.out.println("angular_velocity field: "+s); float xrot = (float) (angular_velocity.<Float64Type>getField("x").getValue().doubleValue()); float yrot = (float) (angular_velocity.<Float64Type>getField("y").getValue().doubleValue()); float zrot = (float) (angular_velocity.<Float64Type>getField("z").getValue().doubleValue()); MessageType linear_acceleration = messageType.getField("linear_acceleration"); // List<String> linaccfields=linear_acceleration.getFieldNames(); // for(String s:linaccfields){ // System.out.println("linaccfields field: "+s); float xacc = (float) (angular_velocity.<Float64Type>getField("x").getValue().doubleValue()); float yacc = (float) (angular_velocity.<Float64Type>getField("y").getValue().doubleValue()); float zacc = (float) (angular_velocity.<Float64Type>getField("z").getValue().doubleValue()); short[] buf = new short[7]; buf[IMUSampleType.ax.code] = (short) (G_PER_MPS2 * xacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); // TODO set these scales from caer parameter messages in stream buf[IMUSampleType.ay.code] = (short) (G_PER_MPS2 * yacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); buf[IMUSampleType.az.code] = (short) (G_PER_MPS2 * zacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); buf[IMUSampleType.gx.code] = (short) (DEG_PER_RAD * xrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb()); buf[IMUSampleType.gy.code] = (short) (DEG_PER_RAD * yrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb()); buf[IMUSampleType.gz.code] = (short) (DEG_PER_RAD * zrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb()); // ApsDvsEvent e = null; // e = outItr.nextOutput(); IMUSample imuSample = new IMUSample(ts, buf); e.setImuSample(imuSample); e.setTimestamp(ts); maybePushEvent(e, imuFifo, outItr); } break; } break; case "dvs_msgs": hasDvs.setTrue(); switch (type) { case "EventArray": MessageType messageType = message.messageType; ArrayType data = messageType.<ArrayType>getField("events"); if (data == null) { log.warning("got null data for field events in message " + message); continue; } List<Field> eventFields = data.getFields(); gotEventsOrFrame = true; int sizeY = chip.getSizeY(); int eventIdxThisPacket = 0; // int nEvents = eventFields.size(); for (Field eventField : eventFields) { MessageType eventMsg = (MessageType) eventField; int x = eventMsg.<UInt16Type>getField("x").getValue(); int y = eventMsg.<UInt16Type>getField("y").getValue(); boolean pol = eventMsg.<BoolType>getField("polarity").getValue(); // false==off, true=on Timestamp timestamp = (Timestamp) eventMsg.<TimeType>getField("ts").getValue(); int ts = getTimestampUsRelative(timestamp, true); // sets nonMonotonicTimestampDetected flag, faster than throwing exception, updates largest timestamp // ApsDvsEvent e = outItr.nextOutput(); e.setReadoutType(ApsDvsEvent.ReadoutType.DVS); e.timestamp = ts; e.x = (short) x; e.y = (short) (sizeY - y - 1); e.polarity = pol ? PolarityEvent.Polarity.Off : PolarityEvent.Polarity.On; e.type = (byte) (pol ? 0 : 1); maybePushEvent(e, dvsFifo, outItr); eventIdxThisPacket++; } } break; } } } catch (UninitializedFieldException ex) { Logger.getLogger(ExampleRosBagReader.class.getName()).log(Level.SEVERE, null, ex); throw new BagReaderException(ex); } // if we were not checking time order, then events were directly copied to output packet oe already if (nonMonotonicTimestampExceptionsChecked) { // now pop events in time order from the FIFOs to the output packet and then reconstruct the raw packet ApsDvsEvent ev; while ((ev = popOldestEvent()) != null) { ApsDvsEvent oe = outItr.nextOutput(); oe.copyFrom(ev); } } AEPacketRaw aePacketRawCollecting = chip.getEventExtractor().reconstructRawPacket(eventPacket); fireInitPropertyChange(); return aePacketRawCollecting; } /** * Either pushes event to fifo or just directly writes it to output packet, * depending on flag nonMonotonicTimestampExceptionsChecked. * * @param ev the event * @param fifo the fifo to write to * @param outItr the output packet iterator, if events are directly written * to output */ private void maybePushEvent(ApsDvsEvent ev, AEFifo fifo, OutputEventIterator<ApsDvsEvent> outItr) { if (nonMonotonicTimestampExceptionsChecked) { fifo.pushEvent(ev); } else { ApsDvsEvent oe = outItr.nextOutput(); oe.copyFrom(ev); } } /** * returns the oldest event (earliest in time) from all of the fifos if * there are younger events in all other fifos * * @return oldest valid event (and first one pushed to any one particular * sub-fifo for identical timestamps) or null if there is none */ private ApsDvsEvent popOldestEvent() { // find oldest event over all fifos ApsDvsEvent ev = null; int ts = Integer.MAX_VALUE; int fifoIdx = -1; int numStreamsWithData = 0; for (int i = 0; i < 3; i++) { boolean hasData = hasDvsApsImu[i].isTrue(); if (hasData) { numStreamsWithData++; } int t; if (hasData && !aeFifos[i].isEmpty() && (t = aeFifos[i].peekNextTimestamp()) <= /* check <= */ ts) { fifoIdx = i; ts = t; } } if (fifoIdx < 0) { return null; // no fifo has event } // if only one stream has data then just return it if (numStreamsWithData == 1) { ev = aeFifos[fifoIdx].popEvent(); } else {// if any of the other fifos for which we actually have sensor data don't have younger event then return null for (int i = 0; i < 3; i++) { if (i == fifoIdx) { // don't compare with ourselves continue; } if (hasDvsApsImu[i].isTrue() && (!aeFifos[i].isEmpty()) // if other stream ever has had data but none is available now && aeFifos[i].getLastTimestamp() <= ts // or if last event in other stream data is still older than we are ) { return null; } } ev = aeFifos[fifoIdx].popEvent(); } return ev; } /** * Called to signal first read from file. Fires PropertyChange * AEInputStream.EVENT_INIT, with new value this. */ protected void fireInitPropertyChange() { if (firstReadCompleted) { return; } getSupport().firePropertyChange(AEInputStream.EVENT_INIT, null, this); firstReadCompleted = true; } @Override synchronized public AEPacketRaw readPacketByNumber(int numEventsToRead) throws IOException { int oldPosition = nextMessageNumber; if (numEventsToRead < 0) { return emptyPacket; } aePacketRawOutput.setNumEvents(0); while (aePacketRawBuffered.getNumEvents() < numEventsToRead && aePacketRawBuffered.getNumEvents() < AEPacketRaw.MAX_PACKET_SIZE_EVENTS) { try { aePacketRawBuffered.append(getNextRawPacket()); } catch (EOFException ex) { rewind(); return readPacketByNumber(numEventsToRead); } catch (BagReaderException ex) { throw new IOException(ex); } } AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, numEventsToRead); // copy over collected events // now use tmp packet to copy rest of buffered to, and then make that the new buffered aePacketRawTmp.setNumEvents(0); AEPacketRaw.copy(aePacketRawBuffered, numEventsToRead, aePacketRawTmp, 0, aePacketRawBuffered.getNumEvents() - numEventsToRead); AEPacketRaw tmp = aePacketRawBuffered; aePacketRawBuffered = aePacketRawTmp; aePacketRawTmp = tmp; getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, position()); if (aePacketRawOutput.getNumEvents() > 0) { currentStartTimestamp = aePacketRawOutput.getLastTimestamp(); } maybeSendRewoundEvent(oldPosition); return aePacketRawOutput; } @Override synchronized public AEPacketRaw readPacketByTime(int dt) throws IOException { int oldPosition = nextMessageNumber; if (dt < 0) { return emptyPacket; } int newEndTime = currentStartTimestamp + dt; // TODO problem is that time advances even when the data time might not. while (aePacketRawBuffered.isEmpty() || (aePacketRawBuffered.getLastTimestamp() < newEndTime && aePacketRawBuffered.getNumEvents() < MAX_RAW_EVENTS_BUFFER_SIZE)) { try { aePacketRawBuffered.append(getNextRawPacket()); // reaching EOF here will throw EOFException } catch (EOFException ex) { clearAccumulatedEvents(); rewind(); return readPacketByTime(dt); } catch (BagReaderException ex) { if (ex.getCause() instanceof ClosedByInterruptException) { // ignore, caussed by interrupting ViewLoop to change rendering mode return emptyPacket; } throw new IOException(ex); } } int[] ts = aePacketRawBuffered.getTimestamps(); int idx = aePacketRawBuffered.getNumEvents() - 1; while (idx > 0 && ts[idx] > newEndTime) { idx } aePacketRawOutput.clear(); //public static void copy(AEPacketRaw src, int srcPos, AEPacketRaw dest, int destPos, int length) { AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, idx); // copy over collected events // now use tmp packet to copy rest of buffered to, and then make that the new buffered aePacketRawTmp.setNumEvents(0); AEPacketRaw.copy(aePacketRawBuffered, idx, aePacketRawTmp, 0, aePacketRawBuffered.getNumEvents() - idx); AEPacketRaw tmp = aePacketRawBuffered; aePacketRawBuffered = aePacketRawTmp; aePacketRawTmp = tmp; if (aePacketRawOutput.isEmpty()) { currentStartTimestamp = newEndTime; } else { currentStartTimestamp = aePacketRawOutput.getLastTimestamp(); } getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, nextMessageNumber); maybeSendRewoundEvent(oldPosition); return aePacketRawOutput; } @Override public boolean isNonMonotonicTimeExceptionsChecked() { return nonMonotonicTimestampExceptionsChecked; } /** * If this option is set, then non-monotonic timestamps are replaced with * the newest timestamp in the file, ensuring monotonicity. It seems that * the frames and IMU samples are captured or timestamped out of order in * the file, resulting in DVS packets that contain timestamps younger than * earlier frames or IMU samples. * * @param yes to guarantee monotonicity */ @Override public void setNonMonotonicTimeExceptionsChecked(boolean yes) { nonMonotonicTimestampExceptionsChecked = yes; } /** * Returns starting time of file since epoch, in UTC time * * @return the time in ms since epoch (1970) */ @Override public long getAbsoluteStartingTimeMs() { return bagFile.getStartTime().getTime(); } @Override public ZoneId getZoneId() { return zoneId; // TODO implement setting time zone from file } @Override public int getDurationUs() { return (int) (bagFile.getDurationS() * 1e6); } @Override public int getFirstTimestamp() { return (int) firstTimestamp; } @Override public PropertyChangeSupport getSupport() { return support; } @Override public float getFractionalPosition() { return (float) mostRecentTimestamp / getDurationUs(); } @Override public long position() { return nextMessageNumber; } @Override public void position(long n) { if (n < 0) { n = 0; } else if (n >= numMessages) { n = numMessages - 1; } nextMessageNumber = (int) n; } @Override synchronized public void rewind() throws IOException { position(isMarkInSet() ? getMarkInPosition() : 0); clearAccumulatedEvents(); largestTimestampReadSinceRewind=0; // timestamps start at 0 by constuction of timestamps try { MessageWithIndex msg = getNextMsg(); if (msg != null) { currentStartTimestamp = getTimestampUsRelative(msg.messageIndex.timestamp, true); // reind, so update the largest timestamp read in this cycle to first timestamp position(isMarkInSet() ? getMarkInPosition() : 0); } } catch (BagReaderException e) { log.warning(String.format("Exception %s getting timestamp after rewind from ROS message", e.toString())); } clearAccumulatedEvents(); rewindFlag = true; } private void maybeSendRewoundEvent(long oldPosition) { if (rewindFlag) { getSupport().firePropertyChange(AEInputStream.EVENT_REWOUND, oldPosition, position()); rewindFlag = false; } } private void clearAccumulatedEvents() { aePacketRawBuffered.clear(); for (AEFifo f : aeFifos) { f.clear(); } } @Override synchronized public void setFractionalPosition(float frac) { position((int) (frac * numMessages)); // must also clear partially accumulated events in collecting packet and reset the timestamp clearAccumulatedEvents(); try { AEPacketRaw raw = getNextRawPacket(); while (raw == null) { log.warning(String.format("got null packet at fractional position %.2f which should have been message number %d, trying next packet", frac, nextMessageNumber)); raw = getNextRawPacket(); } aePacketRawBuffered.append(raw); // reaching EOF here will throw EOFException } catch (EOFException ex) { try { aePacketRawBuffered.clear(); rewind(); } catch (IOException ex1) { Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex1); } } catch (BagReaderException ex) { Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex); } } @Override public long size() { return 0; } @Override public void clearMarks() { markIn = -1; markOut = -1; getSupport().firePropertyChange(AEInputStream.EVENT_MARKS_CLEARED, null, null); } @Override public long setMarkIn() { int old = markIn; markIn = nextMessageNumber; getSupport().firePropertyChange(AEInputStream.EVENT_MARK_IN_SET, old, markIn); return markIn; } @Override public long setMarkOut() { int old = markOut; markOut = nextMessageNumber; getSupport().firePropertyChange(AEInputStream.EVENT_MARK_OUT_SET, old, markOut); return markOut; } @Override public long getMarkInPosition() { return markIn; } @Override public long getMarkOutPosition() { return markOut; } @Override public boolean isMarkInSet() { return markIn > 0; } @Override public boolean isMarkOutSet() { return markOut <= numMessages; } @Override public void setRepeat(boolean repeat) { this.repeatEnabled = repeat; } @Override public boolean isRepeat() { return repeatEnabled; } /** * Returns the File that is being read, or null if the instance is * constructed from a FileInputStream */ public File getFile() { return file; } /** * Sets the File reference but doesn't open the file */ public void setFile(File f) { this.file = f; } @Override public int getLastTimestamp() { return (int) lastTimestamp; // TODO, from last DVS event timestamp } @Override public int getMostRecentTimestamp() { return (int) mostRecentTimestamp; } @Override public int getTimestampResetBitmask() { return 0; // TODO } @Override public void setTimestampResetBitmask(int timestampResetBitmask) { // TODO } @Override synchronized public void close() throws IOException { if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException e) { // ignore this error } } bagFile = null; file = null; System.gc(); } @Override public int getCurrentStartTimestamp() { return (int) lastTimestamp; } @Override synchronized public void setCurrentStartTimestamp(int currentStartTimestamp) { this.currentStartTimestamp = currentStartTimestamp; nextMessageNumber = (int) (numMessages * (float) currentStartTimestamp / getDurationUs()); aePacketRawBuffered.clear(); } @Override protected void finalize() throws Throwable { super.finalize(); close(); } private void generateMessageIndexes(ProgressMonitor progressMonitor) throws BagReaderException, InterruptedException { if (wasIndexed) { return; } log.info("creating or loading cached index for all topics"); if (!maybeLoadCachedMsgIndexes(progressMonitor)) { msgIndexes = bagFile.generateIndexesForTopicList(topicList, progressMonitor); cacheMsgIndexes(); } numMessages = msgIndexes.size(); markIn = 0; markOut = numMessages; firstTimestamp = getTimestampUsRelative(msgIndexes.get(0).timestamp, true); lastTimestamp = getTimestampUsRelative(msgIndexes.get(numMessages - 1).timestamp, false); // don't update largest timestamp with last timestamp wasIndexed = true; } public void addPropertyChangeListener(PropertyChangeListener listener) { this.support.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { this.support.removePropertyChangeListener(listener); } /** * Adds a topic for which listeners should be informed. The PropertyChange * has this as the source and the new value is the MessageType message. * * @param topics a string topic, e.g. "/dvs/events" * @param listener a PropertyChangeListener that gets the messages * @throws java.lang.InterruptedException since generating the topic index * is a long-running process, the method throws * @throws com.github.swrirobotics.bags.reader.exceptions.BagReaderException * if there is an exception for the BagFile * @see MessageType */ @Override synchronized public void addSubscribers(List<String> topics, PropertyChangeListener listener, ProgressMonitor progressMonitor) throws InterruptedException, BagReaderException { List<String> topicsToAdd = new ArrayList(); for (String topic : topics) { if (msgListeners.containsKey(topic) && msgListeners.get(topic).contains(listener)) { log.warning("topic " + topic + " and listener " + listener + " already added, ignoring"); continue; } topicsToAdd.add(topic); } if (topicsToAdd.isEmpty()) { log.warning("nothing to add"); return; } addPropertyChangeListener(listener); List<BagFile.MessageIndex> idx = bagFile.generateIndexesForTopicList(topicsToAdd, progressMonitor); msgIndexes.addAll(idx); for (String topic : topics) { msgListeners.put(topic, listener); } Collections.sort(msgIndexes); } /** * Removes a topic * * @param topic * @param listener */ @Override public void removeTopic(String topic, PropertyChangeListener listener) { log.warning("cannot remove topic parsing, just removing listener"); if (msgListeners.containsValue(listener)) { log.info("removing listener " + listener); removePropertyChangeListener(listener); } } /** * Set if nonmonotonic timestamp was detected. Cleared at start of * collecting each new packet. * * @return the nonMonotonicTimestampDetected true if a nonmonotonic * timestamp was detected. */ public boolean isNonMonotonicTimestampDetected() { return nonMonotonicTimestampDetected; } synchronized private void cacheMsgIndexes() { try { File file = new File(messageIndexesCacheFileName()); if (file.exists() && file.canRead() && file.isFile()) { log.info("cached indexes " + file + " for file " + getFile() + " already exists, not storing it again"); return; } log.info("caching the index for rosbag file " + getFile() + " in " + file); FileOutputStream out = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(msgIndexes); oos.flush(); log.info("cached the index for rosbag file " + getFile() + " in " + file); } catch (Exception e) { log.warning("could not cache the message index to disk: " + e.toString()); } } synchronized private boolean maybeLoadCachedMsgIndexes(ProgressMonitor progressMonitor) { try { File file = new File(messageIndexesCacheFileName()); if (!file.exists() || !file.canRead() || !file.isFile()) { log.info("cached indexes " + file + " for file " + getFile() + " does not exist"); return false; } log.info("reading cached index for rosbag file " + getFile() + " from " + file); long startTime = System.currentTimeMillis(); if (progressMonitor != null) { if (progressMonitor.isCanceled()) { progressMonitor.setNote("canceling"); throw new InterruptedException("canceled loading caches"); } progressMonitor.setNote("reading cached index from " + file); } FileInputStream in = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(in)); List<BagFile.MessageIndex> tmpIdx = (List<BagFile.MessageIndex>) ois.readObject(); msgIndexes = tmpIdx; long ms = System.currentTimeMillis() - startTime; log.info("done after " + ms + "ms with reading cached index for rosbag file " + getFile() + " from " + file); if (progressMonitor != null) { if (progressMonitor.isCanceled()) { progressMonitor.setNote("canceling"); throw new InterruptedException("canceled loading caches"); } progressMonitor.setNote("done reading cached index"); progressMonitor.setProgress(progressMonitor.getMaximum()); } return true; } catch (Exception e) { log.warning("could load cached message index from disk: " + e.toString()); return false; } } private String messageIndexesCacheFileName() { return System.getProperty("java.io.tmpdir") + File.separator + getFile().getName() + ".rosbagidx"; } /** * A FIFO for ApsDvsEvent events. */ private final class AEFifo extends ApsDvsEventPacket { private final int MAX_EVENTS = 1 << 20; int nextToPopIndex = 0; private boolean full = false; public AEFifo() { super(ApsDvsEvent.class); } /** * Adds a new event to end * * @param event */ public final void pushEvent(ApsDvsEvent event) { if (full) { return; } if (size == MAX_EVENTS) { full = true; log.warning(String.format("FIFO has reached capacity RosbagFileInputStream.MAX_EVENTS=%,d events: %s", MAX_EVENTS, toString())); return; } appendCopy(event); } @Override public boolean isEmpty() { return size == 0 || nextToPopIndex >= size; //To change body of generated methods, choose Tools | Templates. } @Override public void clear() { super.clear(); nextToPopIndex = 0; full = false; } /** * @return next event, or null if there are no more */ public final ApsDvsEvent popEvent() { if (isEmpty()) { clear(); return null; } ApsDvsEvent event = (ApsDvsEvent) getEvent(nextToPopIndex++); if (isEmpty()) { clear(); } return event; } public final int peekNextTimestamp() { return getEvent(nextToPopIndex).timestamp; } @Override final public String toString() { return "AEFifo with capacity " + MAX_EVENTS + " nextToPopIndex=" + nextToPopIndex + " holding " + super.toString(); } } }
package nu.validator.checker; import com.cybozu.labs.langdetect.Detector; import com.cybozu.labs.langdetect.DetectorFactory; import com.cybozu.labs.langdetect.LangDetectException; import com.cybozu.labs.langdetect.Language; import com.ibm.icu.util.ULocale; import io.mola.galimatias.GalimatiasParseException; import io.mola.galimatias.Host; import io.mola.galimatias.URL; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import nu.validator.checker.Checker; import nu.validator.checker.LocatorImpl; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class LanguageDetectingChecker extends Checker { private static final String languageList = "nu/validator/localentities/files/language-profiles-list.txt"; private static final String profilesDir = "nu/validator/localentities/files/language-profiles/"; private static final Map<String, String[]> LANG_TAGS_BY_TLD = new HashMap<>(); private String systemId; private String tld; private Locator htmlStartTagLocator; private StringBuilder elementContent; private StringBuilder documentContent; private String httpContentLangHeader; private String htmlElementLangAttrValue; private String declaredLangCode; private boolean htmlElementHasLang; private String dirAttrValue; private boolean hasDir; private boolean inBody; private int currentOpenElementsInDifferentLang; private int currentOpenElementsWithSkipName = 0; private int nonWhitespaceCharacterCount; private static final int MAX_CHARS = 30720; private static final int MIN_CHARS = 1024; private static final double MIN_PROBABILITY = .90; private static final String[] RTL_LANGS = { "ar", "azb", "ckb", "dv", "fa", "he", "pnb", "ps", "sd", "ug", "ur" }; private static final String[] SKIP_NAMES = { "a", "figcaption", "form", "li", "nav", "pre", "script", "select", "style", "td", "textarea" }; static { LANG_TAGS_BY_TLD.put("ae", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("af", new String[] { "ps" }); LANG_TAGS_BY_TLD.put("am", new String[] { "hy" }); LANG_TAGS_BY_TLD.put("ar", new String[] { "es" }); LANG_TAGS_BY_TLD.put("at", new String[] { "de" }); LANG_TAGS_BY_TLD.put("az", new String[] { "az" }); LANG_TAGS_BY_TLD.put("ba", new String[] { "bs", "hr", "sr" }); LANG_TAGS_BY_TLD.put("bd", new String[] { "bn" }); LANG_TAGS_BY_TLD.put("be", new String[] { "de", "fr", "nl" }); LANG_TAGS_BY_TLD.put("bg", new String[] { "bg" }); LANG_TAGS_BY_TLD.put("bh", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("bo", new String[] { "es" }); LANG_TAGS_BY_TLD.put("br", new String[] { "pt" }); LANG_TAGS_BY_TLD.put("by", new String[] { "be" }); LANG_TAGS_BY_TLD.put("bz", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ch", new String[] { "de", "fr", "it", "rm" }); LANG_TAGS_BY_TLD.put("cl", new String[] { "es" }); LANG_TAGS_BY_TLD.put("co", new String[] { "es" }); LANG_TAGS_BY_TLD.put("cu", new String[] { "es" }); LANG_TAGS_BY_TLD.put("cr", new String[] { "es" }); LANG_TAGS_BY_TLD.put("cz", new String[] { "cs" }); LANG_TAGS_BY_TLD.put("de", new String[] { "de" }); LANG_TAGS_BY_TLD.put("dk", new String[] { "da" }); LANG_TAGS_BY_TLD.put("do", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ec", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ee", new String[] { "et" }); LANG_TAGS_BY_TLD.put("eg", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("es", new String[] { "es" }); LANG_TAGS_BY_TLD.put("fi", new String[] { "fi" }); LANG_TAGS_BY_TLD.put("fr", new String[] { "fr" }); LANG_TAGS_BY_TLD.put("ge", new String[] { "ka" }); LANG_TAGS_BY_TLD.put("gr", new String[] { "el" }); LANG_TAGS_BY_TLD.put("gt", new String[] { "es" }); LANG_TAGS_BY_TLD.put("hn", new String[] { "es" }); LANG_TAGS_BY_TLD.put("hr", new String[] { "hr" }); LANG_TAGS_BY_TLD.put("hu", new String[] { "hu" }); LANG_TAGS_BY_TLD.put("id", new String[] { "id" }); LANG_TAGS_BY_TLD.put("is", new String[] { "is" }); LANG_TAGS_BY_TLD.put("it", new String[] { "it" }); LANG_TAGS_BY_TLD.put("il", new String[] { "iw" }); LANG_TAGS_BY_TLD.put("in", new String[] { "bn", "gu", "hi", "kn", "ml", "mr", "pa", "ta", "te" }); LANG_TAGS_BY_TLD.put("ja", new String[] { "jp" }); LANG_TAGS_BY_TLD.put("jo", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("ke", new String[] { "sw" }); LANG_TAGS_BY_TLD.put("kg", new String[] { "ky" }); LANG_TAGS_BY_TLD.put("kh", new String[] { "km" }); LANG_TAGS_BY_TLD.put("kr", new String[] { "ko" }); LANG_TAGS_BY_TLD.put("kw", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("kz", new String[] { "kk" }); LANG_TAGS_BY_TLD.put("la", new String[] { "lo" }); LANG_TAGS_BY_TLD.put("li", new String[] { "de" }); LANG_TAGS_BY_TLD.put("lb", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("lk", new String[] { "si", "ta" }); LANG_TAGS_BY_TLD.put("lt", new String[] { "lt" }); LANG_TAGS_BY_TLD.put("lu", new String[] { "de" }); LANG_TAGS_BY_TLD.put("lv", new String[] { "lv" }); LANG_TAGS_BY_TLD.put("md", new String[] { "mo" }); LANG_TAGS_BY_TLD.put("mk", new String[] { "mk" }); LANG_TAGS_BY_TLD.put("mn", new String[] { "mn" }); LANG_TAGS_BY_TLD.put("mx", new String[] { "es" }); LANG_TAGS_BY_TLD.put("my", new String[] { "ms" }); LANG_TAGS_BY_TLD.put("ni", new String[] { "es" }); LANG_TAGS_BY_TLD.put("nl", new String[] { "nl" }); LANG_TAGS_BY_TLD.put("no", new String[] { "nn", "no" }); LANG_TAGS_BY_TLD.put("np", new String[] { "ne" }); LANG_TAGS_BY_TLD.put("pa", new String[] { "es" }); LANG_TAGS_BY_TLD.put("pe", new String[] { "es" }); LANG_TAGS_BY_TLD.put("ph", new String[] { "tl" }); LANG_TAGS_BY_TLD.put("pl", new String[] { "pl" }); LANG_TAGS_BY_TLD.put("pk", new String[] { "ur" }); LANG_TAGS_BY_TLD.put("pr", new String[] { "es" }); LANG_TAGS_BY_TLD.put("pt", new String[] { "pt" }); LANG_TAGS_BY_TLD.put("py", new String[] { "es" }); LANG_TAGS_BY_TLD.put("qa", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("ro", new String[] { "ro" }); LANG_TAGS_BY_TLD.put("rs", new String[] { "sr" }); LANG_TAGS_BY_TLD.put("ru", new String[] { "ru" }); LANG_TAGS_BY_TLD.put("sa", new String[] { "ar" }); LANG_TAGS_BY_TLD.put("se", new String[] { "sv" }); LANG_TAGS_BY_TLD.put("si", new String[] { "sl" }); LANG_TAGS_BY_TLD.put("sk", new String[] { "sk" }); LANG_TAGS_BY_TLD.put("sv", new String[] { "es" }); LANG_TAGS_BY_TLD.put("th", new String[] { "th" }); LANG_TAGS_BY_TLD.put("tj", new String[] { "tg" }); LANG_TAGS_BY_TLD.put("tm", new String[] { "tk" }); LANG_TAGS_BY_TLD.put("ua", new String[] { "uk" }); LANG_TAGS_BY_TLD.put("uy", new String[] { "es" }); LANG_TAGS_BY_TLD.put("uz", new String[] { "uz" }); LANG_TAGS_BY_TLD.put("ve", new String[] { "es" }); LANG_TAGS_BY_TLD.put("vn", new String[] { "vi" }); LANG_TAGS_BY_TLD.put("za", new String[] { "af" }); try { BufferedReader br = new BufferedReader(new InputStreamReader( LanguageDetectingChecker.class.getClassLoader().getResourceAsStream( languageList), "UTF-8")); List<String> languageTags = new ArrayList<>(); String languageTagAndName = br.readLine(); while (languageTagAndName != null) { languageTags.add(languageTagAndName.split("\t")[0]); languageTagAndName = br.readLine(); } List<String> profiles = new ArrayList<>(); for (String languageTag : languageTags) { profiles.add((new BufferedReader(new InputStreamReader( LanguageDetectingChecker.class.getClassLoader().getResourceAsStream( profilesDir + languageTag), "UTF-8"))).readLine()); } DetectorFactory.clear(); DetectorFactory.loadProfile(profiles); } catch (IOException e) { throw new RuntimeException(e); } catch (LangDetectException e) { } } private boolean shouldAppendToLangdetectContent() { return (inBody && currentOpenElementsWithSkipName < 1 && currentOpenElementsInDifferentLang < 1 && nonWhitespaceCharacterCount < MAX_CHARS); } private void setDocumentLanguage(String languageTag) { if (request != null) { request.setAttribute( "http://validator.nu/properties/document-language", languageTag); } } private String getDetectedLanguageSerboCroatian() throws SAXException { if ("hr".equals(declaredLangCode) || "hr".equals(tld)) { return "hr"; } if ("sr".equals(declaredLangCode) || ".rs".equals(tld)) { return "sr-latn"; } if ("bs".equals(declaredLangCode) || ".ba".equals(tld)) { return "bs"; } return "sh"; } private void checkLangAttributeSerboCroatian() throws SAXException { String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); String langWarning = ""; if (!htmlElementHasLang) { langWarning = "This document appears to be written in either" + " Croatian, Serbian, or Bosnian. Consider adding either" + " \u201Clang=\"hr\"\u201D, \u201Clang=\"sr\"\u201D, or" + " \u201Clang=\"bs\"\u201D to the" + " \u201Chtml\u201D start tag."; } else if (!("hr".equals(declaredLangCode) || "sr".equals(declaredLangCode) || "bs".equals(declaredLangCode))) { langWarning = String.format( "This document appears to be written in either Croatian," + " Serbian, or Bosnian, but the \u201Chtml\u201D" + " start tag has %s. Consider using either" + " \u201Clang=\"hr\"\u201D," + " \u201Clang=\"sr\"\u201D, or" + " \u201Clang=\"bs\"\u201D instead.", getAttValueExpr("lang", lowerCaseLang)); } if (!"".equals(langWarning)) { warn(langWarning, htmlStartTagLocator); } } private void checkLangAttributeNorwegian() throws SAXException { String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); String langWarning = ""; if (!htmlElementHasLang) { langWarning = "This document appears to be written in Norwegian" + " Consider adding either" + " \u201Clang=\"nn\"\u201D or \u201Clang=\"nb\"\u201D" + " (or variant) to the \u201Chtml\u201D start tag."; } else if (!("no".equals(declaredLangCode) || "nn".equals(declaredLangCode) || "nb".equals(declaredLangCode))) { langWarning = String.format( "This document appears to be written in Norwegian, but the" + " \u201Chtml\u201D start tag has %s. Consider" + " using either \u201Clang=\"nn\"\u201D or" + " \u201Clang=\"nb\"\u201D (or variant) instead.", getAttValueExpr("lang", lowerCaseLang)); } if (!"".equals(langWarning)) { warn(langWarning, htmlStartTagLocator); } } private void checkContentLanguageHeaderNorwegian(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode) throws SAXException { if ("".equals(httpContentLangHeader) || httpContentLangHeader.contains(",")) { return; } String lowerCaseContentLang = httpContentLangHeader.toLowerCase(); String contentLangCode = new ULocale( lowerCaseContentLang).getLanguage(); if (!("no".equals(contentLangCode) || "nn".equals(contentLangCode) || "nb".equals(contentLangCode))) { warn("This document appears to be written in" + " Norwegian but the value of the HTTP" + " \u201CContent-Language\u201D header is" + " \u201C" + lowerCaseContentLang + "\u201D. Consider" + " changing it to \u201Cnn\u201D or \u201Cnn\u201D" + " (or variant) instead."); } } private void checkLangAttribute(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode, String preferredLanguageCode) throws SAXException { String langWarning = ""; String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); if (!htmlElementHasLang) { langWarning = String.format( "This document appears to be written in %s." + " Consider adding \u201Clang=\"%s\"\u201D" + " (or variant) to the \u201Chtml\u201D" + " start tag.", detectedLanguageName, preferredLanguageCode); } else { if (request != null) { if ("".equals(lowerCaseLang)) { request.setAttribute( "http://validator.nu/properties/lang-empty", true); } else { request.setAttribute( "http://validator.nu/properties/lang-value", lowerCaseLang); } } if ("tl".equals(detectedLanguageCode) && ("ceb".equals(declaredLangCode) || "ilo".equals(declaredLangCode) || "pag".equals(declaredLangCode) || "war".equals(declaredLangCode))) { return; } if ("id".equals(detectedLanguageCode) && "min".equals(declaredLangCode)) { return; } if ("ms".equals(detectedLanguageCode) && "min".equals(declaredLangCode)) { return; } if ("hr".equals(detectedLanguageCode) && ("sr".equals(declaredLangCode) || "bs".equals(declaredLangCode) || "sh".equals(declaredLangCode))) { return; } if ("sr".equals(detectedLanguageCode) && ("hr".equals(declaredLangCode) || "bs".equals(declaredLangCode) || "sh".equals(declaredLangCode))) { return; } if ("bs".equals(detectedLanguageCode) && ("hr".equals(declaredLangCode) || "sr".equals(declaredLangCode) || "sh".equals(declaredLangCode))) { return; } if ("de".equals(detectedLanguageCode) && ("bar".equals(declaredLangCode) || "gsw".equals(declaredLangCode) || "lb".equals(declaredLangCode))) { return; } if ("zh".equals(detectedLanguageCode) && "yue".equals(lowerCaseLang)) { return; } if ("el".equals(detectedLanguageCode) && "grc".equals(declaredLangCode)) { return; } if ("es".equals(detectedLanguageCode) && ("an".equals(declaredLangCode) || "ast".equals(declaredLangCode))) { return; } if ("it".equals(detectedLanguageCode) && ("co".equals(declaredLangCode) || "pms".equals(declaredLangCode) || "vec".equals(declaredLangCode) || "lmo".equals(declaredLangCode) || "scn".equals(declaredLangCode) || "nap".equals(declaredLangCode))) { return; } if ("rw".equals(detectedLanguageCode) && "rn".equals(declaredLangCode)) { return; } if ("mhr".equals(detectedLanguageCode) && ("chm".equals(declaredLangCode) || "mrj".equals(declaredLangCode))) { return; } if ("mrj".equals(detectedLanguageCode) && ("chm".equals(declaredLangCode) || "mhr".equals(declaredLangCode))) { return; } if ("ru".equals(detectedLanguageCode) && "bg".equals(declaredLangCode)) { return; } String message = "This document appears to be written in %s" + " but the \u201Chtml\u201D start tag has %s. Consider" + " using \u201Clang=\"%s\"\u201D (or variant) instead."; if (zhSubtagMismatch(detectedLanguage, lowerCaseLang) || !declaredLangCode.equals(detectedLanguageCode)) { if (request != null) { request.setAttribute( "http://validator.nu/properties/lang-wrong", true); } langWarning = String.format(message, detectedLanguageName, getAttValueExpr("lang", htmlElementLangAttrValue), preferredLanguageCode); } } if (!"".equals(langWarning)) { warn(langWarning, htmlStartTagLocator); } } private void checkContentLanguageHeader(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode, String preferredLanguageCode) throws SAXException { if ("".equals(httpContentLangHeader) || httpContentLangHeader.contains(",")) { return; } String message = ""; String lowerCaseContentLang = httpContentLangHeader.toLowerCase(); String contentLangCode = new ULocale( lowerCaseContentLang).getLanguage(); if ("tl".equals(detectedLanguageCode) && ("ceb".equals(contentLangCode) || "ilo".equals(contentLangCode) || "pag".equals(contentLangCode) || "war".equals(contentLangCode))) { return; } if ("id".equals(detectedLanguageCode) && "min".equals(contentLangCode)) { return; } if ("ms".equals(detectedLanguageCode) && "min".equals(contentLangCode)) { return; } if ("hr".equals(detectedLanguageCode) && ("sr".equals(contentLangCode) || "bs".equals(contentLangCode) || "sh".equals(contentLangCode))) { return; } if ("sr".equals(detectedLanguageCode) && ("hr".equals(contentLangCode) || "bs".equals(contentLangCode) || "sh".equals(contentLangCode))) { return; } if ("bs".equals(detectedLanguageCode) && ("hr".equals(contentLangCode) || "sr".equals(contentLangCode) || "sh".equals(contentLangCode))) { return; } if ("de".equals(detectedLanguageCode) && ("bar".equals(contentLangCode) || "gsw".equals(contentLangCode) || "lb".equals(contentLangCode))) { return; } if ("zh".equals(detectedLanguageCode) && "yue".equals(lowerCaseContentLang)) { return; } if ("el".equals(detectedLanguageCode) && "grc".equals(contentLangCode)) { return; } if ("es".equals(detectedLanguageCode) && ("an".equals(contentLangCode) || "ast".equals(contentLangCode))) { return; } if ("it".equals(detectedLanguageCode) && ("co".equals(contentLangCode) || "pms".equals(contentLangCode) || "vec".equals(contentLangCode) || "lmo".equals(contentLangCode) || "scn".equals(contentLangCode) || "nap".equals(contentLangCode))) { return; } if ("rw".equals(detectedLanguageCode) && "rn".equals(contentLangCode)) { return; } if ("mhr".equals(detectedLanguageCode) && ("chm".equals(contentLangCode) || "mrj".equals(contentLangCode))) { return; } if ("mrj".equals(detectedLanguageCode) && ("chm".equals(contentLangCode) || "mhr".equals(contentLangCode))) { return; } if ("ru".equals(detectedLanguageCode) && "bg".equals(contentLangCode)) { return; } if (zhSubtagMismatch(detectedLanguage, lowerCaseContentLang) || !contentLangCode.equals(detectedLanguageCode)) { message = "This document appears to be written in %s but the value" + " of the HTTP \u201CContent-Language\u201D header is" + " \u201C%s\u201D. Consider changing it to" + " \u201C%s\u201D (or variant)."; warn(String.format(message, detectedLanguageName, lowerCaseContentLang, preferredLanguageCode, preferredLanguageCode)); } if (htmlElementHasLang) { message = "The value of the HTTP \u201CContent-Language\u201D" + " header is \u201C%s\u201D but it will be ignored because" + " the \u201Chtml\u201D start tag has %s."; String lowerCaseLang = htmlElementLangAttrValue.toLowerCase(); if (htmlElementHasLang) { if (zhSubtagMismatch(lowerCaseContentLang, lowerCaseLang) || !contentLangCode.equals(declaredLangCode)) { warn(String.format(message, httpContentLangHeader, getAttValueExpr("lang", htmlElementLangAttrValue)), htmlStartTagLocator); } } } } private void checkDirAttribute(String detectedLanguage, String detectedLanguageName, String detectedLanguageCode, String preferredLanguageCode) throws SAXException { if (Arrays.binarySearch(RTL_LANGS, detectedLanguageCode) < 0) { return; } String dirWarning = ""; if (!hasDir) { dirWarning = String.format( "This document appears to be written in %s." + " Consider adding \u201Cdir=\"rtl\"\u201D" + " to the \u201Chtml\u201D start tag.", detectedLanguageName, preferredLanguageCode); } else if (!"rtl".equals(dirAttrValue)) { String message = "This document appears to be written in %s" + " but the \u201Chtml\u201D start tag has %s." + " Consider using \u201Cdir=\"rtl\"\u201D instead."; dirWarning = String.format(message, detectedLanguageName, getAttValueExpr("dir", dirAttrValue)); } if (!"".equals(dirWarning)) { warn(dirWarning, htmlStartTagLocator); } } private boolean zhSubtagMismatch(String expectedLanguage, String declaredLanguage) { return (("zh-hans".equals(expectedLanguage) && (declaredLanguage.contains("zh-tw") || declaredLanguage.contains("zh-hant"))) || ("zh-hant".equals(expectedLanguage) && (declaredLanguage.contains("zh-cn") || declaredLanguage.contains("zh-hans")))); } private String getAttValueExpr(String attName, String attValue) { if ("".equals(attValue)) { return String.format("an empty \u201c%s\u201d attribute", attName); } else { return String.format("\u201C%s=\"%s\"\u201D", attName, attValue); } } public LanguageDetectingChecker() { super(); } private HttpServletRequest request; public void setHttpContentLanguageHeader(String httpContentLangHeader) { if (httpContentLangHeader != null) { this.httpContentLangHeader = httpContentLangHeader; } } /** * @see nu.validator.checker.Checker#endDocument() */ @Override public void endDocument() throws SAXException { if (!"0".equals(System.getProperty( "nu.validator.checker.enableLangDetection")) && htmlStartTagLocator != null) { detectLanguageAndCheckAgainstDeclaredLanguage(); } } private void warnIfMissingLang() throws SAXException { if (!htmlElementHasLang) { String message = "Consider adding a \u201Clang\u201D" + " attribute to the \u201Chtml\u201D" + " start tag to declare the language" + " of this document."; warn(message, htmlStartTagLocator); } } private void detectLanguageAndCheckAgainstDeclaredLanguage() throws SAXException { if (nonWhitespaceCharacterCount < MIN_CHARS) { warnIfMissingLang(); return; } if ("zxx".equals(declaredLangCode) // "No Linguistic Content" || "eo".equals(declaredLangCode) // Esperanto || "la".equals(declaredLangCode) // Latin ) { return; } if (LANG_TAGS_BY_TLD.containsKey(tld) && Arrays.binarySearch(LANG_TAGS_BY_TLD.get(tld), declaredLangCode) >= 0) { return; } try { String textContent = documentContent.toString() .replaceAll("\\s+", " "); String detectedLanguage = ""; Detector detector = DetectorFactory.create(); detector.append(textContent); detector.getProbabilities(); ArrayList<String> possibileLanguages = new ArrayList<>(); ArrayList<Language> possibilities = detector.getProbabilities(); for (Language possibility : possibilities) { possibileLanguages.add(possibility.lang); if (possibility.prob > MIN_PROBABILITY) { detectedLanguage = possibility.lang; setDocumentLanguage(detectedLanguage); } else if ((possibileLanguages.contains("hr") && (possibileLanguages.contains("sr-latn") || possibileLanguages.contains("bs"))) || (possibileLanguages.contains("sr-latn") && (possibileLanguages.contains("hr") || possibileLanguages.contains("bs"))) || (possibileLanguages.contains("bs") && (possibileLanguages.contains("hr") || possibileLanguages.contains( "sr-latn")))) { if (htmlElementHasLang || systemId != null) { detectedLanguage = getDetectedLanguageSerboCroatian(); setDocumentLanguage(detectedLanguage); } if ("sh".equals(detectedLanguage)) { checkLangAttributeSerboCroatian(); return; } } } if ("".equals(detectedLanguage)) { warnIfMissingLang(); return; } String detectedLanguageName = ""; String preferredLanguageCode = ""; ULocale locale = new ULocale(detectedLanguage); String detectedLanguageCode = locale.getLanguage(); if ("no".equals(detectedLanguage)) { checkLangAttributeNorwegian(); checkContentLanguageHeaderNorwegian(detectedLanguage, detectedLanguageName, detectedLanguageCode); return; } if ("zh-hans".equals(detectedLanguage)) { detectedLanguageName = "Simplified Chinese"; preferredLanguageCode = "zh-hans"; } else if ("zh-hant".equals(detectedLanguage)) { detectedLanguageName = "Traditional Chinese"; preferredLanguageCode = "zh-hant"; } else if ("mhr".equals(detectedLanguage)) { detectedLanguageName = "Meadow Mari"; preferredLanguageCode = "mhr"; } else if ("mrj".equals(detectedLanguage)) { detectedLanguageName = "Hill Mari"; preferredLanguageCode = "mrj"; } else if ("nah".equals(detectedLanguage)) { detectedLanguageName = "Nahuatl"; preferredLanguageCode = "nah"; } else if ("pnb".equals(detectedLanguage)) { detectedLanguageName = "Western Panjabi"; preferredLanguageCode = "pnb"; } else if ("sr-cyrl".equals(detectedLanguage)) { detectedLanguageName = "Serbian"; preferredLanguageCode = "sr"; } else if ("sr-latn".equals(detectedLanguage)) { detectedLanguageName = "Serbian"; preferredLanguageCode = "sr"; } else if ("uz-cyrl".equals(detectedLanguage)) { detectedLanguageName = "Uzbek"; preferredLanguageCode = "uz"; } else if ("uz-latn".equals(detectedLanguage)) { detectedLanguageName = "Uzbek"; preferredLanguageCode = "uz"; } else if ("zxx".equals(detectedLanguage)) { detectedLanguageName = "Lorem ipsum text"; preferredLanguageCode = "zxx"; } else { detectedLanguageName = locale.getDisplayName(); preferredLanguageCode = detectedLanguageCode; } checkLangAttribute(detectedLanguage, detectedLanguageName, detectedLanguageCode, preferredLanguageCode); checkDirAttribute(detectedLanguage, detectedLanguageName, detectedLanguageCode, preferredLanguageCode); checkContentLanguageHeader(detectedLanguage, detectedLanguageName, detectedLanguageCode, preferredLanguageCode); } catch (LangDetectException e) { } } /** * @see nu.validator.checker.Checker#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String name) throws SAXException { if ("http: return; } if (nonWhitespaceCharacterCount < MAX_CHARS) { documentContent.append(elementContent); elementContent.setLength(0); } if ("body".equals(localName)) { inBody = false; currentOpenElementsWithSkipName = 0; } if (currentOpenElementsInDifferentLang > 0) { currentOpenElementsInDifferentLang if (currentOpenElementsInDifferentLang < 0) { currentOpenElementsInDifferentLang = 0; } } else { if (Arrays.binarySearch(SKIP_NAMES, localName) >= 0) { currentOpenElementsWithSkipName if (currentOpenElementsWithSkipName < 0) { currentOpenElementsWithSkipName = 0; } } } } /** * @see nu.validator.checker.Checker#startDocument() */ @Override public void startDocument() throws SAXException { request = getRequest(); httpContentLangHeader = ""; tld = ""; htmlStartTagLocator = null; inBody = false; currentOpenElementsInDifferentLang = 0; currentOpenElementsWithSkipName = 0; nonWhitespaceCharacterCount = 0; elementContent = new StringBuilder(); documentContent = new StringBuilder(); htmlElementHasLang = false; htmlElementLangAttrValue = ""; declaredLangCode = ""; hasDir = false; dirAttrValue = ""; documentContent.setLength(0); currentOpenElementsWithSkipName = 0; try { systemId = getDocumentLocator().getSystemId(); if (systemId != null && systemId.startsWith("http")) { Host hostname = URL.parse(systemId).host(); if (hostname != null) { String host = hostname.toString(); tld = host.substring(host.lastIndexOf(".") + 1); } } } catch (GalimatiasParseException e) { throw new RuntimeException(e); } } /** * @see nu.validator.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if ("http: return; } if ("html".equals(localName)) { htmlStartTagLocator = new LocatorImpl(getDocumentLocator()); for (int i = 0; i < atts.getLength(); i++) { if ("lang".equals(atts.getLocalName(i))) { if (request != null) { request.setAttribute( "http://validator.nu/properties/lang-found", true); } htmlElementHasLang = true; htmlElementLangAttrValue = atts.getValue(i); declaredLangCode = new ULocale( htmlElementLangAttrValue).getLanguage(); } else if ("dir".equals(atts.getLocalName(i))) { hasDir = true; dirAttrValue = atts.getValue(i); } } } else if ("body".equals(localName)) { inBody = true; } else if (inBody) { if (currentOpenElementsInDifferentLang > 0) { currentOpenElementsInDifferentLang++; } else { for (int i = 0; i < atts.getLength(); i++) { if ("lang".equals(atts.getLocalName(i))) { if (!"".equals(htmlElementLangAttrValue) && !htmlElementLangAttrValue.equals( atts.getValue(i))) { currentOpenElementsInDifferentLang++; } } } } } if (Arrays.binarySearch(SKIP_NAMES, localName) >= 0) { currentOpenElementsWithSkipName++; } } /** * @see nu.validator.checker.Checker#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (shouldAppendToLangdetectContent()) { elementContent.append(ch, start, length); } for (int i = start; i < start + length; i++) { char c = ch[i]; switch (c) { case ' ': case '\t': case '\r': case '\n': case ' case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: if (shouldAppendToLangdetectContent()) { nonWhitespaceCharacterCount++; } } } } }
package com.logentries.misc; import android.os.Build; import android.util.Log; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.UUID; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Utils { private static final String TAG = "LogentriesAndroidLogger"; /** * Reg.ex. that is used to check correctness of HostName if it is defined by user */ private static final Pattern HOSTNAME_REGEX = Pattern.compile("[$/\\\"&+,:;=? private static String traceID = ""; private static String hostName = ""; // Requires at least API level 9 (v. >= 2.3). static { try { traceID = computeTraceID(); } catch (NoSuchAlgorithmException ex) { Log.e(TAG, "Cannot get traceID from device's properties!"); traceID = "unknown"; } try { hostName = getProp("net.hostname"); if (hostName.equals("")) { // We have failed to get the real host name // so, use the default one. hostName = InetAddress.getLocalHost().getHostName(); } } catch (UnknownHostException e) { // We cannot resolve local host name - so won't use it at all. } } private static String getProp(String propertyName) { if (propertyName == null || propertyName.isEmpty()) { return ""; } try { Method getString = Build.class.getDeclaredMethod("getString", String.class); getString.setAccessible(true); return getString.invoke(null, propertyName).toString(); } catch (Exception ex) { // Ignore the exception - we simply couldn't access the property; Log.e(TAG, ex.getMessage()); } return ""; } private static String computeTraceID() throws NoSuchAlgorithmException { String fingerprint = getProp("ro.build.fingerprint"); String displayId = getProp("ro.build.display.id"); String hardware = getProp("ro.hardware"); String device = getProp("ro.product.device"); String rilImei = getProp("ril.IMEI"); MessageDigest hashGen = MessageDigest.getInstance("MD5"); byte[] digest = null; if (fingerprint.isEmpty() & displayId.isEmpty() & hardware.isEmpty() & device.isEmpty() & rilImei.isEmpty()) { Log.e(TAG, "Cannot obtain any of device's properties - will use default Trace ID source."); Double randomTrace = Math.random() + Math.PI; String defaultValue = randomTrace.toString(); randomTrace = Math.random() + Math.PI; defaultValue += randomTrace.toString().replace(".", ""); // The code below fixes one strange bug, when call to a freshly installed app crashes at this // point, because random() produces too short sequence. Note, that this behavior does not // occur for the second and all further launches. defaultValue = defaultValue.length() >= 36 ? defaultValue.substring(2, 34) : defaultValue.substring(2); hashGen.update(defaultValue.getBytes()); } else { StringBuilder sb = new StringBuilder(); sb.append(fingerprint).append(displayId).append(hardware).append(device).append(rilImei); hashGen.update(sb.toString().getBytes()); } digest = hashGen.digest(); StringBuilder conv = new StringBuilder(); for (byte b : digest) { conv.append(String.format("%02x", b & 0xff).toUpperCase()); } return conv.toString(); } public static String getTraceID() { return traceID; } private static String getFormattedDeviceId(boolean toJSON) { if (toJSON) { return "\"DeviceId\": \"" + Build.SERIAL + "\""; } return "DeviceId=" + Build.SERIAL; } public static String getFormattedTraceID(boolean toJSON) { if (toJSON) { return "\"TraceID\": \"" + traceID + "\""; } return "TraceID=" + traceID; } public static String getHostName() { return hostName; } public static String getFormattedHostName(boolean toJSON) { if (toJSON) { return "\"Host\": \"" + hostName + "\""; } return "Host=" + hostName; } public static boolean isJSONValid(String message) { try { new JSONObject(message); } catch (JSONException ex) { try { new JSONArray(message); } catch (JSONException ex1) { return false; } } return true; } /** * Formats given message to make it suitable for ingestion by Logentris endpoint. * If isUsingHttp == true, the method produces such structure: * {"event": {"Host": "SOMEHOST", "Timestamp": 12345, "DeviceID": "DEV_ID", "Message": "MESSAGE"}} * <p> * If isUsingHttp == false the output will be like this: * Host=SOMEHOST Timestamp=12345 DeviceID=DEV_ID MESSAGE * * @param message Message to be sent to Logentries * @param logHostName - if set to true - "Host"=HOSTNAME parameter is appended to the message. * @param isUsingHttp will be using http * @return */ public static String formatMessage(String message, boolean logHostName, boolean isUsingHttp) { StringBuilder sb = new StringBuilder(); if (isUsingHttp) { // Add 'event' structure. sb.append("{\"event\": {"); } if (logHostName) { sb.append(Utils.getFormattedHostName(isUsingHttp)); sb.append(isUsingHttp ? ", " : " "); } sb.append(Utils.getFormattedTraceID(isUsingHttp)).append(" "); sb.append(isUsingHttp ? ", " : " "); sb.append(Utils.getFormattedDeviceId(isUsingHttp)).append(" "); sb.append(isUsingHttp ? ", " : " "); long timestamp = System.currentTimeMillis(); // Current time in UTC in milliseconds. if (isUsingHttp) { sb.append("\"Timestamp\": ").append(Long.toString(timestamp)).append(", "); } else { sb.append("Timestamp=").append(Long.toString(timestamp)).append(" "); } // Append the event data if (isUsingHttp) { if (Utils.isJSONValid(message)) { sb.append("\"Message\":").append(message); sb.append("}}"); } else { sb.append("\"Message\": \"").append(message); sb.append("\"}}"); } } else { sb.append(message); } return sb.toString(); } public static boolean checkValidUUID(String uuid) { if (uuid != null && !uuid.isEmpty()) { try { UUID u = UUID.fromString(uuid); return true; } catch (IllegalArgumentException e) { return false; } } return false; } public static boolean checkIfHostNameValid(String hostName) { return !HOSTNAME_REGEX.matcher(hostName).find(); } public static String[] splitStringToChunks(String source, int chunkLength) { if (chunkLength < 0) { throw new IllegalArgumentException("Chunk length must be greater or equal to zero!"); } int srcLength = source.length(); if (chunkLength == 0 || srcLength <= chunkLength) { return new String[]{source}; } ArrayList<String> chunkBuffer = new ArrayList<String>(); int splitSteps = srcLength / chunkLength + (srcLength % chunkLength > 0 ? 1 : 0); int lastCutPosition = 0; for (int i = 0; i < splitSteps; ++i) { if (i < splitSteps - 1) { // Cut out the chunk of the requested size. chunkBuffer.add(source.substring(lastCutPosition, lastCutPosition + chunkLength)); } else { // Cut out all that left to the end of the string. chunkBuffer.add(source.substring(lastCutPosition)); } lastCutPosition += chunkLength; } return chunkBuffer.toArray(new String[chunkBuffer.size()]); } }
package minigame; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import com.sun.corba.se.spi.orbutil.fsm.Input; import LogicGame.NorthScreenLogic; import entity.AlphabetBox; import entity.Gateway; import entity.Player; import render.IRenderable; import render.RenderableHolder; import utility.ConfigurableOption; import utility.InputUtility; public class Passcode implements IRenderable { protected ArrayList<AlphabetBox> keyBoxs; protected ArrayList<AlphabetBox> passwords; protected ArrayList<Integer> randPrimaryKey; protected int width,height; protected int passwordCounter; public Passcode(){ this.keyBoxs = new ArrayList<AlphabetBox>(); this.passwords = new ArrayList<AlphabetBox>(); this.randPrimaryKey = new ArrayList<Integer>(); this.width = this.height = 50; this.passwordCounter = 0; passwords.add(new AlphabetBox(5*12, (ConfigurableOption.screenWidth/2) - 30*2, 30, 25, 25)); passwords.add(new AlphabetBox(10*12, (ConfigurableOption.screenWidth/2) - 30, 30, 25, 25)); passwords.add(new AlphabetBox(15*12, (ConfigurableOption.screenWidth/2), 30, 25, 25)); passwords.add(new AlphabetBox(20*12, (ConfigurableOption.screenWidth/2) + 30, 30, 25, 25)); for(int i = 1 ; i<=20 ; i++){ randPrimaryKey.add(i); } Collections.shuffle(randPrimaryKey); for(int i = 0, c = 0 ; i < 5 ; i++){ for(int j = 0 ; j < 4 ; j++){ keyBoxs.add(new AlphabetBox(randPrimaryKey.get(c++)*12, (ConfigurableOption.screenWidth/2)-(int)(2.5*width)+(i*width), 100+j*height, width, height)); } } for(AlphabetBox keyBox : keyBoxs){ RenderableHolder.getInstance().addSouthEntity(keyBox); } for(AlphabetBox password : passwords){ RenderableHolder.getInstance().addSouthEntity(password); } } @Override public void draw(Graphics2D g2d) { // TODO Auto-generated method stub } @Override public boolean isVisible() { // TODO Auto-generated method stub return false; } public boolean isInPressAreaX(){ return ( ( (InputUtility.getMouseXSouth() - ((ConfigurableOption.screenWidth/2)-(int)(2.5*width)) ) >= 0 ) && ( ( (ConfigurableOption.screenWidth/2)-(int)(2.5*width) + (5*width) ) - InputUtility.getMouseXSouth() >=0 ) ); } public boolean isInPressAreaY(){ return (InputUtility.getMouseYSouth() - 100 >=0 ) && (100+height*4 - InputUtility.getMouseYSouth() >=0); } public boolean isInPressBoxAreaX(AlphabetBox keyBox){ return InputUtility.getMouseXSouth() - keyBox.getX() >=0 && keyBox.getX()+keyBox.getWidth() - InputUtility.getMouseXSouth() >=0; } public boolean isInPressBoxAreaY(AlphabetBox keyBox){ return InputUtility.getMouseYSouth() - keyBox.getY() >=0 && keyBox.getY()+keyBox.getHeight() - InputUtility.getMouseYSouth() >=0; } public void zombieAppear(){ NorthScreenLogic.spawnZombie = true; for(IRenderable rend : RenderableHolder.getInstance().getNorthRenderableList()){ if(rend instanceof Player){ ((Player) rend).zombieIsComming(); break; } } } @Override public void update() { // TODO Auto-generated method stub if(!isInPressAreaX() || !isInPressAreaY()) return; if(passwordCounter<3){ for(AlphabetBox keyBox : keyBoxs){ if(isInPressBoxAreaX(keyBox) && isInPressBoxAreaY(keyBox)){ if(keyBox.getPrimaryKey() == passwords.get(passwordCounter).getPrimaryKey()){ passwords.get(passwordCounter).setSelected(true); keyBox.setSelected(true); passwordCounter++; break; }else{ zombieAppear(); } } } }else{ //Finish Stage 2 for (IRenderable renderable : RenderableHolder.getInstance().getNorthRenderableList()) { if (renderable instanceof Gateway && ((Gateway) renderable).getX() == ConfigurableOption.xGateway2) { ((Gateway) renderable).setGateClose(false); ConfigurableOption.stageNow = 4; break; } } } } public ArrayList<AlphabetBox> getKeyBox(){ return keyBoxs; } public ArrayList<AlphabetBox> getPassword(){ return passwords; } @Override public int getX() { return 0; } @Override public int getY() { return 0; } @Override public int getZ() { return 0; } @Override public boolean isDestroyed() { return false; } @Override public void setDestroyed(boolean destroyed) { } }
package org.eclipse.jgit.fnmatch2; import static java.lang.Character.isLetter; import java.util.*; import java.util.regex.Pattern; import org.eclipse.jgit.errors.InvalidPatternException; public class Strings { static char getPathSeparator(Character pathSeparator) { return pathSeparator == null ? '/' : pathSeparator.charValue(); } public static String stripTrailing(String pattern, char c) { while(pattern.length() > 0 && pattern.charAt(pattern.length() - 1) == c){ pattern = pattern.substring(0, pattern.length() - 1); } return pattern; } static int count(String s, char c, boolean ignoreFirstLast){ int start = 0; int count = 0; while (true) { start = s.indexOf(c, start); if(start == -1) { break; } if(!ignoreFirstLast || (start != 0 && start != s.length())) { count ++; } start ++; } return count; } public static List<String> split(String pattern, char slash){ int count = count(pattern, slash, true); if(count < 1){ throw new IllegalStateException("Pattern must have at least two segments: " + pattern); } List<String> segments = new ArrayList<String>(count); int right = 0; while (true) { int left = right; right = pattern.indexOf(slash, right); if(right == -1) { if(left < pattern.length()){ segments.add(pattern.substring(left)); } break; } if(right - left > 0) { if(left == 1){ // leading slash should remain by the first pattern segments.add(pattern.substring(left - 1, right)); } else if(right == pattern.length() - 1){ // trailing slash should remain too segments.add(pattern.substring(left, right + 1)); } else { segments.add(pattern.substring(left, right)); } } right ++; } return segments; } static boolean isWildCard(String pattern) { return pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1 || pattern.indexOf('[') != -1 || pattern.indexOf('\\') != -1 || pattern.indexOf(']') != -1; } final static List<String> POSIX_CHAR_CLASSES = Arrays.asList( //[:alnum:] [:alpha:] [:blank:] [:cntrl:] "alnum", "alpha", "blank", "cntrl", //[:digit:] [:graph:] [:lower:] [:print:] "digit", "graph", "lower", "print", //[:punct:] [:space:] [:upper:] [:xdigit:] "punct", "space", "upper", "xdigit", // but this was in org.eclipse.jgit.fnmatch.GroupHead.java ??? "word" ); private static final String DL = "\\p{javaDigit}\\p{javaLetter}"; final static List<String> JAVA_CHAR_CLASSES = Arrays.asList( //[:alnum:] [:alpha:] [:blank:] [:cntrl:] "\\p{Alnum}", "\\p{javaLetter}", "\\p{Blank}", "\\p{Cntrl}", //[:digit:] [:graph:] [:lower:] [:print:] "\\p{javaDigit}", "[\\p{Graph}" + DL + "]", "\\p{Ll}", "[\\p{Print}" + DL + "]", //[:punct:] [:space:] [:upper:] [:xdigit:] "\\p{Punct}", "\\p{Space}", "\\p{Lu}", "\\p{XDigit}", "[" + DL + "_]" ); // XXX Collating symbols [.a.] or equivalence class expressions [=a=] are not supported (yet?) // Have no idea if this was simply not implemented in JGit or CLI git don't support this final static Pattern UNSUPPORTED = Pattern.compile("\\[[.=]\\w+[.=]\\]"); static Pattern convertGlob(String pattern) throws InvalidPatternException { if(UNSUPPORTED.matcher(pattern).find()){ throw new InvalidPatternException( "Collating symbols [.a.] or equivalence class expressions [=a=] are not supported yet", pattern); } StringBuilder sb = new StringBuilder(pattern.length()); int in_brackets = 0; boolean seenEscape = false; boolean ignoreLastBracket = false; boolean in_char_class = false; // 6 is the length of the longest posix char class "xdigit" char[] charClass = new char[6]; for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); switch (c) { case '*': if(seenEscape || in_brackets > 0) { sb.append(c); } else { sb.append('.').append(c); } break; case '.': if(seenEscape || in_brackets > 0) { sb.append(c); } else { sb.append('\\').append('.'); } break; case '?': if(seenEscape || in_brackets > 0) { sb.append(c); } else { sb.append('.'); } break; case ':': if(in_brackets > 0) { if(lookBehind(sb) == '[' && isLetter(lookAhead(pattern, i))) { in_char_class = true; } } sb.append(':'); break; case '-': if(in_brackets > 0) { if(lookAhead(pattern, i) == ']') { sb.append('\\').append(c); } else { sb.append(c); } } else { sb.append('-'); } break; case '\\': if(in_brackets > 0) { char lookAhead = lookAhead(pattern, i); if (lookAhead == ']' || lookAhead == '[') { ignoreLastBracket = true; } } sb.append(c); break; case '[': if(in_brackets > 0) { sb.append('\\').append('['); ignoreLastBracket = true; } else { if(!seenEscape){ in_brackets ++; ignoreLastBracket = false; } sb.append('['); } break; case ']': if(seenEscape){ sb.append(']'); ignoreLastBracket = true; break; } if(in_brackets <= 0) { sb.append('\\').append(']'); ignoreLastBracket = true; break; } char lookBehind = lookBehind(sb); if((lookBehind == '[' && !ignoreLastBracket) || lookBehind == '^' || (!in_char_class && lookAhead(pattern, i) == ']')) { sb.append('\\'); sb.append(']'); ignoreLastBracket = true; } else { ignoreLastBracket = false; if(!in_char_class) { in_brackets sb.append(']'); } else { in_char_class = false; String charCl = checkPosixCharClass(charClass); // delete last \[:: chars and set the pattern if(charCl != null){ sb.setLength(sb.length() - 4); sb.append(charCl); } reset(charClass); } } break; case '!': if(in_brackets > 0) { if(lookBehind(sb) == '[') { sb.append('^'); } else { sb.append(c); } } else { sb.append(c); } break; default: if(in_char_class){ setNext(charClass, c); } else{ sb.append(c); } break; } // end switch seenEscape = c == '\\'; } // end for if(in_brackets > 0){ throw new InvalidPatternException("Not closed bracket?", pattern); } return Pattern.compile(sb.toString()); } /** * @return zero of the buffer is empty, otherwise the last character from buffer */ private static char lookBehind(StringBuilder sb) { return sb.length() > 0? sb.charAt(sb.length() - 1) : 0; } /** * @param pattern * @param i current pointer in the pattern * @return zero of the index is out of range, otherwise the next character from given position */ private static char lookAhead(String pattern, int i) { int idx = i + 1; return idx >= pattern.length()? 0 : pattern.charAt(idx); } private static void setNext(char[] buffer, char c){ for (int i = 0; i < buffer.length; i++) { if(buffer[i] == 0){ buffer[i] = c; break; } } } private static void reset(char[] buffer){ for (int i = 0; i < buffer.length; i++) { buffer[i] = 0; } } private static String checkPosixCharClass(char[] buffer){ for (int i = 0; i < POSIX_CHAR_CLASSES.size(); i++) { String clazz = POSIX_CHAR_CLASSES.get(i); boolean match = true; for (int j = 0; j < clazz.length(); j++) { if(buffer[j] != clazz.charAt(j)){ match = false; break; } } if(match) { return JAVA_CHAR_CLASSES.get(i); } } return null; } }
package com.artifex.mupdf.fitz; public final class Location { public final int chapter; public final int page; public final float x, y; public Location(int chapter, int page) { this.chapter = chapter; this.page = page; this.x = this.y = 0; } public Location(int chapter, int page, float x, float y) { this.chapter = chapter; this.page = page; this.x = x; this.y = y; } public boolean equals(Object obj) { if (!(obj instanceof Location)) return false; Location other = (Location) obj; return this.chapter == other.chapter && this.page == other.page && this.x == other.x && this.y == other.y; } }
package mmbn; import java.util.List; import java.util.Random; import rand.DataProvider; import rand.RandomizerContext; public class ItemProvider extends DataProvider<Item> { private final ChipLibrary chipLibrary; private boolean codeOnly; public ItemProvider(RandomizerContext context, ItemProducer producer) { super(context, producer); this.chipLibrary = producer.chipLibrary(); this.codeOnly = false; } public void setCodeOnly(boolean codeOnly) { this.codeOnly = codeOnly; } @Override protected void randomizeData(Random rng, Item item, int position) { if (item.isChip()) { BattleChip chip = item.getChip(); int r; if (!codeOnly) { // Choose a random new battle chip with the same library and rarity. List<BattleChip> possibleChips = this.chipLibrary.query( (byte)-1, chip.getRarity(), chip.getRarity(), null, chip.getLibrary(), 0, 99 ); if (possibleChips.size() <= 0) { possibleChips.add(chip); } r = rng.nextInt(possibleChips.size()); chip = possibleChips.get(r); } // Choose a random code. byte[] possibleCodes = chip.getCodes(); r = rng.nextInt(possibleCodes.length); byte newCode = possibleCodes[r]; if (item.type == Item.Type.BATTLECHIP_TRAP) { item.setChipCodeTrap(chip, newCode); } else { item.setChipCode(chip, newCode); } } } }
package com.jmonad.seq; import com.jmonad.seq.lambda.Function; import java.util.ArrayList; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SeqTest { private final Logger slf4jLogger = LoggerFactory.getLogger(SeqTest.class); @Test public void sampleTest() { Seq<Boolean> names = new Seq(true, true, false, null).compact(); System.out.println(names.toArrayList()); } @Test public void executeArrayZeroToBigNumberTest() { ArrayList<Integer> integers = new ArrayList<Integer>(1000); for (int i = 0; i <= 1000; i++) { integers.add(i); } Function func = new Function<Integer, Integer>() { @Override public Integer call(Integer x) { return x * 2; } }; long startTime = System.nanoTime(); Seq<Integer> values = new Seq<Integer>(integers).map(func); long endTimeFirstRun = System.nanoTime(); String stubInteraction = "Test: " + values.toArrayList(); System.out.print(stubInteraction); long endTimeSecondRun = System.nanoTime(); long durationOne = (endTimeFirstRun - startTime); long durationSecond = (endTimeSecondRun - startTime) / 10000000; slf4jLogger.info("Result one: " + durationOne + " nanosecond(s), Result two:" + durationSecond + "milisecond(s)"); } }
package model; import javafx.beans.property.ReadOnlyStringProperty; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; public class FileManager implements FileManagerInterface { private boolean isComparing; private static FileManagerInterface instance; private FileModelInterface fileModelL; private FileModelInterface fileModelR; private ArrayList<Block> blockArrayList; private int[][] arrayLCS; private FileManager() { fileModelL = new FileModel(); fileModelR = new FileModel(); } /** * FileManager . * * @return FileManager Editor */ public static FileManagerInterface getFileManagerInterface() { if (instance == null) instance = new FileManager(); return instance; } public void setFileModelL(FileModel L) //@@for mock testing by using Easymock { fileModelL = L; } public void setFileModelR(FileModel R) //@@for mock testing by using Easymock { fileModelR = R; } /** * Left Editor File Model . * * @return FileModel Editor FileModel */ public FileModelInterface getFileModelL() { return fileModelL; } /** * Right Editor File Model . * * @return FileModel Editor FileModel */ public FileModelInterface getFileModelR() { return fileModelR; } //FileManager Interface @Override public ArrayList<LineInterface> getLineArrayList(FileManagerInterface.SideOfEditor side) { if (side == SideOfEditor.Left) { if (isComparing) return fileModelL.getCompareLineArrayList(); else return fileModelL.getLineArrayList(); } else { if (isComparing) return fileModelR.getCompareLineArrayList(); else return fileModelR.getLineArrayList(); } } @Override public void updateLineArrayList(String content, SideOfEditor side) { if (side == SideOfEditor.Left) fileModelL.updateArrayList(content); else fileModelR.updateArrayList(content); } @Override public void saveFile(String content, FileManagerInterface.SideOfEditor side) throws FileNotFoundException, SecurityException { if (side == SideOfEditor.Left) { fileModelL.updateArrayList(content); fileModelL.writeFile(); } else { fileModelR.updateArrayList(content); fileModelR.writeFile(); } } @Override public void saveFile(String content, String filepath, FileManagerInterface.SideOfEditor side) throws FileNotFoundException, SecurityException { if (side == SideOfEditor.Left) { fileModelL.updateArrayList(content); fileModelL.writeFile(filepath); } else { fileModelR.updateArrayList(content); fileModelR.writeFile(filepath); } } @Override public ArrayList<LineInterface> loadFile(String filepath, FileManagerInterface.SideOfEditor side) throws FileNotFoundException, UnsupportedEncodingException { if (side == SideOfEditor.Left) { fileModelL.readFile(filepath); return fileModelL.getLineArrayList(); } else { fileModelR.readFile(filepath); return fileModelR.getLineArrayList(); } } @Override public void setCompare() throws LeftEditorFileCanNotCompareException, RightEditorFileCanNotCompareException { if (!(fileModelL.isFileExist() && !fileModelL.getEdited())) throw new LeftEditorFileCanNotCompareException(); if (!(fileModelR.isFileExist() && !fileModelR.getEdited())) throw new RightEditorFileCanNotCompareException(); arrayLCS = new int[fileModelL.getLineArrayList().size() + 1][fileModelR.getLineArrayList().size() + 1];//LCS buildArrayLCS(); backTrackingLCS(); //diff compare array isComparing = true; } @Override public void cancelCompare() { isComparing = false; } @Override public void clickLine(int lineNum) { if (isComparing) fileModelL.clickLine(lineNum); } @Override public boolean merge(FileManagerInterface.SideOfEditor toSide) { if (!isComparing) return false; FileModelInterface fromFileManager; FileModelInterface toFileManager; if (toSide == SideOfEditor.Left) { toFileManager = fileModelL; fromFileManager = fileModelR; } else { fromFileManager = fileModelL; toFileManager = fileModelR; } for (Block b : blockArrayList) { int count = b.endLineNum - b.startLineNum; System.out.println("count = " + count); int insertNum = b.startLineNum; if (b.getSelected()) { for (int i = 0; i < count; i++) { toFileManager.getCompareLineArrayList().remove(insertNum); } for (int i = 0; i < count; i++) { LineInterface tempL = fromFileManager.getCompareLineArrayList().get(insertNum); if (tempL.getIsWhiteSpace()) fromFileManager.getCompareLineArrayList().remove(insertNum); else { LineInterface insertL = new Line(tempL.getContent(true)); toFileManager.getCompareLineArrayList().add(insertNum, insertL); insertNum++; } } } else { for (int i = 0; i < count; i++) { LineInterface tempL = fromFileManager.getCompareLineArrayList().get(insertNum); if (tempL.getIsWhiteSpace()) fromFileManager.getCompareLineArrayList().remove(insertNum); else { insertNum++; } } insertNum = b.startLineNum; for (int i = 0; i < count; i++) { LineInterface tempR = toFileManager.getCompareLineArrayList().get(insertNum); if (tempR.getIsWhiteSpace()) toFileManager.getCompareLineArrayList().remove(insertNum); else { insertNum++; } } } } String ret = ""; for (LineInterface s : toFileManager.getCompareLineArrayList()) ret += s.getContent(false); ret = ret.substring(0, ret.length() - 1); toFileManager.updateArrayList(ret); ret = ""; for (LineInterface s : fromFileManager.getCompareLineArrayList()) ret += s.getContent(false); ret = ret.substring(0, ret.length() - 1); fromFileManager.updateArrayList(ret); cancelCompare(); return true; } //FileManager Interface @Override public String getString(FileManagerInterface.SideOfEditor side) { if (side == SideOfEditor.Left) return fileModelL.toString(); else return fileModelR.toString(); } public String getFilePath(SideOfEditor side) { if (side == SideOfEditor.Left) return getFileModelL().getFilePath(); else return getFileModelR().getFilePath(); } @Override public ReadOnlyStringProperty getStatus(SideOfEditor side) { return side == SideOfEditor.Left ? fileModelL.getStatus() : fileModelR.getStatus(); } private int max(int a, int b) { if (a > b) return a; else return b; } private void buildArrayLCS() {//LCS int[][] arr = arrayLCS; ArrayList<LineInterface> leftArr = fileModelL.getLineArrayList(); // width ArrayList<LineInterface> rightArr = fileModelR.getLineArrayList(); // height int width = arr.length; int height = arr[0].length; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (i == 0 || j == 0) arr[i][j] = 0; else { //System.out.println(leftArr.get(i - 1).content.compareTo(rightArr.get(j - 1).content)); if (leftArr.get(i - 1).getContent(true).compareTo(rightArr.get(j - 1).getContent(true)) == 0) {// getLine true arr[i][j] = arr[i - 1][j - 1] + 1; } else { arr[i][j] = max(arr[i - 1][j], arr[i][j - 1]); } } } } } private void backTrackingLCS()//LCS DIFF { int[][] arr = arrayLCS; ArrayList<LineInterface> leftArr = fileModelL.getLineArrayList(); // width ArrayList<LineInterface> rightArr = fileModelR.getLineArrayList(); // height ArrayList<LineInterface> cLineArrayListL = new ArrayList<LineInterface>(); ArrayList<LineInterface> cLineArrayListR = new ArrayList<LineInterface>(); blockArrayList = new ArrayList<Block>(); Line.setBlockArrayList(blockArrayList); int i = fileModelL.getLineArrayList().size(); int j = fileModelR.getLineArrayList().size(); int startLineNum = 0; int endLineNum = 0; int numBlock = 0; Block tempBlock = null; int count = i + j - arr[i][j]; while (true) { if (i == 0 && j == 0) { if (tempBlock != null) { endLineNum = count; tempBlock.setLineNum(startLineNum, endLineNum); blockArrayList.add(tempBlock); tempBlock = null; } break; } else if (i == 0) { cLineArrayListL.add(new Line("", numBlock, true)); cLineArrayListR.add(new Line(rightArr.get(j - 1).getContent(true), numBlock, false)); j if (tempBlock == null) { startLineNum = count; tempBlock = new Block(); } } else if (j == 0) { cLineArrayListL.add(new Line(leftArr.get(i - 1).getContent(true), numBlock, false)); cLineArrayListR.add(new Line("", numBlock, true)); i if (tempBlock == null) { endLineNum = count; tempBlock = new Block(); } } else if (leftArr.get(i - 1).getContent(true).compareTo(rightArr.get(j - 1).getContent(true)) == 0) { cLineArrayListL.add(new Line(leftArr.get(i - 1).getContent(true), -1, false)); cLineArrayListR.add(new Line(rightArr.get(j - 1).getContent(true), -1, false)); i j if (tempBlock != null) { startLineNum = count; tempBlock.setLineNum(startLineNum, endLineNum); blockArrayList.add(tempBlock); tempBlock = null; numBlock++; } } else if (arr[i][j - 1] > arr[i - 1][j]) { cLineArrayListL.add(new Line("", numBlock, true)); cLineArrayListR.add(new Line(rightArr.get(j - 1).getContent(true), numBlock, false)); j if (tempBlock == null) { endLineNum = count; tempBlock = new Block(); } } else { cLineArrayListL.add(new Line(leftArr.get(i - 1).getContent(true), numBlock, false)); cLineArrayListR.add(new Line("", numBlock, true)); i if (tempBlock == null) { endLineNum = count; tempBlock = new Block(); } } count--; } // block line Collections.reverse(cLineArrayListL); Collections.reverse(cLineArrayListR); fileModelL.setCompareLineArrayList(cLineArrayListL); fileModelR.setCompareLineArrayList(cLineArrayListR); } @Override public int[][] getArrayLCS() { return arrayLCS.clone(); } //@@for test of jUnit @Override public ReadOnlyStringProperty filePathProperty(SideOfEditor side) { if( side == SideOfEditor.Left ) System.out.println("left!"); return side == SideOfEditor.Left ? fileModelL.filePathProperty() : fileModelR.filePathProperty(); } @Override public boolean getComparing() { return isComparing; } @Override public void setEdited(SideOfEditor side, boolean value) { if(side == SideOfEditor.Left){ fileModelL.setEdited(value); } else{ fileModelR.setEdited(value); } } @Override public boolean getEdited(SideOfEditor side){ if(side == SideOfEditor.Left){ return fileModelL.getEdited(); } else{ return fileModelR.getEdited(); } } private void resetModel(FileManagerInterface.SideOfEditor sideOfEditor) { if (sideOfEditor == FileManagerInterface.SideOfEditor.Left) { this.fileModelL = new FileModel(); } else this.fileModelR = new FileModel(); } }
package top.zibin.luban; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.annotation.NonNull; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import static top.zibin.luban.Preconditions.checkNotNull; public class Luban { public static final int FIRST_GEAR = 1; public static final int THIRD_GEAR = 3; private static final String TAG = "Luban"; public static String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache"; private static volatile Luban INSTANCE; private final File mCacheDir; private OnCompressListener compressListener; private File mFile; private int gear = THIRD_GEAR; Luban(File cacheDir) { mCacheDir = cacheDir; } /** * Returns a directory with a default name in the private cache directory of the application to use to store * retrieved media and thumbnails. * * @param context A context. * @see #getPhotoCacheDir(android.content.Context, String) */ public static File getPhotoCacheDir(Context context) { return getPhotoCacheDir(context, Luban.DEFAULT_DISK_CACHE_DIR); } /** * Returns a directory with the given name in the private cache directory of the application to use to store * retrieved media and thumbnails. * * @param context A context. * @param cacheName The name of the subdirectory in which to store the cache. * @see #getPhotoCacheDir(android.content.Context) */ public static File getPhotoCacheDir(Context context, String cacheName) { File cacheDir = context.getCacheDir(); if (cacheDir != null) { File result = new File(cacheDir, cacheName); if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) { // File wasn't able to create a directory, or the result exists but not a directory return null; } return result; } if (Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "default disk cache dir is null"); } return null; } public static Luban get(Context context) { if (INSTANCE == null) INSTANCE = new Luban(Luban.getPhotoCacheDir(context)); return INSTANCE; } public Luban launch() { checkNotNull(mFile, "the image file cannot be null, please call .load() before this method!"); if (gear == Luban.FIRST_GEAR) firstCompress(mFile); else if (gear == Luban.THIRD_GEAR) thirdCompress(mFile.getAbsolutePath()); return this; } public Luban load(File file) { mFile = file; return this; } public Luban setCompressListener(OnCompressListener listener) { compressListener = listener; return this; } public Luban putGear(int gear) { this.gear = gear; return this; } private void thirdCompress(@NonNull String filePath) { String thumb = mCacheDir.getAbsolutePath() + "/" + System.currentTimeMillis(); double s; int a = getImageSpinAngle(filePath); int i = getImageSize(filePath)[0]; int j = getImageSize(filePath)[1]; int k = i % 2 == 1 ? i + 1 : i; int l = j % 2 == 1 ? j + 1 : j; i = k > l ? l : k; j = k > l ? k : l; double c = ((double) i / j); if (c <= 1 && c > 0.5625) { if (j < 1664) { s = (i * j) / Math.pow(1664, 2) * 150; s = s < 60 ? 60 : s; } else if (j >= 1664 && j < 4990) { k = i / 2; l = j / 2; s = (k * l) / Math.pow(2495, 2) * 300; s = s < 60 ? 60 : s; } else if (j >= 4990 && j < 10240) { k = i / 4; l = j / 4; s = (k * l) / Math.pow(2560, 2) * 300; s = s < 100 ? 100 : s; } else { int multiple = j / 1280; k = i / multiple; l = j / multiple; s = (k * l) / Math.pow(2560, 2) * 300; s = s < 100 ? 100 : s; } } else if (c <= 0.5625 && c > 0.5) { int multiple = j / 1280; k = i / multiple; l = j / multiple; s = (k * l) / (1440.0 * 2560.0) * 200; s = s < 100 ? 100 : s; } else { int multiple = (int) Math.ceil(j / (1280.0 / c)); k = i / multiple; l = j / multiple; s = ((k * l) / (1280.0 * (1280 / c))) * 500; s = s < 100 ? 100 : s; } compress(filePath, thumb, k, l, a, (long) s); } private void firstCompress(@NonNull File file) { int minSize = 60; int longSide = 720; int shortSide = 1280; String filePath = file.getAbsolutePath(); String thumbFilePath = mCacheDir.getAbsolutePath() + "/" + System.currentTimeMillis(); long size = 0; long maxSize = file.length() / 5; int angle = getImageSpinAngle(filePath); int[] imgSize = getImageSize(filePath); int width = 0, height = 0; if (imgSize[0] <= imgSize[1]) { double scale = (double) imgSize[0] / (double) imgSize[1]; if (scale <= 1.0 && scale > 0.5625) { width = imgSize[0] > shortSide ? shortSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = minSize; } else if (scale <= 0.5625) { height = imgSize[1] > longSide ? longSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = maxSize; } } else { double scale = (double) imgSize[1] / (double) imgSize[0]; if (scale <= 1.0 && scale > 0.5625) { height = imgSize[1] > shortSide ? shortSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = minSize; } else if (scale <= 0.5625) { width = imgSize[0] > longSide ? longSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = maxSize; } } compress(filePath, thumbFilePath, width, height, angle, size); } /** * obtain the image's width and height * * @param imagePath the path of image */ public int[] getImageSize(String imagePath) { int[] res = new int[2]; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = 1; BitmapFactory.decodeFile(imagePath, options); res[0] = options.outWidth; res[1] = options.outHeight; return res; } /** * obtain the thumbnail that specify the size * * @param imagePath the target image path * @param width the width of thumbnail * @param height the height of thumbnail * @return {@link Bitmap} */ private Bitmap compress(String imagePath, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); int outH = options.outHeight; int outW = options.outWidth; int inSampleSize = 1; if (outH > height || outW > width) { int halfH = outH / 2; int halfW = outW / 2; while ((halfH / inSampleSize) > height && (halfW / inSampleSize) > width) { inSampleSize *= 2; } } options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; int heightRatio = (int) Math.ceil(options.outHeight / (float) height); int widthRatio = (int) Math.ceil(options.outWidth / (float) width); if (heightRatio > 1 || widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(imagePath, options); } /** * obtain the image rotation angle * * @param path path of target image */ private int getImageSpinAngle(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * * create the thumbnail with the true rotate angle * * @param largeImagePath the big image path * @param thumbFilePath the thumbnail path * @param width width of thumbnail * @param height height of thumbnail * @param angle rotation angle of thumbnail * @param size the file size of image */ private void compress(String largeImagePath, String thumbFilePath, int width, int height, int angle, long size) { Bitmap thbBitmap = compress(largeImagePath, width, height); thbBitmap = rotatingImage(angle, thbBitmap); saveImage(thumbFilePath, thbBitmap, size); } /** * * rotate the image with specified angle * * @param angle the angle will be rotating * @param bitmap target image */ private static Bitmap rotatingImage(int angle, Bitmap bitmap) { //rotate image Matrix matrix = new Matrix(); matrix.postRotate(angle); //create a new image return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * * Save image with specified size * * @param filePath the image file save path * @param bitmap the image what be save * @param size the file size of image */ private void saveImage(String filePath, Bitmap bitmap, long size) { checkNotNull(bitmap, TAG + "bitmap cannot be null"); File result = new File(filePath.substring(0, filePath.lastIndexOf("/"))); if (!result.exists() && !result.mkdirs()) return; ByteArrayOutputStream stream = new ByteArrayOutputStream(); int options = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); while (stream.toByteArray().length / 1024 > size) { stream.reset(); options -= 6; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); } try { FileOutputStream fos = new FileOutputStream(filePath); fos.write(stream.toByteArray()); fos.flush(); fos.close(); if (compressListener != null) compressListener.onSuccess(new File(filePath)); } catch (Exception e) { e.printStackTrace(); } } }
//Java forrit til ad spila tona og hljoma (mjog takmarkad) //Matthias //2011 import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.embed.swing.JFXPanel; import java.nio.file.Paths; public class Audio { //samplar toninn (sinus) public static double[] tone(double hz, double t) { //sja fallid freq() if (hz == 666.0) { String a = StdIn.readString(); String b = StdIn.readString(); String c = StdIn.readString(); return chord(a, b, c, t); } int sps = 44100; int N = (int)(sps * t); double[] a = new double[N + 1]; for (int i = 0; i <= N; i++) { a[i] = Math.sin(2 * Math.PI * i * hz / sps); } return a; } //sawtooth bylgja public static double[] sawtooth(double hz, double t) { if (hz == 666.0) { String a = StdIn.readString(); String b = StdIn.readString(); String c = StdIn.readString(); return sawchord(a, b, c, t); } int sps = 44100; int N = (int)(sps * t); double[] a = new double[N + 1]; for (int i = 0; i <= N; i++) { a[i] = (2 * Math.PI * i * (hz / 8.0) / sps) - (int)(2 * Math.PI * i * (hz / 8.0) / sps); } return a; } //triangle bylgja (so far virkar ekki, er bara eins og saw) public static double[] triangle(double hz, double t) { if (hz == 666.0) { String a = StdIn.readString(); String b = StdIn.readString(); String c = StdIn.readString(); return trichord(a, b, c, t); } int sps = 44100; int N = (int)(sps * t); double[] a = new double[N + 1]; for (int i = 0; i <= N; i++) { a[i] = Math.abs((2 * Math.PI * i * (hz / 8.0) / sps) - (int)(2 * Math.PI * i * (hz / 8.0) / sps)); } return a; } //Virkar, byr til square bylgju i stad sinus public static double[] square(double hz, double t) { if (hz == 666.0) { String a = StdIn.readString(); String b = StdIn.readString(); String c = StdIn.readString(); return squarechord(a, b, c, t); } int sps = 44100; int N = (int)(sps * t); double[] a = new double[N + 1]; for (int i = 0; i <= N; i++) { a[i] = (Math.sin(2 * Math.PI * i * hz / sps)) / (Math.abs(Math.sin(2 * Math.PI * i * hz / sps))); } return a; } //Notkun: a = freq(x) //Fyrir: x er bokstafur sem taknar notu: //C, Cis/Db, D, Dis/Eb, E, F, Fis/Gb, G, Gis/Ab, A, Ais/Bb, B og t.d. Cis3 eda B6 (C = C4) //Eftir: a er tidnin sem taknar notuna public static double freq(String x) { //mid attund (nr 4) String[] a = { "C", "Cis", "Db", "D", "Dis", "Eb", "E", "F", "Fis", "Gb", "G", "Gis", "Ab", "A", "Ais", "Bb", "B" }; double[] b = { 261.63, 277.18, 277.18, 293.66, 311.13, 311.13, 329.63, 349.23, 369.99, 369.99, 392.00, 415.30, 415.30, 440.00, 466.16, 466.16, 493.88 }; //attund nr 3 String[] a3 = { "C3", "Cis3", "Db3", "D3", "Dis3", "Eb3", "E3", "F3", "Fis3", "Gb3", "G3", "Gis3", "Ab3", "A3", "Ais3", "Bb3", "B3" }; double[] b3 = new double[a3.length]; for (int i = 0; i < b3.length; i++) { b3[i] = b[i] / 2; } //attund nr 5 String[] a5 = { "C5", "Cis5", "Db5", "D5", "Dis5", "Eb5", "E5", "F5", "Fis5", "Gb5", "G5", "Gis5", "Ab5", "A5", "Ais5", "Bb5", "B5" }; double[] b5 = new double[a5.length]; for (int i = 0; i < b5.length; i++) { b5[i] = b[i] * 2; } //attund nr 2 String[] a2 = { "C2", "Cis2", "Db2", "D2", "Dis2", "Eb2", "E2", "F2", "Fis2", "Gb2", "G2", "Gis2", "Ab2", "A2", "Ais2", "Bb2", "B2" }; double[] b2 = new double[a2.length]; for (int i = 0; i < b2.length; i++) { b2[i] = b3[i] / 2; } //attund nr 6 String[] a6 = { "C6", "Cis6", "Db6", "D6", "Dis6", "Eb6", "E6", "F6", "Fis6", "Gb6", "G6", "Gis6", "Ab6", "A6", "Ais6", "Bb6", "B6" }; double[] b6 = new double[a6.length]; for (int i = 0; i < b6.length; i++) { b6[i] = b5[i] * 2; } //bara til minningar um thekkingarleysi: /* if (x.length() == 1 && a[i].length() == 1) { if (x.charAt(0) == a[i].charAt(0)) { return b[i]; } } else if (x.length() == 2 && a[i].length() == 2) { if (x.charAt(0) == a[i].charAt(0) && x.charAt(1) == a[i].charAt(1)) { return b[i]; } } else if (x.length() == 3 && a[i].length() == 3) { if (x.charAt(0) == a[i].charAt(0) && x.charAt(1) == a[i].charAt(1) && x.charAt(2) == a[i].charAt(2)) { return b[i]; } } else if (x.length() == 4 && a[i].length() == 4) { if (x.charAt(0) == a[i].charAt(0) && x.charAt(1) == a[i].charAt(1) && x.charAt(2) == a[i].charAt(2) && x.charAt(3) == a[i].charAt(3)) return b[i]; }*/ for (int i = 0; i < a.length; i++) { if (x.equals("c")) { return 666.0; } else if (x.equals("R")) { return 0.0; } else if (x.equals(a[i])) { return b[i]; } else if (x.equals(a3[i])) { return b3[i]; } else if (x.equals(a5[i])) { return b5[i]; } else if (x.equals(a2[i])) { return b2[i]; } else if (x.equals(a6[i])) { return b6[i]; } } return -1.0; } public static double[] sum(double[] a, double[] b, double awt, double bwt) { //superpose a and b, weigthed double[] c = new double[a.length]; for (int i = 0; i < a.length; i++) { c[i] = a[i] * awt + b[i] * bwt; } return c; } //tekur inn thrja strengi sem taknar hljom t.d. Cis E Gis og skilar fylki med tidni sem taknar hljominn public static double[] chord(String x, String y, String z, double t) { double[] G = tone(freq(x), t); double[] G1 = tone(freq(y), t); double[] G2 = tone(freq(z), t); double[] h = sum(G1, G2, .5, .5); return sum(G, h, .33, .67); } public static double[] sawchord(String x, String y, String z, double t) { double[] G = sawtooth(freq(x), t); double[] G1 = sawtooth(freq(y), t); double[] G2 = sawtooth(freq(z), t); double[] h = sum(G1, G2, .5, .5); return sum(G, h, .33, .67); } public static double[] trichord(String x, String y, String z, double t) { double[] G = triangle(freq(x), t); double[] G1 = triangle(freq(y), t); double[] G2 = triangle(freq(z), t); double[] h = sum(G1, G2, .5, .5); return sum(G, h, .33, .67); } public static double[] squarechord(String x, String y, String z, double t) { double[] G = square(freq(x), t); double[] G1 = square(freq(y), t); double[] G2 = square(freq(z), t); double[] h = sum(G1, G2, .5, .5); return sum(G, h, .33, .67); } public static void loopchord(String note1, String note2, String note3, double t) { double[] userchord = chord(note1, note2, note3, t); while (1 > 0) { StdAudio.play(userchord); } } public static void loopchord(String note1, String note2, String note3, String note4, String note5, String note6, String note7, String note8, String note9, String note10, String note11, String note12, double t) { double[] userchord1 = chord(note1, note2, note3, t); double[] userchord2 = chord(note4, note5, note6, t); double[] userchord3 = chord(note7, note8, note9, t); double[] userchord4 = chord(note10, note11, note12, t); String lol = "lol"; while (lol != "wtf") { StdAudio.play(userchord1); StdAudio.play(userchord2); StdAudio.play(userchord3); StdAudio.play(userchord4); } } public static void loopsquarechord(String note1, String note2, String note3, String note4, String note5, String note6, String note7, String note8, String note9, String note10, String note11, String note12, double t) { double[] userchord1 = squarechord(note1, note2, note3, t); double[] userchord2 = squarechord(note4, note5, note6, t); double[] userchord3 = squarechord(note7, note8, note9, t); double[] userchord4 = squarechord(note10, note11, note12, t); while (true) { StdAudio.play(userchord1); StdAudio.play(userchord2); StdAudio.play(userchord3); StdAudio.play(userchord4); } } //teknar flott munstur i command prompt public static void flipp() { for (int i = 1; i <= 10000; i++) { for (int j = 1; j <= 10000; j++) { if ((i % j == 0 || j % i == 0)) { System.out.print("* "); } else { System.out.print(" "); } } } } //setur saman 4 fylki i 1 public static double[] splice(double[] f, double[] a, double[] b, double[] c) { double[] x = new double[(f.length + a.length + b.length + c.length)]; for (int i = 0; i < x.length; i++) { if (i < f.length) { x[i] = f[i]; } else if (i >= f.length && i < a.length + f.length) { x[i] = a[i - f.length]; } else if (i >= f.length + a.length && i < f.length + a.length + b.length) { x[i] = b[i - (f.length + a.length)]; } else { x[i] = c[i - (f.length + a.length + b.length)]; } } return x; } public static void main(String[] args) { StdOut.println("Note: C-sharp is denoted by \"Cis\" and A-flat by \"Ab\" for example.\n"); StdOut.println(" C3 is one octave lower than C and C5 is one octave higher and\n"); StdOut.println(" so on and so forth.\n"); StdOut.println(" A rest is denoted by \"R\".\n"); StdOut.println(" If you want to play notes or chords(sine), press: n\n "); StdOut.println(" If you want to play notes or chords(square), type: mega\n "); StdOut.println(" If you want to play notes or chords(triangle), type: tri\n "); StdOut.println(" If you want to play notes or chords(sawtooth), type: saw\n "); StdOut.println(" If you want to loop a chord, press: l\n "); StdOut.println(" If you want to loop 4 chords, press: x\n "); StdOut.println(" If you want to loop 4 square chords, press: xmega\n "); StdOut.println(" If you want to listen to a good song while you watch, press: z\n "); String answer = StdIn.readString(); if (answer.equalsIgnoreCase("n")) { StdOut.println("\nInsert notes please.\n"); StdOut.println("Example: Play C for 1 second is \"C 1\"\n"); StdOut.println(" To play a chord type \"c 1 C E G\" to play a C-major\n"); StdOut.println(" chord.\n"); String note; double t = 0; while (!StdIn.isEmpty()) { note = StdIn.readString(); t = StdIn.readDouble(); double[] a = tone(freq(note), t); StdAudio.play(a); } } else if (answer.equalsIgnoreCase("mega")) { StdOut.println("\nInsert notes please.\n"); StdOut.println("Example: Play C for 1 second is \"C 1\"\n"); StdOut.println(" To play a chord type \"c 1 C E G\" to play a C-major\n"); StdOut.println(" chord.\n"); String note; double t = 0; while (!StdIn.isEmpty()) { note = StdIn.readString(); t = StdIn.readDouble(); double[] a = square(freq(note), t); StdAudio.play(a); } } else if (answer.equalsIgnoreCase("tri")) { StdOut.println("\nInsert notes please.\n"); StdOut.println("Example: Play C for 1 second is \"C 1\"\n"); StdOut.println(" To play a chord type \"c 1 C E G\" to play a C-major\n"); StdOut.println(" chord.\n"); String note; double t = 0; while (!StdIn.isEmpty()) { note = StdIn.readString(); t = StdIn.readDouble(); double[] a = triangle(freq(note), t); StdAudio.play(a); } } else if (answer.equalsIgnoreCase("saw")) { StdOut.println("\nInsert notes please.\n"); StdOut.println("Example: Play C for 1 second is \"C 1\"\n"); StdOut.println(" To play a chord type \"c 1 C E G\" to play a C-major\n"); StdOut.println(" chord.\n"); String note; double t = 0; while (!StdIn.isEmpty()) { note = StdIn.readString(); t = StdIn.readDouble(); double[] a = sawtooth(freq(note), t); StdAudio.play(a); } } else if (answer.equalsIgnoreCase("l")) { StdOut.println(" To play a chord type \"C E G 1\" to loop a C-major\n"); StdOut.println(" chord played for 1 second at a time.\n"); String note1 = StdIn.readString(); String note2 = StdIn.readString(); String note3 = StdIn.readString(); double t = StdIn.readDouble(); loopchord(note1, note2, note3, t); } else if (answer.equalsIgnoreCase("x")) { StdOut.println(" To loop the chords type \"C E G F A C5 G B D5 E G C5 1\" to loop a C-major,\n"); StdOut.println(" F-major, G major, and a C-major chord played for 1 second each.\n"); String note1 = StdIn.readString(); String note2 = StdIn.readString(); String note3 = StdIn.readString(); String note4 = StdIn.readString(); String note5 = StdIn.readString(); String note6 = StdIn.readString(); String note7 = StdIn.readString(); String note8 = StdIn.readString(); String note9 = StdIn.readString(); String note10 = StdIn.readString(); String note11 = StdIn.readString(); String note12 = StdIn.readString(); double t = StdIn.readDouble(); loopchord(note1, note2, note3, note4, note5, note6, note7, note8, note9, note10, note11, note12, t); } else if (answer.equalsIgnoreCase("xmega")) { StdOut.println(" To loop the chords type \"C E G F A C5 G B D5 E G C5 1\" to loop a C-major,\n"); StdOut.println(" F-major, G major, and a C-major chord played for 1 second each.\n"); String note1 = StdIn.readString(); String note2 = StdIn.readString(); String note3 = StdIn.readString(); String note4 = StdIn.readString(); String note5 = StdIn.readString(); String note6 = StdIn.readString(); String note7 = StdIn.readString(); String note8 = StdIn.readString(); String note9 = StdIn.readString(); String note10 = StdIn.readString(); String note11 = StdIn.readString(); String note12 = StdIn.readString(); double t = StdIn.readDouble(); loopsquarechord(note1, note2, note3, note4, note5, note6, note7, note8, note9, note10, note11, note12, t); } else if (answer.equalsIgnoreCase("z")) { /*AePlayWave aw = new AePlayWave("TogFeBachiDm.wav"); aw.start();*/ JFXPanel fxPanel = new JFXPanel(); // hack to get hidden initialization of javafx lib Media m = new Media(Paths.get("TogFeBachiDm.mp3").toUri().toString()); MediaPlayer mp = new MediaPlayer(m); mp.play(); flipp(); } //main test bara else if (answer.equalsIgnoreCase("test")) { maintest(); } else StdOut.println("Wrong entry, bye bye."); } public static void maintest() { StdOut.println("\nTest."); String note; String note1; String note2; double t = 0.0; double t1 = 0.0; double t2 = 0.0; String note0; double t0 = 0.0; note0 = StdIn.readString(); t0 = StdIn.readDouble(); double[] f = triangle(freq(note0), t0); note = StdIn.readString(); t = StdIn.readDouble(); double[] a = triangle(freq(note), t); note1 = StdIn.readString(); t1 = StdIn.readDouble(); double[] b = triangle(freq(note1), t1); note2 = StdIn.readString(); t2 = StdIn.readDouble(); double[] c = triangle(freq(note2), t2); double[] x = splice(f, a, b, c); StdAudio.play(x); StdAudio.save("Tri.wav", x); } }
package data_manipulation; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class D0722_Extract_exonHash_from_CCDSHs371 { /******** * The main() method; * create a new extract exon Hash from CCDS object, * call run() method to get all exons, and update the HashMap<geneName, Exon_ArrayList>; * * @param args * @throws IOException */ public static void main(String[] args) throws IOException{ //create a new object of Extracting Exon Hash from CCDS document; D0722_Extract_exonHash_from_CCDSHs371 get_exons = new D0722_Extract_exonHash_from_CCDSHs371(); // D0627_GetGeneNames_from_ALSData getNames = new D0627_GetGeneNames_from_ALSData(); //Initial a HashMap; HashMap<String, ArrayList<Exon_objects>> exonHash = new HashMap<String, ArrayList<Exon_objects>>(); //call run() method, to get all exons, and update the HashMap; get_exons.run( exonHash ); /*** * the gene names from ALS * String[] geneList = getNames.run(); for( int i=0; i<geneList.length; i++){ String gene_name = geneList[i]; get_exons.run(gene_name, exonHash); System.out.println(gene_name + " done."); } */ } //end of main(); private void run(HashMap<String, ArrayList<Exon_objects>> exonHash) throws IOException { // TODO Auto-generated method stub //1st, find the routine to the CCDS15_exon_frame.txt document; String routine = "D:/PhD/CCDS_exon_frames/Hs37.1/"; String file_name = "CCDS.current.txt"; Scanner read_in = new Scanner(new File(routine + file_name)); //3rd, get and write title line String title_line = read_in.nextLine(); System.out.println("Title line: " + title_line); int totalExons = 0; while(read_in.hasNextLine()){ String currLine = read_in.nextLine(); String[] exons = currLine.split("\t"); if(exons[1].equals(geneName)){ totalExons++; out_writer.write(currLine + "\n"); } //end if condition }//end while loop; System.out.println("There are " + totalExons + " exons on gene " + geneName + ", based on different transcripts. "); read_in.close(); out_writer.close(); }//end of run() method; }
/* * $Log: XmlUtils.java,v $ * Revision 1.20 2005-06-20 09:01:44 europe\L190409 * made identity_transform public * * Revision 1.19 2005/06/13 11:48:32 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made namespaceAware option for stringToSource * made separate version of stringToSource, optimized for single use * * Revision 1.18 2005/06/13 10:12:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected handling of namespaces in DomDocumentBuilder; * namespaceAware is now an optional parameter (default=true) * * Revision 1.17 2005/05/31 09:38:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added versionInfo() and stringToSource() * * Revision 1.16 2005/01/10 08:56:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Xslt parameter handling by Maps instead of by Ibis parameter system * * Revision 1.15 2004/11/10 13:01:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added dynamic setting of copy-method in createXpathEvaluatorSource * * Revision 1.14 2004/10/26 16:18:08 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * set UTF-8 as default inputstream encoding * * Revision 1.13 2004/10/26 15:35:55 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * reduced logging for transformer parameter setting * * Revision 1.12 2004/10/12 15:15:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected XmlDeclaration-handling * * Revision 1.11 2004/10/05 09:56:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of TransformerPool * * Revision 1.10 2004/09/01 07:15:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added namespaced xpath evaluator * * Revision 1.9 2004/06/21 10:04:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added version of createXPathEvaluator() that allows to * set output-method to xml (instead of only text), and uses copy-of instead of * value-of * * Revision 1.8 2004/06/16 13:08:34 Johan Verrips <johan.verrips@ibissource.org> * added IdentityTransform * * Revision 1.7 2004/05/25 09:11:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added transformXml from Document * * Revision 1.6 2004/05/25 08:41:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added createXPathEvaluator() * * Revision 1.5 2004/04/27 10:52:50 unknown <unknown@ibissource.org> * Make thread-safety a little more efficient * * Revision 1.4 2004/03/26 10:42:37 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.3 2004/03/23 17:09:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * cosmetic changes * */ package nl.nn.adapterframework.util; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.exception.NestableException; import org.apache.log4j.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.Source; import javax.xml.transform.Result; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.Reader; import java.io.FileReader; import java.io.StringReader; import java.io.StringWriter; import java.io.InputStreamReader; import java.io.IOException; import java.io.FileNotFoundException; import java.net.URL; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; public class XmlUtils { public static final String version = "$RCSfile: XmlUtils.java,v $ $Revision: 1.20 $ $Date: 2005-06-20 09:01:44 $"; static Logger log = Logger.getLogger(XmlUtils.class); static final String W3C_XML_SCHEMA = "http: static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; public final static String OPEN_FROM_FILE = "file"; public final static String OPEN_FROM_URL = "url"; public final static String OPEN_FROM_RESOURCE = "resource"; public final static String OPEN_FROM_XML = "xml"; public static final String XPATH_GETROOTNODENAME = "name(/node()[position()=last()])"; public static String IDENTITY_TRANSFORM = "<?xml version=\"1.0\"?><xsl:stylesheet xmlns:xsl=\"http: + "<xsl:template match=\"@*|*|processing-instruction()|comment()\">" + "<xsl:copy><xsl:apply-templates select=\"*|@*|text()|processing-instruction()|comment()\" />" + "</xsl:copy></xsl:template></xsl:stylesheet>"; public XmlUtils() { super(); } static public Document buildDomDocument(File file) throws DomBuilderException { Reader in; Document output; try { in = new FileReader(file); } catch (FileNotFoundException e) { throw new DomBuilderException(e); } output = buildDomDocument(in); try { in.close(); } catch (IOException e) { log.debug("xception closing file", e); } return output; } static public Document buildDomDocument(Reader in) throws DomBuilderException { return buildDomDocument(in,true); } static public Document buildDomDocument(Reader in, boolean namespaceAware) throws DomBuilderException { Document document; InputSource src; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(namespaceAware); try { DocumentBuilder builder = factory.newDocumentBuilder(); src = new InputSource(in); document = builder.parse(src); } catch (SAXParseException e) { throw new DomBuilderException(e); } catch (ParserConfigurationException e) { throw new DomBuilderException(e); } catch (IOException e) { throw new DomBuilderException(e); } catch (SAXException e) { throw new DomBuilderException(e); } if (document == null) { throw new DomBuilderException("Parsed Document is null"); } return document; } public static Document buildDomDocument(String s) throws DomBuilderException { StringReader sr = new StringReader(s); return (buildDomDocument(sr)); } public static Document buildDomDocument(String s, boolean namespaceAware) throws DomBuilderException { StringReader sr = new StringReader(s); return (buildDomDocument(sr,namespaceAware)); } /** * Build a Document from a URL * @param url * @return Document * @throws DomBuilderException */ static public Document buildDomDocument(URL url) throws DomBuilderException { Reader in; Document output; try { in = new InputStreamReader(url.openStream(),Misc.DEFAULT_INPUT_STREAM_ENCODING); } catch (IOException e) { throw new DomBuilderException(e); } output = buildDomDocument(in); try { in.close(); } catch (IOException e) { log.debug("Exception closing URL-stream", e); } return output; } public static Element buildElement(String s) throws DomBuilderException { return buildDomDocument(s).getDocumentElement(); } public static String createXPathEvaluatorSource(String XPathExpression) throws TransformerConfigurationException { return createXPathEvaluatorSource(XPathExpression,"text"); } /* * version of createXPathEvaluator that allows to set outputMethod, and uses copy-of instead of value-of */ public static String createXPathEvaluatorSource(String namespaceDefs, String XPathExpression, String outputMethod, boolean includeXmlDeclaration) throws TransformerConfigurationException { if (StringUtils.isEmpty(XPathExpression)) throw new TransformerConfigurationException("XPathExpression must be filled"); if (namespaceDefs==null) { namespaceDefs=""; } String copyMethod; if ("xml".equals(outputMethod)) { copyMethod="copy-of"; } else { copyMethod="value-of"; } String xsl = // "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<xsl:stylesheet xmlns:xsl=\"http: "<xsl:output method=\""+outputMethod+"\" omit-xml-declaration=\""+ (includeXmlDeclaration ? "no": "yes") +"\"/>" + "<xsl:strip-space elements=\"*\"/>" + "<xsl:template match=\"/\">" + "<xsl:"+copyMethod+" "+namespaceDefs+" select=\"" + XPathExpression + "\"/>" + "</xsl:template>" + "</xsl:stylesheet>"; return xsl; } public static String createXPathEvaluatorSource(String namespaceDefs, String XPathExpression, String outputMethod) throws TransformerConfigurationException { return createXPathEvaluatorSource(namespaceDefs, XPathExpression, outputMethod, false); } public static String createXPathEvaluatorSource(String XPathExpression, String outputMethod) throws TransformerConfigurationException { return createXPathEvaluatorSource(null, XPathExpression, outputMethod); } public static Transformer createXPathEvaluator(String XPathExpression) throws TransformerConfigurationException { return createTransformer(createXPathEvaluatorSource(XPathExpression)); } public static Transformer createXPathEvaluator(String namespaceDefs, String XPathExpression, String outputMethod) throws TransformerConfigurationException { return createTransformer(createXPathEvaluatorSource(namespaceDefs, XPathExpression, outputMethod)); } public static Transformer createXPathEvaluator(String XPathExpression, String outputMethod) throws TransformerConfigurationException { return createXPathEvaluator(XPathExpression, outputMethod); } /** * Converts a string containing xml-markup to a Source-object, that can be used as the input of a XSLT-transformer. * The source may be used multiple times. */ public static Source stringToSource(String xmlString, boolean namespaceAware) throws DomBuilderException { Document doc = XmlUtils.buildDomDocument(xmlString,namespaceAware); return new DOMSource(doc); } public static Source stringToSource(String xmlString) throws DomBuilderException { return stringToSource(xmlString,true); } public static Source stringToSourceForSingleUse(String xmlString) throws DomBuilderException { StringReader sr = new StringReader(xmlString); return new StreamSource(sr); } public static synchronized Transformer createTransformer(String xsltString) throws TransformerConfigurationException { StringReader sr = new StringReader(xsltString); StreamSource stylesource = new StreamSource(sr); return createTransformer(stylesource); } public static synchronized Transformer createTransformer(URL url) throws TransformerConfigurationException, IOException { StreamSource stylesource = new StreamSource(url.openStream(),Misc.DEFAULT_INPUT_STREAM_ENCODING); stylesource.setSystemId(url.toString()); return createTransformer(stylesource); } public static synchronized Transformer createTransformer(Source source) throws TransformerConfigurationException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer result; result = tFactory.newTransformer(source); return result; } /** * translates special characters to xml equivalents * like <b>&gt;</b> and <b>&amp;</b> */ public static String encodeChars(String string) { int length = string.length(); char[] characters = new char[length]; string.getChars(0, length, characters, 0); StringBuffer encoded = new StringBuffer(); String escape; for (int i = 0; i < length; i++) { escape = escapeChar(characters[i]); if (escape == null) encoded.append(characters[i]); else encoded.append(escape); } return encoded.toString(); } /** * Conversion of special xml signs **/ private static String escapeChar(char c) { switch (c) { case ('<') : return "&lt;"; case ('>') : return "&gt;"; case ('&') : return "&amp;"; case ('\"') : return "&quot;"; } return null; } /** * Method getChildTagAsBoolean. * Return the boolean-value of the first element with tag * <code>tag</code> in the DOM subtree <code>el</code>. * * <p> * To determine true or false, the value of the tag is compared case- * insensitive with the values <pre>true</pre>, <pre>yes</pre>, or * <pre>on</pre>. If it matches, <code>true</code> is returned. If not, * <code>false</code> is returned. * * <p> * If the tag can not be found, <code>false</code> is returned. * * @param el DOM subtree * @param tag Name of tag to find * * @return boolean The value found. */ static public boolean getChildTagAsBoolean(Element el, String tag) { return getChildTagAsBoolean(el, tag, false); } /** * Method getChildTagAsBoolean. * Return the boolean-value of the first element with tag * <code>tag</code> in the DOM subtree <code>el</code>. * * <p> * To determine true or false, the value of the tag is compared case- * insensitive with the values <pre>true</pre>, <pre>yes</pre>, or * <pre>on</pre>. If it matches, <code>true</code> is returned. If not, * <code>false</code> is returned. * * <p> * If the tag can not be found, the default-value is returned. * * @param el DOM subtree * @param tag Name of tag to find * @param defaultValue Default-value in case tag can not * be found. * * @return boolean The value found. */ static public boolean getChildTagAsBoolean( Element el, String tag, boolean defaultValue) { String str; boolean bool; str = getChildTagAsString(el, tag, null); if (str == null) { return defaultValue; } bool = false; if (str.equalsIgnoreCase("true") || str.equalsIgnoreCase("yes") || str.equalsIgnoreCase("on")) { bool = true; } return bool; } /** * Method getChildTagAsLong. * Return the long integer-value of the first element with tag * <code>tag</code> in the DOM subtree <code>el</code>. * * @param el DOM subtree * @param tag Name of tag to find * * @return long The value found. Returns 0 if no * tag can be found, or if the tag * doesn't have an integer-value. */ static public long getChildTagAsLong(Element el, String tag) { return getChildTagAsLong(el, tag, 0); } /** * Method getChildTagAsLong. * Return the long integer-value of the first element with tag * <code>tag</code> in the DOM subtree <code>el</code>. * * @param el DOM subtree * @param tag Name of tag to find * @param defaultValue Default-value in case tag can not * be found, or is not numeric. * * @return long The value found. */ static public long getChildTagAsLong( Element el, String tag, long defaultValue) { String str; long num; str = getChildTagAsString(el, tag, null); num = 0; if (str == null) { return defaultValue; } try { num = Long.parseLong(str); } catch (NumberFormatException e) { num = defaultValue; System.err.println("Tag " + tag + " has no integer value"); e.printStackTrace(); } return num; } /** * Method getChildTagAsString. * Return the value of the first element with tag * <code>tag</code> in the DOM subtree <code>el</code>. * * @param el DOM subtree * @param tag Name of tag to find * * @return String The value found, or null if no matching * tag is found. */ static public String getChildTagAsString(Element el, String tag) { return getChildTagAsString(el, tag, null); } /** * Method getChildTagAsString. * Return the value of the first element with tag * <code>tag</code> in the DOM subtree <code>el</code>. * * @param el DOM subtree * @param tag Name of tag to find * @param defaultValue Default-value in case tag can not * be found. * * @return String The value found. */ static public String getChildTagAsString( Element el, String tag, String defaultValue) { Element tmpEl; String str = ""; tmpEl = getFirstChildTag(el, tag); if (tmpEl != null) { str = getStringValue(tmpEl, true); } return (str.length() == 0) ? (defaultValue) : (str); } /** * Method getChildTags. Get all direct children of given element which * match the given tag. * This method only looks at the direct children of the given node, and * doesn't descent deeper into the tree. If a '*' is passed as tag, * all elements are returned. * * @param el Element where to get children from * @param tag Tag to match. Use '*' to match all tags. * @return Collection Collection containing all elements found. If * size() returns 0, then no matching elements * were found. All items in the collection can * be safely cast to type * <code>org.w3c.dom.Element</code>. */ public static Collection getChildTags(Element el, String tag) { Collection c; NodeList nl; int len; boolean allChildren; c = new LinkedList(); nl = el.getChildNodes(); len = nl.getLength(); if ("*".equals(tag)) { allChildren = true; } else { allChildren = false; } for (int i = 0; i < len; i++) { Node n = nl.item(i); if (n instanceof Element) { Element e = (Element) n; if (allChildren || e.getTagName().equals(tag)) { c.add(n); } } } return c; } /** * Method getFirstChildTag. Return the first child-node which is an element * with tagName equal to given tag. * This method only looks at the direct children of the given node, and * doesn't descent deeper into the tree. * * @param el Element where to get children from * @param tag Tag to match * @return Element The element found, or <code>null</code> if no match * found. */ static public Element getFirstChildTag(Element el, String tag) { NodeList nl; int len; nl = el.getChildNodes(); len = nl.getLength(); for (int i = 0; i < len; ++i) { Node n = nl.item(i); if (n instanceof Element) { Element elem = (Element) n; if (elem.getTagName().equals(tag)) { return elem; } } } return null; } static public String getStringValue(Element el) { return getStringValue(el, true); } static public String getStringValue(Element el, boolean trimWhitespace) { StringBuffer sb = new StringBuffer(1024); String str; NodeList nl = el.getChildNodes(); for (int i = 0; i < nl.getLength(); ++i) { Node n = nl.item(i); if (n instanceof Text) { sb.append(n.getNodeValue()); } } if (trimWhitespace) { str = sb.toString().trim(); } else { str = sb.toString(); } return str; } /** * sets all the parameters of the transformer using a HashMap with parameter values. */ public static void setTransformerParameters(Transformer t, Map parameters) { t.clearParameters(); if (parameters == null) { return; } for (Iterator it=parameters.keySet().iterator(); it.hasNext();) { String name=(String)it.next(); Object value = parameters.get(name); if (value != null) { t.setParameter(name, value); log.debug("setting parameter [" + name+ "] on transformer"); } else { log.warn("omitting setting of parameter ["+name+"] on transformer, as it has a null-value"); } } } public static String transformXml(Transformer t, Document d) throws TransformerException, IOException { return transformXml(t, new DOMSource(d)); } public static String transformXml(Transformer t, String s) throws TransformerException, IOException, DomBuilderException { // log.debug("transforming under the assumption that source document may contain namespaces (therefore using DOMSource)"); return transformXml(t, stringToSourceForSingleUse(s)); } public static String transformXml(Transformer t, Source s) throws TransformerException, IOException { StringWriter out = new StringWriter(64 * 1024); Result result = new StreamResult(out); synchronized (t) { t.transform(s, result); } out = (StringWriter) ((StreamResult) result).getWriter(); out.close(); return (out.getBuffer().toString()); } /* *This function does not operate with Xerces 1.4.1 */ static public boolean ValidateToSchema(InputSource src, URL schema) throws NestableException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); SAXParser saxParser; try { saxParser = factory.newSAXParser(); saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); saxParser.setProperty(JAXP_SCHEMA_SOURCE, schema.openStream()); } catch (ParserConfigurationException e) { throw new NestableException(e); } catch (SAXException e) { throw new NestableException(e); } catch (IOException e) { throw new NestableException(e); } try { saxParser.parse(src, new DefaultHandler()); return true; } catch (Exception e) { log.warn(e); } return false; } /** * Performs an Identity-transform, with resolving entities with the content files in the classpath * @param input * @return String (the complete and xml) * @throws DomBuilderException */ static public String identityTransform(String input) throws DomBuilderException { String result = ""; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document; DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new ClassPathEntityResolver()); StringReader sr = new StringReader(input); InputSource src = new InputSource(sr); document = builder.parse(src); Transformer t = XmlUtils.createTransformer(IDENTITY_TRANSFORM); Source s = new DOMSource(document); result = XmlUtils.transformXml(t, s); } catch (Exception tce) { throw new DomBuilderException(tce); } return result; } public static String getVersionInfo() { StringBuffer sb=new StringBuffer(); sb.append(version+SystemUtils.LINE_SEPARATOR); sb.append("XML tool version info:"+SystemUtils.LINE_SEPARATOR); SAXParserFactory spFactory = SAXParserFactory.newInstance(); sb.append("SAXParserFactory-class ="+spFactory.getClass().getName()+SystemUtils.LINE_SEPARATOR); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); sb.append("DocumentBuilderFactory-class ="+domFactory.getClass().getName()+SystemUtils.LINE_SEPARATOR); TransformerFactory tFactory = TransformerFactory.newInstance(); sb.append("TransformerFactory-class ="+tFactory.getClass().getName()+SystemUtils.LINE_SEPARATOR); sb.append("Apache-XML tool version info:"+SystemUtils.LINE_SEPARATOR); try { sb.append("Xerces-Version="+org.apache.xerces.framework.Version.fVersion+SystemUtils.LINE_SEPARATOR); } catch (Throwable t) { sb.append("Xerces-Version not found ("+t.getClass().getName()+": "+t.getMessage()+")"+SystemUtils.LINE_SEPARATOR); } try { sb.append("Xalan-version="+org.apache.xalan.Version.getVersion()+SystemUtils.LINE_SEPARATOR); } catch (Throwable t) { sb.append("Xalan-Version not found ("+t.getClass().getName()+": "+t.getMessage()+")"+SystemUtils.LINE_SEPARATOR); } try { // sb.append("XmlCommons-Version="+org.apache.xmlcommons.Version.getVersion()+SystemUtils.LINE_SEPARATOR); } catch (Throwable t) { sb.append("XmlCommons-Version not found ("+t.getClass().getName()+": "+t.getMessage()+")"+SystemUtils.LINE_SEPARATOR); } return sb.toString(); } }
package org.joda.time; import java.io.Serializable; import java.util.Locale; import org.joda.time.base.BaseDateTime; import org.joda.time.chrono.ISOChronology; import org.joda.time.field.AbstractReadableInstantFieldProperty; import org.joda.time.field.FieldUtils; import org.joda.time.format.ISODateTimeFormat; /** * MutableDateTime is the standard implementation of a modifiable datetime class. * It holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. * <p> * This class uses a Chronology internally. The Chronology determines how the * millisecond instant value is converted into the date time fields. * The default Chronology is <code>ISOChronology</code> which is the agreed * international standard and compatable with the modern Gregorian calendar. * <p> * Each individual field can be accessed in two ways: * <ul> * <li><code>getHourOfDay()</code> * <li><code>hourOfDay().get()</code> * </ul> * The second technique also provides access to other useful methods on the * field: * <ul> * <li>get numeric value * <li>set numeric value * <li>add to numeric value * <li>add to numeric value wrapping with the field * <li>get text vlaue * <li>get short text value * <li>set text value * <li>field maximum value * <li>field minimum value * </ul> * * <p> * MutableDateTime is mutable and not thread-safe, unless concurrent threads * are not invoking mutator methods. * * @author Guy Allard * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 * @see DateTime */ public class MutableDateTime extends BaseDateTime implements ReadWritableDateTime, Cloneable, Serializable { /** Serialization version */ private static final long serialVersionUID = 2852608688135209575L; /** Rounding is disabled */ public static final int ROUND_NONE = 0; /** Rounding mode as described by {@link DateTimeField#roundFloor} */ public static final int ROUND_FLOOR = 1; /** Rounding mode as described by {@link DateTimeField#roundCeiling} */ public static final int ROUND_CEILING = 2; /** Rounding mode as described by {@link DateTimeField#roundHalfFloor} */ public static final int ROUND_HALF_FLOOR = 3; /** Rounding mode as described by {@link DateTimeField#roundHalfCeiling} */ public static final int ROUND_HALF_CEILING = 4; /** Rounding mode as described by {@link DateTimeField#roundHalfEven} */ public static final int ROUND_HALF_EVEN = 5; /** The field to round on */ private DateTimeField iRoundingField; /** The mode of rounding */ private int iRoundingMode; /** * Constructs an instance set to the current system millisecond time * using <code>ISOChronology</code> in the default time zone. */ public MutableDateTime() { super(); } /** * Constructs an instance set to the current system millisecond time * using <code>ISOChronology</code> in the specified time zone. * <p> * If the specified time zone is null, the default zone is used. * * @param zone the time zone, null means default zone */ public MutableDateTime(DateTimeZone zone) { super(zone); } /** * Constructs an instance set to the current system millisecond time * using the specified chronology. * <p> * If the chronology is null, <code>ISOChronology</code> * in the default time zone is used. * * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime(Chronology chronology) { super(chronology); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using <code>ISOChronology</code> in the default time zone. * * @param instant the milliseconds from 1970-01-01T00:00:00Z */ public MutableDateTime(long instant) { super(instant); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using <code>ISOChronology</code> in the specified time zone. * <p> * If the specified time zone is null, the default zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param zone the time zone, null means default zone */ public MutableDateTime(long instant, DateTimeZone zone) { super(instant, zone); } /** * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z * using the specified chronology. * <p> * If the chronology is null, <code>ISOChronology</code> * in the default time zone is used. * * @param instant the milliseconds from 1970-01-01T00:00:00Z * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime(long instant, Chronology chronology) { super(instant, chronology); } public MutableDateTime(Object instant) { super(instant); } public MutableDateTime(Object instant, DateTimeZone zone) { super(instant, zone); } public MutableDateTime(Object instant, Chronology chronology) { super(instant, chronology); } /** * Constructs an instance from datetime field values * using <code>ISOChronology</code> in the default time zone. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } /** * Constructs an instance from datetime field values * using <code>ISOChronology</code> in the specified time zone. * <p> * If the specified time zone is null, the default zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param zone the time zone, null means default time zone */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, DateTimeZone zone) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, zone); } /** * Constructs an instance from datetime field values * using the specified chronology. * <p> * If the chronology is null, <code>ISOChronology</code> * in the default time zone is used. * * @param year the year * @param monthOfYear the month of the year * @param dayOfMonth the day of the month * @param hourOfDay the hour of the day * @param minuteOfHour the minute of the hour * @param secondOfMinute the second of the minute * @param millisOfSecond the millisecond of the second * @param chronology the chronology, null means ISOChronology in default zone */ public MutableDateTime( int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, Chronology chronology) { super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, chronology); } /** * Gets the field used for rounding this instant, returning null if rounding * is not enabled. * * @return the rounding field */ public DateTimeField getRoundingField() { return iRoundingField; } /** * Gets the rounding mode for this instant, returning ROUND_NONE if rounding * is not enabled. * * @return the rounding mode constant */ public int getRoundingMode() { return iRoundingMode; } /** * Sets the status of rounding to use the specified field and ROUND_FLOOR mode. * A null field will disable rounding. * Once set, the instant is then rounded using the new field and mode. * <p> * Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} * to be rounded. This can be used to control the precision of the instant, * for example by setting a rounding field of minuteOfDay, the seconds and * milliseconds will always be zero. * * @param field rounding field or null to disable */ public void setRounding(DateTimeField field) { setRounding(field, MutableDateTime.ROUND_FLOOR); } public void setRounding(DateTimeField field, int mode) { if (field != null && (mode < ROUND_NONE || mode > ROUND_HALF_EVEN)) { throw new IllegalArgumentException("Illegal rounding mode: " + mode); } iRoundingField = (mode == ROUND_NONE ? null : field); iRoundingMode = (field == null ? ROUND_NONE : mode); setMillis(getMillis()); } /** * Set the milliseconds of the datetime. * <p> * All changes to the millisecond field occurs via this method. * * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the * datetime to */ public void setMillis(long instant) { switch (iRoundingMode) { case ROUND_NONE: break; case ROUND_FLOOR: instant = iRoundingField.roundFloor(instant); break; case ROUND_CEILING: instant = iRoundingField.roundCeiling(instant); break; case ROUND_HALF_FLOOR: instant = iRoundingField.roundHalfFloor(instant); break; case ROUND_HALF_CEILING: instant = iRoundingField.roundHalfCeiling(instant); break; case ROUND_HALF_EVEN: instant = iRoundingField.roundHalfEven(instant); break; } super.setMillis(instant); } /** * Sets the millisecond instant of this instant from another. * <p> * This method does not change the chronology of this instant, just the * millisecond instant. * * @param instant the instant to use, null means now */ public void setMillis(ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); setMillis(instantMillis); // set via this class not super } /** * Add an amount of time to the datetime. * * @param duration the millis to add * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(long duration) { setMillis(FieldUtils.safeAdd(getMillis(), duration)); // set via this class not super } /** * Adds a duration to this instant. * <p> * This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadableDuration duration) { add(duration, 1); } /** * Adds a duration to this instant specifying how many times to add. * <p> * This will typically change the value of most fields. * * @param duration the duration to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadableDuration duration, int scalar) { if (duration != null) { add(FieldUtils.safeMultiply(duration.getMillis(), scalar)); } } /** * Adds a period to this instant. * <p> * This will typically change the value of most fields. * * @param period the period to add, null means add zero * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadablePeriod period) { add(period, 1); } /** * Adds a period to this instant specifying how many times to add. * <p> * This will typically change the value of most fields. * * @param period the period to add, null means add zero * @param scalar direction and amount to add, which may be negative * @throws ArithmeticException if the result exceeds the capacity of the instant */ public void add(ReadablePeriod period, int scalar) { if (period != null) { setMillis(period.addTo(getMillis(), scalar)); // set via this class not super } } /** * Set the chronology of the datetime. * <p> * All changes to the chronology occur via this method. * * @param chronology the chronology to use, null means ISOChronology in default zone */ public void setChronology(Chronology chronology) { super.setChronology(chronology); } /** * Sets the time zone of the datetime, changing the chronology and field values. * <p> * Changing the zone using this method retains the millisecond instant. * The millisecond instant is adjusted in the new zone to compensate. * * chronology. Setting the time zone does not affect the millisecond value * of this instant. * <p> * If the chronology already has this time zone, no change occurs. * * @param newZone the time zone to use, null means default zone * @see #setZoneRetainFields */ public void setZone(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); Chronology chrono = getChronology(); if (chrono.getZone() != newZone) { setChronology(chrono.withZone(newZone)); // set via this class not super } } /** * Sets the time zone of the datetime, changing the chronology and millisecond. * <p> * Changing the zone using this method retains the field values. * The millisecond instant is adjusted in the new zone to compensate. * <p> * If the chronology already has this time zone, no change occurs. * * @param newZone the time zone to use, null means default zone * @see #setZone */ public void setZoneRetainFields(DateTimeZone newZone) { newZone = DateTimeUtils.getZone(newZone); DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); if (newZone == originalZone) { return; } long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); setChronology(getChronology().withZone(newZone)); // set via this class not super setMillis(millis); } public void set(final DateTimeField field, final int value) { if (field == null) { throw new IllegalArgumentException("The DateTimeField must not be null"); } setMillis(field.set(getMillis(), value)); } public void add(final DurationField field, final int value) { if (field == null) { throw new IllegalArgumentException("The DurationField must not be null"); } setMillis(field.add(getMillis(), value)); } public void setYear(final int year) { setMillis(getChronology().year().set(getMillis(), year)); } public void addYears(final int years) { setMillis(getChronology().years().add(getMillis(), years)); } public void setWeekyear(final int weekyear) { setMillis(getChronology().weekyear().set(getMillis(), weekyear)); } public void addWeekyears(final int weekyears) { setMillis(getChronology().weekyears().add(getMillis(), weekyears)); } public void setMonthOfYear(final int monthOfYear) { setMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); } public void addMonths(final int months) { setMillis(getChronology().months().add(getMillis(), months)); } public void setWeekOfWeekyear(final int weekOfWeekyear) { setMillis(getChronology().weekOfWeekyear().set(getMillis(), weekOfWeekyear)); } public void addWeeks(final int weeks) { setMillis(getChronology().weeks().add(getMillis(), weeks)); } public void setDayOfYear(final int dayOfYear) { setMillis(getChronology().dayOfYear().set(getMillis(), dayOfYear)); } public void setDayOfMonth(final int dayOfMonth) { setMillis(getChronology().dayOfMonth().set(getMillis(), dayOfMonth)); } public void setDayOfWeek(final int dayOfWeek) { setMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); } public void addDays(final int days) { setMillis(getChronology().days().add(getMillis(), days)); } public void setHourOfDay(final int hourOfDay) { setMillis(getChronology().hourOfDay().set(getMillis(), hourOfDay)); } public void addHours(final int hours) { setMillis(getChronology().hours().add(getMillis(), hours)); } public void setMinuteOfDay(final int minuteOfDay) { setMillis(getChronology().minuteOfDay().set(getMillis(), minuteOfDay)); } public void setMinuteOfHour(final int minuteOfHour) { setMillis(getChronology().minuteOfHour().set(getMillis(), minuteOfHour)); } public void addMinutes(final int minutes) { setMillis(getChronology().minutes().add(getMillis(), minutes)); } public void setSecondOfDay(final int secondOfDay) { setMillis(getChronology().secondOfDay().set(getMillis(), secondOfDay)); } public void setSecondOfMinute(final int secondOfMinute) { setMillis(getChronology().secondOfMinute().set(getMillis(), secondOfMinute)); } public void addSeconds(final int seconds) { setMillis(getChronology().seconds().add(getMillis(), seconds)); } public void setMillisOfDay(final int millisOfDay) { setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); } public void setMillisOfSecond(final int millisOfSecond) { setMillis(getChronology().millisOfSecond().set(getMillis(), millisOfSecond)); } public void addMillis(final int millis) { setMillis(getChronology().millis().add(getMillis(), millis)); } public void setDate(final long instant) { setMillis(getChronology().millisOfDay().set(instant, getMillisOfDay())); } public void setDate(final ReadableInstant instant) { // TODO: Does time zone need to be considered? See setTime(ReadableInstant) long instantMillis = DateTimeUtils.getInstantMillis(instant); setDate(instantMillis); } public void setDate( final int year, final int monthOfYear, final int dayOfMonth) { Chronology c = getChronology(); long instantMidnight = c.getDateTimeMillis(year, monthOfYear, dayOfMonth, 0); setDate(instantMidnight); } public void setTime(final long millis) { int millisOfDay = ISOChronology.getInstanceUTC().millisOfDay().get(millis); setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); } public void setTime(final ReadableInstant instant) { long instantMillis = DateTimeUtils.getInstantMillis(instant); Chronology instantChrono = DateTimeUtils.getInstantChronology(instant); DateTimeZone zone = instantChrono.getZone(); if (zone != null) { instantMillis = zone.getMillisKeepLocal(DateTimeZone.UTC, instantMillis); } setTime(instantMillis); } public void setTime( final int hour, final int minuteOfHour, final int secondOfMinute, final int millisOfSecond) { long instant = getChronology().getDateTimeMillis( getMillis(), hour, minuteOfHour, secondOfMinute, millisOfSecond); setMillis(instant); } public void setDateTime( final int year, final int monthOfYear, final int dayOfMonth, final int hourOfDay, final int minuteOfHour, final int secondOfMinute, final int millisOfSecond) { long instant = getChronology().getDateTimeMillis( year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); setMillis(instant); } /** * Get the era property. * * @return the era property */ public Property era() { return new Property(this, getChronology().era()); } /** * Get the century of era property. * * @return the year of era property */ public Property centuryOfEra() { return new Property(this, getChronology().centuryOfEra()); } /** * Get the year of century property. * * @return the year of era property */ public Property yearOfCentury() { return new Property(this, getChronology().yearOfCentury()); } /** * Get the year of era property. * * @return the year of era property */ public Property yearOfEra() { return new Property(this, getChronology().yearOfEra()); } /** * Get the year property. * * @return the year property */ public Property year() { return new Property(this, getChronology().year()); } /** * Get the year of a week based year property. * * @return the year of a week based year property */ public Property weekyear() { return new Property(this, getChronology().weekyear()); } /** * Get the month of year property. * * @return the month of year property */ public Property monthOfYear() { return new Property(this, getChronology().monthOfYear()); } /** * Get the week of a week based year property. * * @return the week of a week based year property */ public Property weekOfWeekyear() { return new Property(this, getChronology().weekOfWeekyear()); } /** * Get the day of year property. * * @return the day of year property */ public Property dayOfYear() { return new Property(this, getChronology().dayOfYear()); } /** * Get the day of month property. * <p> * The values for day of month are defined in {@link DateTimeConstants}. * * @return the day of month property */ public Property dayOfMonth() { return new Property(this, getChronology().dayOfMonth()); } /** * Get the day of week property. * <p> * The values for day of week are defined in {@link DateTimeConstants}. * * @return the day of week property */ public Property dayOfWeek() { return new Property(this, getChronology().dayOfWeek()); } /** * Get the hour of day field property * * @return the hour of day property */ public Property hourOfDay() { return new Property(this, getChronology().hourOfDay()); } /** * Get the minute of day property * * @return the minute of day property */ public Property minuteOfDay() { return new Property(this, getChronology().minuteOfDay()); } /** * Get the minute of hour field property * * @return the minute of hour property */ public Property minuteOfHour() { return new Property(this, getChronology().minuteOfHour()); } /** * Get the second of day property * * @return the second of day property */ public Property secondOfDay() { return new Property(this, getChronology().secondOfDay()); } /** * Get the second of minute field property * * @return the second of minute property */ public Property secondOfMinute() { return new Property(this, getChronology().secondOfMinute()); } /** * Get the millis of day property * * @return the millis of day property */ public Property millisOfDay() { return new Property(this, getChronology().millisOfDay()); } /** * Get the millis of second property * * @return the millis of second property */ public Property millisOfSecond() { return new Property(this, getChronology().millisOfSecond()); } /** * Clone this object without having to cast the returned object. * * @return a clone of the this object. */ public MutableDateTime copy() { return (MutableDateTime)clone(); } /** * Clone this object. * * @return a clone of this object. */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError("Clone error"); } } /** * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZ). * * @return ISO8601 time formatted string. */ public String toString() { return ISODateTimeFormat.getInstance(getChronology()).dateTime().print(this); } /** * MutableDateTime.Property binds a MutableDateTime to a * DateTimeField allowing powerful datetime functionality to be easily * accessed. * <p> * The example below shows how to use the property to change the value of a * MutableDateTime object. * <pre> * MutableDateTime dt = new MutableDateTime(1972, 12, 3, 13, 32, 19, 123); * dt.year().add(20); * dt.second().roundFloor().minute().set(10); * </pre> * <p> * MutableDateTime.Propery itself is thread-safe and immutable, but the * MutableDateTime being operated on is not. * * @author Stephen Colebourne * @author Brian S O'Neill * @since 1.0 */ public static final class Property extends AbstractReadableInstantFieldProperty { /** Serialization version */ private static final long serialVersionUID = -4481126543819298617L; /** The instant this property is working against */ private final MutableDateTime iInstant; /** The field this property is working against */ private final DateTimeField iField; /** * Constructor. * * @param instant the instant to set * @param field the field to use */ Property(MutableDateTime instant, DateTimeField field) { super(); iInstant = instant; iField = field; } /** * Gets the field being used. * * @return the field */ public DateTimeField getField() { return iField; } /** * Gets the instant being used. * * @return the instant */ public ReadableInstant getReadableInstant() { return iInstant; } /** * Gets the mutable datetime being used. * * @return the mutable datetime */ public MutableDateTime getMutableDateTime() { return iInstant; } /** * Adds a value to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#add(long,int) */ public MutableDateTime add(int value) { iInstant.setMillis(getField().add(iInstant.getMillis(), value)); return iInstant; } /** * Adds a value to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#add(long,long) */ public MutableDateTime add(long value) { iInstant.setMillis(getField().add(iInstant.getMillis(), value)); return iInstant; } /** * Adds a value, possibly wrapped, to the millis value. * * @param value the value to add * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#addWrapField */ public MutableDateTime addWrapField(int value) { iInstant.setMillis(getField().addWrapField(iInstant.getMillis(), value)); return iInstant; } /** * Sets a value. * * @param value the value to set. * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#set(long,int) */ public MutableDateTime set(int value) { iInstant.setMillis(getField().set(iInstant.getMillis(), value)); return iInstant; } public MutableDateTime set(String text, Locale locale) { iInstant.setMillis(getField().set(iInstant.getMillis(), text, locale)); return iInstant; } public MutableDateTime set(String text) { set(text, null); return iInstant; } /** * Round to the lowest whole unit of this field. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundFloor */ public MutableDateTime roundFloor() { iInstant.setMillis(getField().roundFloor(iInstant.getMillis())); return iInstant; } /** * Round to the highest whole unit of this field. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundCeiling */ public MutableDateTime roundCeiling() { iInstant.setMillis(getField().roundCeiling(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field, favoring the floor if * halfway. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfFloor */ public MutableDateTime roundHalfFloor() { iInstant.setMillis(getField().roundHalfFloor(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field, favoring the ceiling if * halfway. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfCeiling */ public MutableDateTime roundHalfCeiling() { iInstant.setMillis(getField().roundHalfCeiling(iInstant.getMillis())); return iInstant; } /** * Round to the nearest whole unit of this field. If halfway, the ceiling * is favored over the floor only if it makes this field's value even. * * @return the mutable datetime being used, so calls can be chained * @see DateTimeField#roundHalfEven */ public MutableDateTime roundHalfEven() { iInstant.setMillis(getField().roundHalfEven(iInstant.getMillis())); return iInstant; } } }
package be.italent.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) @Entity public class Project extends AbstractITalentEntity implements Serializable { private static final long serialVersionUID = 4300509934424545336L; @Transient private boolean liked; @Id @GeneratedValue @Column(name="project_id") private int projectId; @Size(min=2, max=100) private String title; @Size(max=2000) @Lob private String description; @Size(max=200) @Column(name="short_description") private String shortDescription; @Temporal(TemporalType.TIMESTAMP) @Column(name="creation_date") private Date creationDate; @OneToOne private User user; //minutes @Column(name="duration_in_minutes") private int durationInMinutes; @Temporal(TemporalType.TIMESTAMP) @Column(name="start_date") private Date startDate; @JsonIgnore @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name = "project_category", joinColumns = { @JoinColumn(name = "project_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "category_id", nullable = false, updatable = false) }) private List<Category> categories = new ArrayList<Category>(); @OneToOne private Domain domain; @Column(name="backing_pct") private int backingPct; @Column(name="is_public") private boolean isPublic; @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JsonIgnore private List<Like> likes = new ArrayList<Like>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<Milestone> milestones = new ArrayList<Milestone>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<Movie> movies = new ArrayList<Movie>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<Picture> pictures = new ArrayList<Picture>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<WantedSubscriber> wantedSubscribers = new ArrayList<WantedSubscriber>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<SubscriberStudent> subscribersStudent = new ArrayList<SubscriberStudent>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<SubscriberDocent> subscribersDocent = new ArrayList<SubscriberDocent>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<Prezi> prezis = new ArrayList<Prezi>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<OnlineFile> onlineFiles = new ArrayList<OnlineFile>(); @OneToMany(mappedBy="project", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true) private List<Comment> Comments = new ArrayList<Comment>(); @Transient private int numberOfLikes; public int getNumberOfLikes(){ return likes.size(); } public void updateBackingPct(){ int total = 0; for (int i = 0; i < this.subscribersDocent.size(); i++) { total += this.subscribersDocent.get(i).getBackingPct(); } this.backingPct = total; } @Transient private int wantedSeats; public int getWantedSeats(){ this.wantedSeats = 0; for (int i = 0; i < this.getWantedSubscribers().size(); i++) { this.wantedSeats += this.getWantedSubscribers().get(i).getNumber(); } return this.wantedSeats; } @Transient private int takenSeats; public int getTakenSeats(){ this.takenSeats = 0; for (int i = 0; i < this.getSubscribersStudent().size(); i++) { this.takenSeats += 1; } return this.takenSeats; } @Transient private boolean canSubscribe = false; @JsonIgnore public void setCanSubscribe(int currentUserId, int departmentId){ if (this.getWantedSeats()>this.getTakenSeats()){ // Check amount asked in user department int wantedInMyDepartment = 0; for (WantedSubscriber wantedSubscriber : this.getWantedSubscribers()) { if(wantedSubscriber.getDepartment().getDepartmentId() == departmentId){ wantedInMyDepartment = wantedSubscriber.getNumber(); break; } } if(wantedInMyDepartment == 0){ return; } int alreadyEnrolledInMyDepartment = 0; for(SubscriberStudent subscriberStudent : this.getSubscribersStudent()){ if(subscriberStudent.getUser().getDepartment().getDepartmentId() == departmentId){ //check if user is already subscribed if (subscriberStudent.getUser().getUserId() == currentUserId){ return; } alreadyEnrolledInMyDepartment++; } } if(wantedInMyDepartment > alreadyEnrolledInMyDepartment){ this.setCanSubscribe(true); } } else{ return; } } @Transient private boolean canBack = false; @JsonIgnore public void setCanBack(int currentUserId){ if (this.getBackingPct()>99){ return; } for(SubscriberDocent subscriberDocent : this.getSubscribersDocent()){ //check if docent is already backing if(subscriberDocent.getUser().getUserId() == currentUserId){ return; } } this.canBack = true; } //TODO remove /*@Column(name="is_backed") private boolean isBacked; public boolean isBacked() { int total = 0; for(SubscriberDocent s : subscribersDocent){ total += s.getBackingPct(); } return total > 99; }*/ @JsonIgnore public void setLiked(int currentUserId) { this.liked = false; for (Like l : this.getLikes()) { if(l.getUser().getUserId() == currentUserId){ this.liked = true; break; } } } }
import java.util.ArrayList; public class PathSumTwo { public static void main(String[] args) { // TODO Auto-generated method stub // 4 15 TreeNode root=new TreeNode(5); root.left=new TreeNode(4); root.right=new TreeNode(15); root.left.left=new TreeNode(11); System.out.println(pathSumTwo(root, 20)); } public static class TreeNode{ int val; TreeNode left,right; public TreeNode(int val) { // TODO Auto-generated constructor stub this.val=val; left=null; right=null; } } public static ArrayList<ArrayList <Integer>> pathSumTwo(TreeNode root,int sum){ ArrayList<ArrayList <Integer>> result=new ArrayList<ArrayList<Integer>>(); if(root==null){ return result; } ArrayList<Integer> l=new ArrayList<>(); l.add(root.val); dfs(root, sum-root.val, result, l); return result; } public static void dfs(TreeNode root,int sum,ArrayList<ArrayList<Integer>> result,ArrayList<Integer> l) { if(root.left==null && root.right==null && sum==0){ ArrayList<Integer> temp=new ArrayList<>(); temp.addAll(l); result.add(temp); } if(root.left!=null){ l.add(root.left.val); dfs(root.left, sum-root.left.val, result, l); l.remove(l.size()-1); } if(root.right!=null){ l.add(root.right.val); dfs(root.right, sum-root.right.val, result, l); l.add(l.size()-1); } } }
package mswindow; import mslogic.Logger; import mslogic.MS_Game; import mslogic.MS_Map; import mslogic.MS_Square; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.File; public class MS_Panel extends JPanel implements MouseListener, MouseMotionListener, Runnable { private static final int GUIEXTRAHEIGHT = 130; private static boolean showAll = false; public boolean mouseDown = false; int numColsP, numRowsP, columnP = -1, rowP = -1; Image digitEmpty, dead, oh, down, happy, happyDown, shades, digitNine, digitEight, digitSeven, digitSix, digitFive, digitFour, digitThree, digitHyphen, digitTwo, digitOne, digitZero, eight, seven, six, five, four, three, two, one, empty, unclicked, flag, question, mine, incorrectFlag, exploded; private int faceX, faceY; private MS_Game game; private boolean faceClicked = false; public MS_Panel(int numCols, int numRows, int numMines) { setSize(numCols * 16, numRows * 16 + GUIEXTRAHEIGHT); this.numColsP = numCols; this.numRowsP = numRows; game = new MS_Game(numRows, numCols, numMines); game.setState(MS_Game.NOT_STARTED); //determines place of face faceX = (getWidth() / 2) - 11; faceY = (GUIEXTRAHEIGHT / 2) - 10; try { dead = ImageIO.read((new File("resource/Dead.png"))); oh = ImageIO.read((new File("resource/Oh.png"))); down = ImageIO.read((new File("resource/Down.png"))); happy = ImageIO.read((new File("resource/Happy.png"))); happyDown = ImageIO.read((new File("resource/Happy_Down.png"))); shades = ImageIO.read((new File("resource/Shades.png"))); digitNine = ImageIO.read((new File("resource/Digit_Nine.png"))); digitEmpty = ImageIO.read((new File("resource/Digit_Empty.png"))); digitEight = ImageIO.read((new File("resource/Digit_Eight.png"))); digitSeven = ImageIO.read((new File("resource/Digit_Seven.png"))); digitSix = ImageIO.read((new File("resource/Digit_Six.png"))); digitFive = ImageIO.read((new File("resource/Digit_Five.png"))); digitFour = ImageIO.read((new File("resource/Digit_Four.png"))); digitThree = ImageIO.read((new File("resource/Digit_Three.png"))); digitHyphen = ImageIO.read((new File("resource/Digit_Hyphen.png"))); digitTwo = ImageIO.read((new File("resource/Digit_Two.png"))); digitOne = ImageIO.read((new File("resource/Digit_One.png"))); digitZero = ImageIO.read((new File("resource/Digit_Zero.png"))); eight = ImageIO.read((new File("resource/Eight.png"))); seven = ImageIO.read((new File("resource/Seven.png"))); six = ImageIO.read((new File("resource/Six.png"))); five = ImageIO.read((new File("resource/Five.png"))); four = ImageIO.read((new File("resource/Four.png"))); three = ImageIO.read((new File("resource/Three.png"))); two = ImageIO.read((new File("resource/Two.png"))); one = ImageIO.read((new File("resource/One.png"))); empty = ImageIO.read((new File("resource/Empty.png"))); unclicked = ImageIO.read((new File("resource/Unclicked.png"))); flag = ImageIO.read((new File("resource/Flag.png"))); question = ImageIO.read((new File("resource/Question.png"))); mine = ImageIO.read((new File("resource/Mine.png"))); incorrectFlag = ImageIO.read((new File("resource/IncorrectFlag.png"))); exploded = ImageIO.read((new File("resource/Exploded.png"))); Logger.logOtherMessage("ImageLoader", "Succeeded."); } catch (Exception e) { System.err.println("Error Loading Images: " + e.getMessage()); Logger.logErrorMessage("Error with loading images. Exiting..."); System.exit(-1); //if loading fails, end the program. } addMouseListener(this); addMouseMotionListener(this); } /** * Method to get the column of the provided x. * * @param e used for getting x. * @return the column clicked. */ public static int getColumnOffCoord(MouseEvent e) { return (e.getX()) / 16; } /** * Method to get the row of a coord. * * @param e used for getting y. * @return the row clicked. */ public static int getRowOffCoord(MouseEvent e) { return (e.getY() - GUIEXTRAHEIGHT) / 16; } public void run() { //noinspection InfiniteLoopStatement while (true) { paint(this.getGraphics()); try { Thread.sleep(35); } catch (Exception e) { System.err.println("Error Sleeping."); Logger.logErrorMessage("Error Sleeping Thread."); } } } public void paint(Graphics g) { long time = game.getSeconds(game.getStartTime()); //paint game g.setColor(Color.WHITE); g.drawRect(0, 0, getWidth(), GUIEXTRAHEIGHT); //draw the face in the gui switch (game.getState()) { case MS_Game.LOSE: g.drawImage(dead, faceX, faceY, null); break; case MS_Game.WIN: g.drawImage(shades, faceX, faceY, null); break; case MS_Game.NOT_STARTED: g.drawImage(oh, faceX, faceY, null); break; default: g.drawImage(happy, faceX, faceY, null); break; } showNumbers(g, time); showFlagNumbers(g); for (int r = 0; r < game.getNumRowsG(); r++) { for (int c = 0; c < game.getNumColsG(); c++) { MS_Map m = game.getMap(); if (r == rowP && c == columnP && m.getSquare(c, r).getState() == MS_Square.UP) { //draw the square being clicked as down g.drawImage(down, c * 16, r * 16 + GUIEXTRAHEIGHT, null); } else { //noinspection ConstantConditions,PointlessBooleanExpression if (m.getSquare(c, r).getState() == MS_Square.UP && !showAll) { g.drawImage(unclicked, c * 16, r * 16 + GUIEXTRAHEIGHT, null); } else if (m.getSquare(c, r).getState() == MS_Square.FLAG) { g.drawImage(flag, c * 16, r * 16 + GUIEXTRAHEIGHT, null); } else if (m.getSquare(c, r).getState() == MS_Square.QUESTION) { g.drawImage(question, c * 16, r * 16 + GUIEXTRAHEIGHT, null); } else if (m.getSquare(c, r).isMine()) { if (game.getState() == MS_Game.LOSE) g.drawImage(exploded, c * 16, r * 16 + GUIEXTRAHEIGHT, null); else g.drawImage(mine, c * 16, r * 16 + GUIEXTRAHEIGHT, null); } else { switch (m.getSquare(c, r).getNumber()) { case 1: g.drawImage(one, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 2: g.drawImage(two, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 3: g.drawImage(three, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 4: g.drawImage(four, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 5: g.drawImage(five, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 6: g.drawImage(six, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 7: g.drawImage(seven, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; case 8: g.drawImage(eight, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; default: g.drawImage(empty, c * 16, r * 16 + GUIEXTRAHEIGHT, null); break; } } } } } } public void addNotify() { super.addNotify(); Thread a = new Thread(this); a.start(); Logger.logCodeMessage("Thread Created Successfully."); } public void mousePressed(MouseEvent e) { if (game.getState() == MS_Game.NOT_STARTED && (e.getX() >= faceX && e.getX() <= faceX + 16) && (e.getY() >= faceY && e.getY() <= faceY + 16) && e.getButton() == MouseEvent.BUTTON1) { game.setState(MS_Game.PLAYING); faceClicked = true; Logger.logCodeMessage("Starting Game."); } else if (game.getState() == MS_Game.LOSE && (e.getX() >= faceX && e.getX() <= faceX + 16) && (e.getY() >= faceY && e.getY() <= faceY + 16) && e.getButton() == MouseEvent.BUTTON1) { game.setState(MS_Game.PLAYING); faceClicked = true; Logger.logCodeMessage("Restarting Game, after a loss."); } else if (game.getState() == MS_Game.WIN && (e.getX() >= faceX && e.getX() <= faceX + 16) && (e.getY() >= faceY && e.getY() <= faceY + 16) && e.getButton() == MouseEvent.BUTTON1) { game.setState(MS_Game.PLAYING); faceClicked = true; Logger.logCodeMessage("Restarting Game, after a win."); } if (game.getState() == MS_Game.LOSE || game.getState() == MS_Game.NOT_STARTED || game.getState() == MS_Game.WIN || !faceClicked) { //do nothing Logger.logUserMessage("Disallowing clicking as game is over/not started."); } else if (e.getButton() == MouseEvent.BUTTON1) { mouseDown = true; columnP = getColumnOffCoord(e); rowP = getRowOffCoord(e); System.out.println("User Pressed the mouse at " + e.getX() + "," + e.getY() + " at col " + columnP + "," + rowP); Logger.logUserMessage("Pressed the mouse at " + e.getX() + "," + e.getY() + " at col " + columnP + "," + rowP); } } public void mouseReleased(MouseEvent e) { if (game.getState() == MS_Game.LOSE || game.getState() == MS_Game.NOT_STARTED || game.getState() == MS_Game.WIN || !faceClicked) { //do nothing } else if (e.getButton() == MouseEvent.BUTTON1) { int columnR = getColumnOffCoord(e), rowR = getRowOffCoord(e); System.out.println("User Released the mouse at " + e.getX() + "," + e.getY() + " at col " + columnR + "," + rowR); Logger.logUserMessage("Released the mouse at " + e.getX() + "," + e.getY() + " at col " + columnR + "," + rowR); game.reveal(columnR, rowR); //call reveal to start revealing squares if (game.getMap().getSquare(columnR, rowR).isMine()) { //if they clicked on a mine game.setState(MS_Game.LOSE); showAll = true; Logger.logUserMessage("User has lost."); faceClicked = false; } } else if (e.getButton() == MouseEvent.BUTTON3) { if (game.getMap().getSquare(getColumnOffCoord(e), getRowOffCoord(e)).getState() == MS_Square.UP) game.getMap().getSquare(getColumnOffCoord(e), getRowOffCoord(e)).setState(MS_Square.FLAG); else if (game.getMap().getSquare(getColumnOffCoord(e), getRowOffCoord(e)).getState() == MS_Square.FLAG) { game.getMap().getSquare(getColumnOffCoord(e), getRowOffCoord(e)).setState(MS_Square.QUESTION); } else if (game.getMap().getSquare(getColumnOffCoord(e), getRowOffCoord(e)).getState() == MS_Square.QUESTION) { game.getMap().getSquare(getColumnOffCoord(e), getRowOffCoord(e)).setState(MS_Square.UP); } } } @Deprecated public void mouseClicked(MouseEvent e) { //not used } @Deprecated public void mouseEntered(MouseEvent e) { //unused } @Deprecated public void mouseExited(MouseEvent e) { //unused } @Deprecated public void mouseMoved(MouseEvent e) { //unused } public void mouseDragged(MouseEvent e) { if (game.getState() == MS_Game.LOSE || game.getState() == MS_Game.NOT_STARTED || game.getState() == MS_Game.WIN || !faceClicked) { //do nothing } else if (e.getButton() == MouseEvent.BUTTON1) { mouseDown = true; columnP = getColumnOffCoord(e); rowP = getRowOffCoord(e); } } /** * Analyses the provided square for what image to display. * * @param s an MS_Square to analyse. * @return the image to be displayed for the square. */ public Image getSquare(MS_Square s) { //get square image if (s.getState() == MS_Square.FLAG) return flag; else if (s.getState() == MS_Square.QUESTION) return question; else if (s.getState() == MS_Square.UP) return unclicked; else if (s.getState() == MS_Square.SHOWN) { if (s.isMine()) { return mine; } switch (s.getNumber()) { //returns images if the object is a number case 0: return empty; case 1: return one; case 2: return two; case 3: return three; case 4: return four; case 5: return five; case 6: return six; case 7: return seven; case 8: return eight; } } return null; } /** * Method to show the timer. * * @param g Graphics from paint * @param time current game time. */ private void showNumbers(Graphics g, /*love you*/ long time) { int ones = (int) ((time) % 10); int tens = (int) ((time) % 100) / 10; int hundreds = (int) time / 100; switch (ones) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.30), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.30), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.30), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.30), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.30), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.30), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.30), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.30), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.30), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.30), 50, null); } switch (tens) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.20), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.20), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.20), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.20), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.20), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.20), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.20), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.20), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.20), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.20), 50, null); } switch (hundreds) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.10), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.10), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.10), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.10), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.10), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.10), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.10), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.10), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.10), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.10), 50, null); } } /** * Method to show the amount of squares flagged in the gui * * @param g graphics from paint method */ private void showFlagNumbers(Graphics g) { int ones, tens = 0; game.setNumMarked(game.getMineCounter()); int numMarked = game.getNumMarked(); if (numMarked < 0) //if marked is negative { String number = "" + numMarked; char tOnes = number.charAt(1); String tOnes2 = "" + tOnes; ones = Integer.parseInt(tOnes2); switch (ones) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.80), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.80), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.80), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.80), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.80), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.80), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.80), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.80), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.80), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.80), 50, null); } g.drawImage(digitHyphen, (int) (getWidth() * 0.70), 50, null); //draw the negative place } else if (numMarked < 10) { String number = "" + numMarked; char tOnes = number.charAt(0); String tOnes2 = "" + tOnes; ones = Integer.parseInt(tOnes2); switch (ones) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.80), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.80), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.80), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.80), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.80), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.80), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.80), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.80), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.80), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.80), 50, null); } g.drawImage(digitZero, (int) (getWidth() * 0.70), 50, null); //draw the tens place } else { //if above 10 - you gotta do what you gotta do. Int to char, to string, and back to int. such hack String number = "" + numMarked; char tTens = number.charAt(0); char tOnes = number.charAt(1); String tOnes2 = "" + tOnes; String tTens2 = "" + tTens; ones = Integer.parseInt(tOnes2); tens = Integer.parseInt(tTens2); switch (ones) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.80), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.80), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.80), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.80), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.80), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.80), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.80), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.80), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.80), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.80), 50, null); } switch (tens) { case 1: g.drawImage(digitOne, (int) (getWidth() * 0.70), 50, null); break; case 2: g.drawImage(digitTwo, (int) (getWidth() * 0.70), 50, null); break; case 3: g.drawImage(digitThree, (int) (getWidth() * 0.70), 50, null); break; case 4: g.drawImage(digitFour, (int) (getWidth() * 0.70), 50, null); break; case 5: g.drawImage(digitFive, (int) (getWidth() * 0.70), 50, null); break; case 6: g.drawImage(digitSix, (int) (getWidth() * 0.70), 50, null); break; case 7: g.drawImage(digitSeven, (int) (getWidth() * 0.70), 50, null); break; case 8: g.drawImage(digitEight, (int) (getWidth() * 0.70), 50, null); break; case 9: g.drawImage(digitNine, (int) (getWidth() * 0.70), 50, null); break; default: g.drawImage(digitZero, (int) (getWidth() * 0.70), 50, null); } } } private void checkForWin() { //todo check for win } }
package jolie.runtime; import jolie.ExecutionThread; import jolie.State; import jolie.process.TransformationReason; import jolie.runtime.expression.Expression; import jolie.util.Pair; import java.util.Arrays; /** * Represents a variable path, e.g. a.b[3], offering mechanisms for referring to the object pointed * by it. * * @author Fabrizio Montesi */ public class VariablePath implements Expression { public static class EmptyPathLazyHolder { private EmptyPathLazyHolder() {} @SuppressWarnings( "unchecked" ) public static final Pair< Expression, Expression >[] EMPTY_PATH = new Pair[ 0 ]; } private final Pair< Expression, Expression >[] path; // Right Expression may be null public final Pair< Expression, Expression >[] path() { return path; } public boolean isGlobal() { return false; } protected static Pair< Expression, Expression >[] cloneExpressionHelper( Pair< Expression, Expression >[] path, TransformationReason reason ) { @SuppressWarnings( "unchecked" ) Pair< Expression, Expression >[] clonedPath = new Pair[ path.length ]; for( int i = 0; i < path.length; i++ ) { clonedPath[ i ] = new Pair<>( path[ i ].key().cloneExpression( reason ), (path[ i ].value() == null) ? null : path[ i ].value().cloneExpression( reason ) ); } return clonedPath; } public VariablePath copy() { return new VariablePath( Arrays.copyOf( path, path.length ) ); } @Override public Expression cloneExpression( TransformationReason reason ) { Pair< Expression, Expression >[] clonedPath = cloneExpressionHelper( path, reason ); return new VariablePath( clonedPath ); } public final VariablePath containedSubPath( VariablePath otherVarPath ) { if( getRootValue() != otherVarPath.getRootValue() ) return null; // If the other path is shorter than this, it's not a subpath. if( otherVarPath.path.length < path.length ) return null; int i, myIndex, otherIndex; Pair< Expression, Expression > pair, otherPair; Expression expr, otherExpr; for( i = 0; i < path.length; i++ ) { pair = path[ i ]; otherPair = otherVarPath.path[ i ]; // *.element_name is not a subpath of *.other_name if( !pair.key().evaluate().strValue().equals( otherPair.key().evaluate().strValue() ) ) return null; // If element name is equal, check for the same index expr = pair.value(); otherExpr = otherPair.value(); myIndex = (expr == null) ? 0 : expr.evaluate().intValue(); otherIndex = (otherExpr == null) ? 0 : otherExpr.evaluate().intValue(); if( myIndex != otherIndex ) return null; } // Now i represents the beginning of the subpath, we can just copy it from there @SuppressWarnings( "unchecked" ) Pair< Expression, Expression >[] subPath = new Pair[ otherVarPath.path.length - i ]; System.arraycopy( otherVarPath.path, i, subPath, 0, otherVarPath.path.length - i ); /* * for( int k = 0; i < otherVarPath.path.length; i++ ) { subPath[k] = otherVarPath.path[i]; k++; } */ return _createVariablePath( subPath ); } protected VariablePath _createVariablePath( Pair< Expression, Expression >[] path ) { return new VariablePath( path ); } public VariablePath( Pair< Expression, Expression >[] path ) { this.path = path; } protected Value getRootValue() { return ExecutionThread.getState().root(); } public final void undef() { Pair< Expression, Expression > pair; ValueVector currVector; Value currValue = getRootValue(); int index; String keyStr; for( int i = 0; i < path.length; i++ ) { pair = path[ i ]; keyStr = pair.key().evaluate().strValue(); currVector = currValue.children().get( keyStr ); if( currVector == null ) { return; } else if( currVector.size() < 1 ) { currValue.children().remove( keyStr ); return; } if( pair.value() == null ) { if( (i + 1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished currValue.children().remove( keyStr ); } } else { index = pair.value().evaluate().intValue(); if( (i + 1) < path.length ) { if( currVector.size() <= index ) { return; } currValue = currVector.get( index ); } else { if( currVector.size() > index ) { currVector.remove( index ); } } } } } public final Value getValue() { return getValue( getRootValue() ); } public final Value getValue( ValueLink l ) { final State state = ExecutionThread.currentThread().state(); if( state.hasAlias( this, l ) ) { throw buildAliasAccessException().toRuntimeFaultException(); } else { state.putAlias( this, l ); } Value v = getValue(); state.removeAlias( this, l ); return v; } public final Value getValue( Value currValue ) { for( Pair< Expression, Expression > pair : path ) { final String keyStr = pair.key().evaluate().strValue(); currValue = pair.value() == null ? currValue.getFirstChild( keyStr ) : currValue.getChildren( keyStr ).get( pair.value().evaluate().intValue() ); } return currValue; } public final void setValue( Value value ) { Pair< Expression, Expression > pair; ValueVector currVector; Value currValue = getRootValue(); int index; String keyStr; if( path.length == 0 ) { currValue.refCopy( value ); } else { for( int i = 0; i < path.length; i++ ) { pair = path[ i ]; keyStr = pair.key().evaluate().strValue(); currVector = currValue.getChildren( keyStr ); if( pair.value() == null ) { if( (i + 1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished if( currVector.get( 0 ).isUsedInCorrelation() ) { currVector.get( 0 ).refCopy( value ); } else { currVector.set( 0, value ); } } } else { index = pair.value().evaluate().intValue(); if( (i + 1) < path.length ) { currValue = currVector.get( index ); } else { if( currVector.get( index ).isUsedInCorrelation() ) { currVector.get( index ).refCopy( value ); } else { currVector.set( index, value ); } } } } } } public final Value getValueOrNull() { return getValueOrNull( getRootValue() ); } public final Value getValueOrNull( Value currValue ) { for( int i = 0; i < path.length; i++ ) { final Pair< Expression, Expression > pair = path[ i ]; final ValueVector currVector = currValue.children().get( pair.key().evaluate().strValue() ); if( currVector == null ) { return null; } if( pair.value() == null ) { if( (i + 1) < path.length ) { if( currVector.isEmpty() ) { return null; } currValue = currVector.get( 0 ); } else { // We're finished if( currVector.isEmpty() ) { return null; } else { return currVector.get( 0 ); } } } else { final int index = pair.value().evaluate().intValue(); if( currVector.size() <= index ) { return null; } currValue = currVector.get( index ); if( (i + 1) >= path.length ) { return currValue; } } } return currValue; } public final ValueVector getValueVector( ValueVectorLink l ) { final State state = ExecutionThread.currentThread().state(); if( state.hasAlias( this, l ) ) { throw buildAliasAccessException().toRuntimeFaultException(); } else { state.putAlias( this, l ); } ValueVector v = getValueVector(); if( state.hasAlias( this, v ) ) { throw buildAliasAccessException().toRuntimeFaultException(); } state.removeAlias( this, l ); return v; } private FaultException buildAliasAccessException() { String alias = ""; boolean isRoot = true; for( Pair< Expression, Expression > p : path ) { if( isRoot ) { alias += p.key().evaluate().strValue(); isRoot = false; } else { alias += "." + p.key().evaluate().strValue(); } } return new FaultException( "AliasAccessException", "Found a loop when accessing an alias pointing to path: " + alias ); } public final ValueVector getValueVector( Value currValue ) { ValueVector currVector = null; for( int i = 0; i < path.length; i++ ) { final Pair< Expression, Expression > pair = path[ i ]; currVector = currValue.getChildren( pair.key().evaluate().strValue() ); if( (i + 1) < path.length ) { if( pair.value() == null ) { currValue = currVector.get( 0 ); } else { currValue = currVector.get( pair.value().evaluate().intValue() ); } } } return currVector; } public final ValueVector getValueVectorOrNull( Value currValue ) { ValueVector currVector = null; for( int i = 0; i < path.length; i++ ) { final Pair< Expression, Expression > pair = path[ i ]; currVector = currValue.children().get( pair.key().evaluate().strValue() ); if( currVector == null ) { return null; } if( (i + 1) < path.length ) { if( pair.value() == null ) { if( currVector.isEmpty() ) { return null; } currValue = currVector.get( 0 ); } else { final int index = pair.value().evaluate().intValue(); if( currVector.size() <= index ) { return null; } currValue = currVector.get( index ); } } } return currVector; } public final ValueVector getValueVectorOrNull() { return getValueVectorOrNull( getRootValue() ); } public final ValueVector getValueVector() { return getValueVector( getRootValue() ); } public final void makePointer( VariablePath rightPath ) { makePointer( getRootValue(), rightPath ); } public final void makePointer( Value currValue, VariablePath rightPath ) { Pair< Expression, Expression > pair; ValueVector currVector; int index; String keyStr; for( int i = 0; i < path.length; i++ ) { pair = path[ i ]; keyStr = pair.key().evaluate().strValue(); currVector = currValue.getChildren( keyStr ); if( pair.value() == null ) { if( (i + 1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished currValue.children().put( keyStr, ValueVector.createLink( rightPath ) ); } } else { index = pair.value().evaluate().intValue(); if( (i + 1) < path.length ) { currValue = currVector.get( index ); } else { currVector.set( index, Value.createLink( rightPath ) ); } } } } public Object getValueOrValueVector() { Pair< Expression, Expression > pair; ValueVector currVector; Value currValue = getRootValue(); int index; for( int i = 0; i < path.length; i++ ) { pair = path[ i ]; currVector = currValue.getChildren( pair.key().evaluate().strValue() ); if( pair.value() == null ) { if( (i + 1) < path.length ) { currValue = currVector.get( 0 ); } else { // We're finished return currVector; } } else { index = pair.value().evaluate().intValue(); if( (i + 1) < path.length ) { currValue = currVector.get( index ); } else { return currVector.get( index ); } } } return currValue; } public final void deepCopy( VariablePath rightPath ) { Object myObj = getValueOrValueVector(); if( myObj instanceof Value ) { ((Value) myObj).deepCopy( rightPath.getValue() ); } else { ValueVector myVec = (ValueVector) myObj; ValueVector rightVec = rightPath.getValueVector(); for( int i = 0; i < rightVec.size(); i++ ) { myVec.get( i ).deepCopy( rightVec.get( i ) ); } } } @Override public final Value evaluate() { final Value v = getValueOrNull(); return (v == null) ? Value.UNDEFINED_VALUE : v; } }
package org.joverseer.ui.map; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Stroke; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import javax.imageio.ImageIO; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JViewport; import javax.swing.TransferHandler; import javax.swing.event.MouseInputListener; import org.apache.log4j.Logger; import org.joverseer.joApplication; import org.joverseer.domain.Army; import org.joverseer.domain.Artifact; import org.joverseer.domain.Character; import org.joverseer.domain.Combat; import org.joverseer.domain.Encounter; import org.joverseer.domain.NationMessage; import org.joverseer.domain.Note; import org.joverseer.domain.Order; import org.joverseer.domain.PopulationCenter; import org.joverseer.game.Game; import org.joverseer.game.Turn; import org.joverseer.metadata.GameMetadata; import org.joverseer.metadata.domain.Hex; import org.joverseer.metadata.domain.HexSideElementEnum; import org.joverseer.metadata.domain.HexSideEnum; import org.joverseer.metadata.domain.HexTerrainEnum; import org.joverseer.preferences.PreferenceRegistry; import org.joverseer.support.Container; import org.joverseer.support.GameHolder; import org.joverseer.support.movement.MovementDirection; import org.joverseer.support.movement.MovementUtils; import org.joverseer.ui.LifecycleEventsEnum; import org.joverseer.ui.command.ShowCharacterFastStrideRangeCommand; import org.joverseer.ui.command.ShowCharacterLongStrideRangeCommand; import org.joverseer.ui.command.ShowCharacterMovementRangeCommand; import org.joverseer.ui.command.ShowCharacterPathMasteryRangeCommand; import org.joverseer.ui.command.range.ShowFedCavalryArmyRangeCommand; import org.joverseer.ui.command.range.ShowFedInfantryArmyRangeCommand; import org.joverseer.ui.command.range.ShowFedNavyCoastalRangeCommand; import org.joverseer.ui.command.range.ShowFedNavyOpenSeasRangeCommand; import org.joverseer.ui.command.range.ShowUnfedCavalryArmyRangeCommand; import org.joverseer.ui.command.range.ShowUnfedInfantryArmyRangeCommand; import org.joverseer.ui.command.range.ShowUnfedNavyCoastalRangeCommand; import org.joverseer.ui.command.range.ShowUnfedNavyOpenSeasRangeCommand; import org.joverseer.ui.domain.mapEditor.MapEditorOptionsEnum; import org.joverseer.ui.domain.mapItems.AbstractMapItem; import org.joverseer.ui.map.renderers.Renderer; import org.joverseer.ui.support.Messages; import org.joverseer.ui.support.dataFlavors.ArtifactDataFlavor; import org.joverseer.ui.support.dataFlavors.CharacterDataFlavor; import org.joverseer.ui.support.transferHandlers.HexNoTransferHandler; import org.joverseer.ui.views.MapEditorView; import org.springframework.richclient.application.Application; import org.springframework.richclient.command.CommandGroup; import org.springframework.richclient.dialog.ConfirmationDialog; import org.springframework.richclient.progress.BusyIndicator; /** * The basic control for displaying the map. It derives itself from a JPanel and * implements custom painting. * * Painting is done in a layered way in order to avoid having to always redraw * everything, which is slow The three layers are: 1. the map, which shows the * terrain and other static stuff for the game type 2. the map base items, which * shows fairly non-volatile objects for the current turn such as pop centers, * chars, armies, etc 3. the map items, which shows volatile objects such as * army ranges and orders Each layer is stored in a buffered image so that if * one of the higher layers is changed, the buffered image is used to redraw the * lower layer. * * The control uses renderers to paint the various layers. * * The control also implements mouse listener and mouse motion listener * interfaces to provide: - hex selection upon mouse click - scrolling upon * ctrl+mouse drag - drag & drop capability for dragging hex number from the map * to other controls * * * @author Marios Skounakis */ public class MapPanel extends JPanel implements MouseInputListener, MouseWheelListener { private static final long serialVersionUID = 1L; protected javax.swing.event.EventListenerList listenerList1 = new javax.swing.event.EventListenerList(); private static Logger logger = Logger.getLogger(MapPanel.class); private static MapPanel _instance = null; Polygon hex = new Polygon(); int[] xPoints = new int[6]; int[] yPoints = new int[6]; Point location = new Point(); boolean outOfMemoryErrorThrown = false; BufferedImage map = null; BufferedImage mapBaseItems = null; BufferedImage mapItems = null; BufferedImage mapBack = null; BufferedImage mapBaseItemsBack = null; BufferedImage mapItemsBack = null; MapMetadata metadata; Point selectedHex = null; private Game game = null; int xDiff, yDiff; boolean isDragging; java.awt.Container c; boolean saveMap = false; public MapPanel() { addMouseListener(this); addMouseWheelListener(this); addMouseMotionListener(this); this.setTransferHandler(new HexNoTransferHandler("hex")); //$NON-NLS-1$ this.setDropTarget(new DropTarget(this, new MapPanelDropTargetAdapter())); _instance = this; } public static MapPanel instance() { return _instance; } private void setHexLocation(int x, int y) { this.location = getHexLocation(x, y); } protected MapMetadata getMetadata() { if (this.metadata == null) { this.metadata = (MapMetadata) Application.instance().getApplicationContext().getBean("mapMetadata"); //$NON-NLS-1$ } return this.metadata; } public Point getHexCenter(int hexNo) { Point p = getHexLocation(hexNo); MapMetadata metadata1 = getMetadata(); p.translate(metadata1.getHexSize() * metadata1.getGridCellWidth() / 2, metadata1.getHexSize() * metadata1.getGridCellHeight() / 2); return p; } public Point getHexLocation(int hexNo) { return getHexLocation(hexNo / 100, hexNo % 100); } public Point getHexLocation(int x, int y) { Point location1 = new Point(); MapMetadata metadata1 = getMetadata(); x = x - metadata1.getMinMapColumn(); y = y - metadata1.getMinMapRow(); if ((y + metadata1.getMinMapRow() + 1) % 2 == 0) { location1.setLocation(metadata1.getHexSize() * metadata1.getGridCellWidth() * x, metadata1.getHexSize() * 3 / 4 * y * metadata1.getGridCellHeight()); } else { location1.setLocation((x + .5) * metadata1.getHexSize() * metadata1.getGridCellWidth(), metadata1.getHexSize() * 3 / 4 * y * metadata1.getGridCellHeight()); } return location1; } private void setPoints(int x, int y) { MapMetadata metadata1 = getMetadata(); this.xPoints[0] = metadata1.getHexSize() / 2; this.xPoints[1] = metadata1.getHexSize(); this.xPoints[2] = metadata1.getHexSize(); this.xPoints[3] = metadata1.getHexSize() / 2; this.xPoints[4] = 0; this.xPoints[5] = 0; this.yPoints[0] = 0; this.yPoints[1] = metadata1.getHexSize() / 4; this.yPoints[2] = metadata1.getHexSize() * 3 / 4; this.yPoints[3] = metadata1.getHexSize(); this.yPoints[4] = metadata1.getHexSize() * 3 / 4; this.yPoints[5] = metadata1.getHexSize() / 4; setHexLocation(x, y); for (int i = 0; i < 6; i++) { this.xPoints[i] = this.xPoints[i] * metadata1.getGridCellWidth() + this.location.x; this.yPoints[i] = this.yPoints[i] * metadata1.getGridCellHeight() + this.location.y; } } /** * Creates the basic map (the background layer with the hexes) The hexes are * retrieved from the Game Metadata and rendered with all the valid * available renderers found in the Map Metadata * */ private void createMap() { MapMetadata metadata1; try { metadata1 = getMetadata(); } catch (Exception exc) { // application is not ready return; } Game game1 = getGame(); if (!Game.isInitialized(game1)) return; GameMetadata gm = game1.getMetadata(); if (this.mapBack == null) { Dimension d = getMapDimension(); this.mapBack = new BufferedImage((int) d.getWidth(), (int) d.getHeight(), BufferedImage.TYPE_INT_ARGB); this.setPreferredSize(d); this.setSize(d); } this.map = this.mapBack; Graphics2D g = this.map.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, this.map.getWidth(), this.map.getHeight()); // try { // Resource r = // Application.instance().getApplicationContext().getResource("classpath:images/map/map.png"); // BufferedImage mm = ImageIO.read(r.getInputStream()); // g.drawImage(mm, 0, 0, null); // catch (Exception exc) { // exc.printStackTrace(); refreshRendersConfig(); for (Hex h : gm.getHexes()) { setHexLocation(h.getColumn(), h.getRow()); for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(h)) { r.render(h, g, this.location.x, this.location.y); } } } Container<Hex> hexOverrides = gm.getHexOverrides(game1.getCurrentTurn()); for (Hex h : hexOverrides) { setHexLocation(h.getColumn(), h.getRow()); for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(h)) { r.render(h, g, this.location.x, this.location.y); } } } if (this.saveMap) { File outputFile = new File("map.png"); //$NON-NLS-1$ try { ImageIO.write(this.map, "PNG", outputFile); //$NON-NLS-1$ } catch (Exception exc) { } ; } } public Dimension getMapDimension() { int width = (int) ((this.metadata.getMaxMapColumn() + 2d - this.metadata.getMinMapColumn() - .5) * this.metadata.getHexSize() * this.metadata.getGridCellWidth()); int height = (int) ((this.metadata.getMaxMapRow() * .75d + .25) * this.metadata.getHexSize() * this.metadata.getGridCellHeight()); return new Dimension(width, height); } private void createMapItems() { MapMetadata metadata1; try { metadata1 = getMetadata(); } catch (Exception exc) { // application is not ready return; } Game game1 = getGame(); if (!Game.isInitialized(game1)) return; Graphics2D g = null; BusyIndicator.showAt(this); try { refreshRendersConfig(); if (this.mapItemsBack == null) { Dimension d = getMapDimension(); this.mapItemsBack = new BufferedImage((int) d.getWidth(), (int) d.getHeight(), BufferedImage.TYPE_INT_ARGB); } this.mapItems = this.mapItemsBack; g = this.mapItems.createGraphics(); if (this.mapBaseItems == null) { createMapBaseItems(); } g.drawImage(this.mapBaseItems, 0, 0, this); } catch (OutOfMemoryError e) { if (!this.outOfMemoryErrorThrown) { this.outOfMemoryErrorThrown = true; throw e; } } try { for (Character c1 : getGame().getTurn().getCharacters()) { for (Order o : c1.getOrders()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(o)) { setHexLocation(c1.getX(), c1.getY()); try { r.render(o, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering order " + o.getCharacter().getName() + " " + o.getOrderNo() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } } } } } catch (Exception exc) { logger.error("Error rendering orders " + exc.getMessage()); //$NON-NLS-1$ } for (AbstractMapItem mi : game1.getTurn().getMapItems()) { for (Renderer r : metadata1.getRenderers()) { if (r.appliesTo(mi)) { r.render(mi, g, 0, 0); } } } try { for (Note n : getGame().getTurn().getNotes()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(n)) { setHexLocation(n.getX(), n.getY()); try { r.render(n, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering note " + n.getHexNo() + " " + n.getText() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } } } } catch (Exception exc) { logger.error("Error rendering notes " + exc.getMessage()); //$NON-NLS-1$ } BusyIndicator.clearAt(this); } /** * Draws the items on the map, i.e. everything that is in front of the * background (terrain) todo update with renderers */ private void createMapBaseItems() { MapMetadata metadata1; try { metadata1 = getMetadata(); } catch (Exception exc) { // application is not ready return; } Game game1 = getGame(); if (!Game.isInitialized(game1)) return; MapTooltipHolder.instance().reset(); BusyIndicator.showAt(this); refreshRendersConfig(); if (this.mapBaseItemsBack == null) { Dimension d = getMapDimension(); this.mapBaseItemsBack = new BufferedImage((int) d.getWidth(), (int) d.getHeight(), BufferedImage.TYPE_INT_ARGB); } this.mapBaseItems = this.mapBaseItemsBack; Graphics2D g = this.mapBaseItems.createGraphics(); if (this.map == null) { createMap(); } g.drawImage(this.map, 0, 0, this); try { for (PopulationCenter pc : getGame().getTurn().getPopulationCenters()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(pc)) { setHexLocation(pc.getX(), pc.getY()); try { r.render(pc, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error pc " + pc.getName() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } catch (Exception exc) { logger.error("Error rendering pop centers " + exc.getMessage()); //$NON-NLS-1$ } try { for (Character c1 : getGame().getTurn().getCharacters()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(c1)) { setHexLocation(c1.getX(), c1.getY()); try { r.render(c1, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering character " + c1.getName() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } catch (Exception exc) { logger.error("Error rendering pop centers " + exc.getMessage()); //$NON-NLS-1$ } try { for (Army army : getGame().getTurn().getArmies()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(army)) { setHexLocation(army.getX(), army.getY()); try { r.render(army, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering army " + army.getCommanderName() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } catch (Exception exc) { logger.error("Error rendering pop centers " + exc.getMessage()); //$NON-NLS-1$ } try { for (NationMessage nm : getGame().getTurn().getNationMessages()) { if (nm.getX() <= 0 || nm.getY() <= 0) continue; for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(nm)) { setHexLocation(nm.getX(), nm.getY()); try { r.render(nm, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering nation message " + nm.getMessage() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } catch (Exception exc) { logger.error("Error rendering nation " + exc.getMessage()); //$NON-NLS-1$ } try { for (Artifact a : getGame().getTurn().getArtifacts()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(a)) { setHexLocation(a.getX(), a.getY()); try { r.render(a, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering artifact " + a.getNumber() + " " + a.getName() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } } } } catch (Exception exc) { logger.error("Error rendering orders " + exc.getMessage()); //$NON-NLS-1$ } try { for (Combat a : getGame().getTurn().getCombats()) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(a)) { setHexLocation(a.getX(), a.getY()); try { r.render(a, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering combat " + a.getHexNo() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } catch (Exception exc) { logger.error("Error rendering combats " + exc.getMessage()); //$NON-NLS-1$ } try { ArrayList<Encounter> encounters = new ArrayList<Encounter>(); encounters.addAll(getGame().getTurn().getEncounters().getItems()); encounters.addAll(getGame().getTurn().getChallenges().getItems()); for (Encounter a : encounters) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { if (r.appliesTo(a)) { setHexLocation(a.getX(), a.getY()); try { r.render(a, g, this.location.x, this.location.y); } catch (Exception exc) { logger.error("Error rendering encounter " + a.getHexNo() + " " + exc.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } } } } catch (Exception exc) { logger.error("Error rendering encounters " + exc.getMessage()); //$NON-NLS-1$ } BusyIndicator.clearAt(this); } @Override public void invalidate() { } public void invalidateAndReset() { this.metadata = null; this.map = null; this.mapBack = null; this.mapItemsBack = null; this.mapBaseItemsBack = null; invalidateAll(); } public void invalidateAll() { this.metadata = null; this.map = null; this.mapBaseItems = null; this.mapItems = null; setGame(GameHolder.instance().getGame()); } public void invalidateMapItems() { this.metadata = null; this.mapItems = null; } public void refreshRendersConfig() { MapMetadata metadata1; metadata1 = getMetadata(); if (metadata1 != null ) { for (org.joverseer.ui.map.renderers.Renderer r : metadata1.getRenderers()) { r.refreshConfig(); } } } /** * Basic painting todo update/cleanup * * @param g */ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (isOpaque()) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); } if (this.mapItems == null) { createMapItems(); } if (this.mapItems == null) { // application is not ready return; } try { MapMetadata.instance(); } catch (Exception exc) { // application is not ready return; } // g.drawImage(map, 0, 0, this); g.drawImage(this.mapItems, 0, 0, this); if (getSelectedHex() != null) { Stroke s = ((Graphics2D) g).getStroke(); Stroke r = new BasicStroke(2); setPoints(getSelectedHex().x, getSelectedHex().y); g.setColor(Color.YELLOW); ((Graphics2D) g).setStroke(r); g.drawPolygon(this.xPoints, this.yPoints, 6); ((Graphics2D) g).setStroke(s); } } public Point getSelectedHex() { return this.selectedHex; } public void setSelectedHex(Point selectedHex) { if (selectedHex == null || (selectedHex.x == 0 && selectedHex.y == 0)) return; if (this.selectedHex == null || selectedHex.x != this.selectedHex.x || selectedHex.y != this.selectedHex.y) { this.selectedHex = selectedHex; // fireMyEvent(new SelectedHexChangedEvent(this)); joApplication.publishEvent(LifecycleEventsEnum.SelectedHexChangedEvent, selectedHex, this); } } public Rectangle getSelectedHexRectangle() { setHexLocation(getSelectedHex().x, getSelectedHex().y); MapMetadata metadata1; try { metadata1 = MapMetadata.instance(); return new Rectangle(this.location.x, this.location.y, metadata1.getHexSize() * metadata1.getGridCellWidth(), metadata1.getHexSize() * metadata1.getGridCellHeight()); } catch (Exception exc) { // application is not ready } return new Rectangle(this.location.x, this.location.y, 1, 1); } /** * Given a client point (eg from mouse click), it finds the containing hex * and returns it as a point (i.e. point.x = hex.column, point.y = hex.row) */ private Point getHexFromPoint(Point p) { MapMetadata metadata1 = MapMetadata.instance(); int y = p.y / (metadata1.getHexSize() * 3 / 4 * metadata1.getGridCellHeight()); int x; if ((y + metadata1.getMinMapRow() + 1) % 2 == 0) { x = p.x / (metadata1.getHexSize() * metadata1.getGridCellWidth()); } else { x = (p.x - metadata1.getHexSize() / 2 * metadata1.getGridCellWidth()) / (metadata1.getHexSize() * metadata1.getGridCellWidth()); } x += metadata1.getMinMapColumn(); y += metadata1.getMinMapRow(); if (x > metadata1.getMaxMapColumn()) x = metadata1.getMaxMapColumn(); if (y > metadata1.getMaxMapRow()) y = metadata1.getMaxMapRow(); return new Point(x, y); } /** * Handles the mouse pressed event to change the current selected hex */ @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { this.xDiff = e.getX(); this.yDiff = e.getY(); if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) { } else { setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } } else if (e.getButton() == MouseEvent.BUTTON3) { Point h = getHexFromPoint(e.getPoint()); int hexNo = h.x * 100 + h.y; Game g = GameHolder.instance().getGame(); Hex hex1 = g.getMetadata().getHex(hexNo); ArrayList<Object> commands = new ArrayList<Object>(Arrays.asList(new ShowCharacterMovementRangeCommand(hexNo, 12), new ShowCharacterLongStrideRangeCommand(hexNo), new ShowCharacterFastStrideRangeCommand(hexNo), new ShowCharacterPathMasteryRangeCommand(hexNo))); HexTerrainEnum terrain = hex1.getTerrain(); if (terrain.isLand()) { commands.add("separator"); //$NON-NLS-1$ commands.add(new ShowFedInfantryArmyRangeCommand(hexNo)); commands.add(new ShowUnfedInfantryArmyRangeCommand(hexNo)); commands.add(new ShowFedCavalryArmyRangeCommand(hexNo)); commands.add(new ShowUnfedCavalryArmyRangeCommand(hexNo)); } if (MovementUtils.calculateNavyRangeHexes(hexNo, false, true).size() > 0) { commands.add("separator"); //$NON-NLS-1$ commands.add(new ShowFedNavyCoastalRangeCommand(hexNo)); commands.add(new ShowUnfedNavyCoastalRangeCommand(hexNo)); commands.add(new ShowFedNavyOpenSeasRangeCommand(hexNo)); commands.add(new ShowUnfedNavyOpenSeasRangeCommand(hexNo)); } CommandGroup group = Application.instance().getActiveWindow().getCommandManager().createCommandGroup("MapPanelContextMenu", commands.toArray()); //$NON-NLS-1$ JPopupMenu popup = group.createPopupMenu(); popup.show(this, e.getPoint().x, e.getPoint().y); } } @Override public void mouseReleased(MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { Point p = e.getPoint(); Point hex1 = getHexFromPoint(p); setSelectedHex(hex1); this.updateUI(); } else if (e.getButton() == MouseEvent.BUTTON3) { HashMap<MapEditorOptionsEnum, Object> mapEditorOptions = (HashMap<MapEditorOptionsEnum, Object>) Application.instance().getApplicationContext().getBean("mapEditorOptions"); //$NON-NLS-1$ Boolean active = (Boolean) mapEditorOptions.get(MapEditorOptionsEnum.active); if (active == null || !active) return; Object brush = mapEditorOptions.get(MapEditorOptionsEnum.brush); if (HexTerrainEnum.class.isInstance(brush)) { Point p = e.getPoint(); Point h = getHexFromPoint(p); int hexNo = h.x * 100 + h.y; Hex hex1 = GameHolder.instance().getGame().getMetadata().getHex(hexNo); hex1.setTerrain((HexTerrainEnum) brush); MapEditorView.instance.log(""); //$NON-NLS-1$ MapEditorView.instance.log(hexNo + " terrain " + brush.toString()); invalidateAll(); this.updateUI(); } else if (HexSideElementEnum.class.isInstance(brush)) { Point p = e.getPoint(); Point h = getHexFromPoint(p); int hexNo = h.x * 100 + h.y; Hex hex1 = GameHolder.instance().getGame().getMetadata().getHex(hexNo); Point hp = getHexLocation(hexNo); int hexHalfWidth = this.metadata.getGridCellWidth() * this.metadata.getHexSize() / 2; int hexOneThirdHeight = this.metadata.getGridCellHeight() * this.metadata.getHexSize() / 3; boolean leftSide = p.x < hp.x + hexHalfWidth; int ySide = 0; if (p.y < hp.y + hexOneThirdHeight) { ySide = 0; } else if (p.y < hp.y + 2 * hexOneThirdHeight) { ySide = 1; } else { ySide = 2; } HexSideEnum hexSide = null; HexSideEnum otherHexSide = null; int otherHexNo = 0; if (leftSide) { if (ySide == 0) { hexSide = HexSideEnum.TopLeft; otherHexNo = MovementUtils.getHexNoAtDir(hexNo, MovementDirection.NorthWest); otherHexSide = HexSideEnum.BottomRight; } if (ySide == 1) { hexSide = HexSideEnum.Left; otherHexNo = MovementUtils.getHexNoAtDir(hexNo, MovementDirection.West); otherHexSide = HexSideEnum.Right; } if (ySide == 2) { hexSide = HexSideEnum.BottomLeft; otherHexNo = MovementUtils.getHexNoAtDir(hexNo, MovementDirection.SouthWest); otherHexSide = HexSideEnum.TopRight; } } else { if (ySide == 0) { hexSide = HexSideEnum.TopRight; otherHexNo = MovementUtils.getHexNoAtDir(hexNo, MovementDirection.NorthEast); otherHexSide = HexSideEnum.BottomLeft; } if (ySide == 1) { hexSide = HexSideEnum.Right; otherHexNo = MovementUtils.getHexNoAtDir(hexNo, MovementDirection.East); otherHexSide = HexSideEnum.Left; } if (ySide == 2) { hexSide = HexSideEnum.BottomRight; otherHexNo = MovementUtils.getHexNoAtDir(hexNo, MovementDirection.SouthEast); otherHexSide = HexSideEnum.TopLeft; } } Hex otherHex = null; if (otherHexNo > 0) { otherHex = GameHolder.instance().getGame().getMetadata().getHex(otherHexNo); } HexSideElementEnum element = (HexSideElementEnum) brush; ArrayList<HexSideElementEnum> toRemove = new ArrayList<HexSideElementEnum>(); ArrayList<HexSideElementEnum> toAdd = new ArrayList<HexSideElementEnum>(); if (hex1.getHexSideElements(hexSide).contains(element)) { // remove element // if element is a river, then remove the bridge as well if (element.equals(HexSideElementEnum.MajorRiver)) { // remove major river // remove bridge // remove ford toRemove.add(HexSideElementEnum.MajorRiver); toRemove.add(HexSideElementEnum.Bridge); toRemove.add(HexSideElementEnum.Ford); } else if (element.equals(HexSideElementEnum.MinorRiver)) { // remove minor river // remove bridge // remove ford toRemove.add(HexSideElementEnum.MinorRiver); toRemove.add(HexSideElementEnum.Bridge); toRemove.add(HexSideElementEnum.Ford); } else { // just remove the element toRemove.add(element); } } else { // adding new element if (element.equals(HexSideElementEnum.MajorRiver)) { // if new is major river, remove minor river toRemove.add(HexSideElementEnum.MinorRiver); } else if (element.equals(HexSideElementEnum.MinorRiver)) { // if new is minor river, remove major river toRemove.add(HexSideElementEnum.MajorRiver); } else if (element.equals(HexSideElementEnum.Bridge)) { // if new is bridge, remove ford toRemove.add(HexSideElementEnum.Ford); } else if (element.equals(HexSideElementEnum.Ford)) { // if new is ford, remove bridge and road toRemove.add(HexSideElementEnum.Bridge); } // add appropriate elements if (element.equals(HexSideElementEnum.Bridge)) { // add a bridge only if river exists if (hex1.getHexSideElements(hexSide).contains(HexSideElementEnum.MinorRiver) || hex1.getHexSideElements(hexSide).contains(HexSideElementEnum.MajorRiver)) { toAdd.add(HexSideElementEnum.Bridge); } } else { toAdd.add(element); } } if (toRemove.size() + toAdd.size() > 0) { MapEditorView.instance.log(""); //$NON-NLS-1$ } // remove what you must for (HexSideElementEnum el : toRemove) { if (hex1.getHexSideElements(hexSide).contains(el)) { hex1.getHexSideElements(hexSide).remove(el); MapEditorView.instance.log(hex1.getHexNo() + " " + hexSide.toString() + " remove " + el.toString()); //$NON-NLS-1$ } if (otherHex != null) { if (otherHex.getHexSideElements(otherHexSide).contains(el)) { otherHex.getHexSideElements(otherHexSide).remove(el); MapEditorView.instance.log(otherHex.getHexNo() + " " + otherHexSide.toString() + " remove " + el.toString()); //$NON-NLS-1$ } } } // add what you must for (HexSideElementEnum el : toAdd) { if (!hex1.getHexSideElements(hexSide).contains(el)) { MapEditorView.instance.log(hex1.getHexNo() + " " + hexSide.toString() + " add " + el.toString()); //$NON-NLS-1$ hex1.getHexSideElements(hexSide).add(el); } if (otherHex != null && !otherHex.getHexSideElements(otherHexSide).contains(el)) { MapEditorView.instance.log(otherHex.getHexNo() + " " + otherHexSide.toString() + " add " + el.toString()); //$NON-NLS-1$ otherHex.getHexSideElements(otherHexSide).add(el); } } invalidateAll(); this.updateUI(); } } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) { if (!GameHolder.hasInitializedGame()) return; int dx = Math.abs(e.getX() - this.xDiff); int dy = Math.abs(e.getY() - this.yDiff); if (dx > 5 || dy > 5) { TransferHandler handler = this.getTransferHandler(); handler.exportAsDrag(this, e, TransferHandler.COPY); requestFocusInWindow(); } } else { this.c = this.getParent(); if (this.c instanceof JViewport) { JViewport jv = (JViewport) this.c; Point p = jv.getViewPosition(); int newX = p.x - (e.getX() - this.xDiff); int newY = p.y - (e.getY() - this.yDiff); int maxX = this.getWidth() - jv.getWidth(); int maxY = this.getHeight() - jv.getHeight(); if (newX < 0) newX = 0; if (newX > maxX) newX = maxX; if (newY < 0) newY = 0; if (newY > maxY) newY = maxY; jv.setViewPosition(new Point(newX, newY)); } } } @Override public void mouseMoved(MouseEvent e) { MapTooltipHolder tooltipHolder = MapTooltipHolder.instance(); String pval = PreferenceRegistry.instance().getPreferenceValue("map.tooltips"); //$NON-NLS-1$ if (pval != null && pval.equals("yes")) //$NON-NLS-1$ tooltipHolder.showTooltip(e.getPoint(), e.getPoint()); } public Game getGame() { if (this.game == null) { this.game = GameHolder.instance().getGame(); } return this.game; } public void setGame(Game game) { this.game = game; } public BufferedImage getMapImage() { return this.mapItems; } public String getHex() { Point p = getHexFromPoint(new Point(this.xDiff, this.yDiff)); String h = String.valueOf(p.x * 100 + p.y); if (h.length() < 4) { h = "0" + h; //$NON-NLS-1$ } return h; } public void setHex(String hex) { }; public BufferedImage getMap() { return this.mapItems; } class MapPanelDropTargetAdapter extends DropTargetAdapter { @Override public void drop(DropTargetDropEvent e) { Transferable t = e.getTransferable(); Object obj = null; try { if (t.isDataFlavorSupported(new CharacterDataFlavor())) { obj = t.getTransferData(new CharacterDataFlavor()); } else if (t.isDataFlavorSupported(new ArtifactDataFlavor())) { obj = t.getTransferData(new ArtifactDataFlavor()); } else if (t.isDataFlavorSupported(new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" + Army.class.getName()))) { //$NON-NLS-1$ obj = t.getTransferData(new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" + Army.class.getName())); //$NON-NLS-1$ } ; Point p = MapPanel.instance().getHexFromPoint(e.getLocation()); final int hexNo = p.x * 100 + p.y; if (obj != null) { final Turn turn = GameHolder.instance().getGame().getTurn(); final Object target = obj; ConfirmationDialog dlg = new ConfirmationDialog(Messages.getString("MapPanel.MoveConfirmation.title"), Messages.getString("MapPanel.MoveConfirmation.text", new Object[] { hexNo })) { @Override protected void onConfirm() { if (Character.class.isInstance(target)) { ((Character) target).setHexNo(hexNo); turn.getCharacters().refreshItem((Character) target); } else if (Army.class.isInstance(target)) { ((Army) target).setHexNo(String.valueOf(hexNo)); turn.getArmies().refreshItem((Army) target); } else if (Artifact.class.isInstance(target)) { ((Artifact) target).setHexNo(hexNo); turn.getArtifacts().refreshItem((Artifact) target); } joApplication.publishEvent(LifecycleEventsEnum.SelectedTurnChangedEvent, this, this); } }; dlg.showDialog(); } } catch (Exception exc) { } ; } } @Override public void mouseWheelMoved(MouseWheelEvent e) { if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) { if (e.getUnitsToScroll() < 0) { joApplication.publishEvent(LifecycleEventsEnum.ZoomIncreaseEvent, this, this); } else if (e.getUnitsToScroll() > 0) { joApplication.publishEvent(LifecycleEventsEnum.ZoomDecreaseEvent, this, this); } } else { // get the JScrollPane for this container if (getParent() != null && getParent().getParent() != null) { for (MouseWheelListener mwl : getParent().getParent().getMouseWheelListeners()) { mwl.mouseWheelMoved(e); } } } } }
package org.jpos.space; public class SpaceTap implements SpaceListener { LocalSpace ssp; LocalSpace dsp; Object key; Object tapKey; long tapTimeout; /** * @param sp space * @param key key to monitor * @param tapKey key to use when copying * @param tapTimeout copy timeout in millis */ public SpaceTap (LocalSpace sp, Object key, Object tapKey, long tapTimeout) { this (sp, sp, key, tapKey, tapTimeout); } /** * @param ssp source space * @param dsp destination space * @param key key to monitor * @param tapKey key to use when copying * @param tapTimeout copy timeout in millis */ public SpaceTap (LocalSpace ssp, LocalSpace dsp, Object key, Object tapKey, long tapTimeout) { super(); this.ssp = ssp; this.dsp = dsp; this.key = key; this.tapKey = tapKey; this.tapTimeout = tapTimeout; if (key.equals (tapKey) && ssp == dsp) throw new IllegalArgumentException ("Possible deadlock - key equals tap-key within same space"); ssp.addListener (key, this); } public void notify (Object key, Object value) { dsp.out (tapKey, value, tapTimeout); } public void close() { if (ssp != null) { ssp.removeListener (key, this); ssp = null; } } }
package com.mybar.music.util; import android.media.MediaPlayer; public class MusicPlayer { private static MediaPlayer mediaPlayer = getMedia();; public static MediaPlayer getMedia() { if (mediaPlayer == null) { // System.out.println("321321"); mediaPlayer = new MediaPlayer(); // System.out.println("123123"); } return mediaPlayer; } public void playFromLocal(String path) { try { // System.out.println("aaaaa"); mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepare(); mediaPlayer.start(); mediaPlayer .setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub // Mp3Thread.state = Final.DOWN;// } }); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void playFromNetwork(String path) { try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepare(); mediaPlayer.start(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public boolean Pause() { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); return true; } else { mediaPlayer.start(); return false; } } public int GetPlayerTime() { return mediaPlayer.getCurrentPosition(); } public void SeektoMusic(int time) { mediaPlayer.seekTo(time); mediaPlayer.start(); } }
package netplot; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.Container; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; /* * Change log * * 2.4 * - Allow plot images bigger than the screen size to be saved. * - Allow plot images to be GIF or PNG files. * * 2.3 * - Add menu option to save all plots on a grid as a png file. * * 2.2 * - Previous fix, stopped showing the log axis name, if set. Fixed. * * 2.1 * - Fixed build of Java demo client. Previously it would not run. * - Log plot now shows log values correctly. * * 2.0 * - Don't resize frame/window (call pack() on frame) when the client sets the grid * dimensions as it is unwanted behaviour. * - When closed the position and size of the window is saved. When restarted the * last position and size of the window is restored. * - Split the Netplot client demo out into separate Java src file in order to * improve clarity of code. * * 1.9 * - Maximising the frame is painful to use. Revert to previous approach. * * 1.8 * - Enable auto flush on PrintWriter back to client in order to improve plot speed. * - When starting up Netplot frame startup maximised. * * 1.7 * - Add ability to set the thickness of the plot lines to netplot. Updated all * clients and all demo's. * * 1.6 * - If we don't have a valid number to plot for a timeseries plot we ignore it. * and do not generate an error as on a time series graph we may not have * values for all points in time for all plots. * * 1.5 * - Add the ability to plot time periods not in real time. Previously when a value * to be plotted was added the time at which the value was received was used as * X axis time value. No it is possible to pass the time stamp from the client * to the server in order to plot old time series data. * * 1.4 * - If a bind error on the TCP ports used by the netplot GUI server then report the * port error in the error message. * * 1.3 * - Fixed the input of the max plot count on the command line. -p argument was used * twice, rather than -p and -m. * - Previously when 10 chart panels were requested 11 servers were opened. Now it will * open 10 as it should do. * * 1.21 * Possible fix when invalid xy plot values are detected. * * 1.20 * Added two keywords to the commands * enable_status : Enable/disable adding messages to the GUI status message history window. * replot : Restart the plotting of data so that the next plot point added replaces * the first plot point, the next replaces the second displayed plot point * and so on. * * 1.19 * - Update the help text on the status log window. * - Add clear command to empty a plot of data. * * 1.18 * Set all plots background to white rather than light grey as is several plots are displayed * light grey is used to display a plot. * * 1.17 * - Remove stdout debug print messages * * 1.16 * Don't resize frame when graph init occurs as the user may want to size/position the graph * window themselves. * Fix bug in java netplot client that caused always added new Y axis even when no Y axis name * had been set. * * 1.15 * Added disconnect method to the NetplotClient class. * * 1.14 Initial release * */ /** * Show a frame with a status bar along the lower edge. * This status bar may be double clicked to get the help text * for commands that may be used to plot data. */ public class PlotFrame extends JFrame implements ActionListener { static final long serialVersionUID=5; public static final double NETPLOT_VERSION=2.4; String helpLines[] = { "* All netplot commands are text strings which makes the client code simple to implement.", "* Java and python clients are supplied by default but you may implement you own clients", "* using the information below.", "* ", "* The commands (all text strings) that may be used over the TCP/IP network connections", "* on ports "+NetPlotter.basePort+" - "+(+NetPlotter.basePort+NetPlotter.maxPlotCount)+" are shown below", "* ", "*** GLOBAL ATTRIBUTES ***", "* set grid=2,2", "* Set chart grid 2,2 gives 4 charts. Connect to the base TCP/IP port to set", "* chart 0, base TCP/IP port+1 for chart 1, etc. This should be called after", "* connecting. Max of "+NetPlotter.maxPlotCount+" charts available on above TCP/IP ports.", "* ", "* set "+KeyWords.FRAME_TITLE+"=The Frame Title", "* Sets the text in the title bar of the window holding the charts.", "* ", "* ", "*** CHART SPECIFIC ATTRIBUTES ***", "* ", "* set graph=time", "* Init a timeplot graph (This is the default graph type).", "*", "* set graph=bar", "* Init a barplot graph (plots a single value repeatedly as different bars).", "*", "* set graph=xy", "* Init an X/Y plot graph. Plot may include lines and shapes.", "* ", "* init", "* Init the graph. This should be called after the set graph= command has been issued.", "* ", "* set "+KeyWords.ENABLE_LEGEND+"=true", "* true/false, enables/disables the inclusion of the plot titles (Legend) at the bottom of the graph.", "* ", "* enable_status 1", "* Enables the status messages in the GUI (default), enable_status 0 will disable the", "* status messages in the GUI. The messages will not then be shown in the status message history window.", "* This may speed up the plotting of data if CPU bound.", "* ", "* ", "*** PLOT SPECIFIC ATTRIBUTES ***", "* ", "* set "+KeyWords.PLOT_TITLE+"=The plot title", "* Set the chart title.", "* ", "* set "+KeyWords.PLOT_NAME+"=The plot name", "* Set the name of a plot", "* ", "* set "+KeyWords.X_AXIS_NAME+"=X axis name", "* Set the name of the x axis. All plots on a graph have the same X axis.", "* ", "* set "+KeyWords.Y_AXIS_NAME+"=Y axis name", "* Set the name of the y axis. Multiple Y axis may be added to a chart.", "* ", "* set "+KeyWords.ENABLE_LINES+"=true", "* true/false, enables/disables printed lines on a plot", "* ", "* set "+KeyWords.LINE_WIDTH+"=X", "* Set the width (in pixels) of the lines to be used when above option is enabled (default="+GenericPlotPanel.DEFAULT_LINE_WIDTH+").", "* ", "* set "+KeyWords.ENABLE_SHAPES+"=true", "* true/false, enables/disables printed shapes (plot points) on a plot", "* ", "* set "+KeyWords.ENABLE_AUTOSCALE+"=true", "* true/false, enables/disables autoscaling of plot. Autoscaling is disabled on Log plots.", "* ", "* set "+KeyWords.MIN_SCALE_VALUE+"=-100", "* Defines the min Y scale value when autoscale is disabled.", "* ", "* set "+KeyWords.MAX_SCALE_VALUE+"=100", "* Defines the max Y scale value when autoscale is disabled.", "* ", "* set "+KeyWords.MAX_AGE_SECONDS+"=60", "* Only valid on time plots. Sets the max age of the plot. After this period the plot slides off the left side of the chart.", "* ", "* set "+KeyWords.ENABLE_LOG_Y_AXIS+"=true", "* true/false, enables/disables a logarithmic Y scale. The min and max Y scales values are used.", "* ", "* set "+KeyWords.ENABLE_ZERO_ON_X_SCALE+"=true", "* true/false, enables/disables the inclusion of the value 0 the X scale when autoscale is enabled.", "* ", "* set "+KeyWords.ENABLE_ZERO_ON_Y_SCALE+"=true", "* true/false, enables/disables the inclusion of the value 0 the Y scale when autoscale is enabled.", "* ", "* set "+KeyWords.TICK_COUNT+"=0", "* Sets the tick count on the Y axis. A tick will occur at this interval on the Y axis of time, bar and xy charts.", "* The default is 0 which will automatically set the Y axis tick count.", "* ", "* clear 0", "* Clears all values in plot 0.", "* ", "* replot 0", "* Restarts the plotting of plot 0 at the first plot point. The next plot point added will replace the first", "* plot point, the next the second, and so on.", "* ", "*** ADDING NUMBERS TO PLOTS ***", "* ", "* Adding plot points to all plots except xy plots can be done as follows.", "* ", "* To add the value 40 to a single time plot you would send", "* 40", "* ", "* If two time plots have been defined and you wish to add 10 to the first plot and 20 to the second, you would send", "* 10,20", "* ", "* Multiple time plots are possible.", "* Only single bar plots are possible.", "* Only two dial plots are possible.", "* Mulltiple xy plots are possible.", "* ", "* To add the value x=10,y=20 to xy plot 0 you would send", "* 0:10:20", "* ", "* To add the value x=10,y=20 to xy plot 0 and x=50, y=60 to plot 1 you would send", "* 0:10:20", "* then send", "* 1:50:60", "* ", "* When plotting to a time series plot you would send", "* 0:2013;00;02;23;10;05;587:1.234", "* Plot index 0 (digit before first colon)", "* Timestamp=Jan 02 2013 23:10:05 and 587 microseconds", "* value=1.234", "* ", }; StatusBar statusBar; private final JPanel mainPanel = new JPanel( new BorderLayout() ); private final JPanel chartPanel = new JPanel(); private boolean showStatusMessages=true; private JMenuBar menuBar; private JMenu fileMenu; private JMenuItem savePlotsMenuItem; private JFileChooser saveImageJFC = new JFileChooser(); public PlotFrame() { statusBar = new StatusBar(); statusBar.println("Version "+PlotFrame.NETPLOT_VERSION); for( String line : helpLines ) { statusBar.println(line); } getContentPane().add(mainPanel); mainPanel.add(statusBar,BorderLayout.SOUTH); JScrollPane jScrollPane = new JScrollPane(chartPanel); jScrollPane.setPreferredSize( new Dimension(1024,768)); mainPanel.add(jScrollPane,BorderLayout.CENTER); setChartLayout(1,1); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menuBar = new JMenuBar(); fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); menuBar.add(fileMenu); savePlotsMenuItem = new JMenuItem("Save Image", KeyEvent.VK_S); savePlotsMenuItem.getAccessibleContext().setAccessibleDescription("Save plots as an image file"); fileMenu.add(savePlotsMenuItem); setJMenuBar(menuBar); savePlotsMenuItem.addActionListener(this); saveImageJFC.setToolTipText("Save window to a PNG image file."); try { NetPlotter.PersistentConfig.load(NetPlotter.NetPlotterPersistentConfigFile); //Set the location of the window when previously shutdown //But protect from being moved off the screen if( NetPlotter.PersistentConfig.guiXPos < 0 ) { NetPlotter.PersistentConfig.guiXPos=0; } if( NetPlotter.PersistentConfig.guiYPos < 0 ) { NetPlotter.PersistentConfig.guiYPos=0; } setLocation(NetPlotter.PersistentConfig.guiXPos, NetPlotter.PersistentConfig.guiYPos); setSize(NetPlotter.PersistentConfig.guiWidth, NetPlotter.PersistentConfig.guiHeight); } catch(Exception e) { mainPanel.add(jScrollPane,BorderLayout.CENTER); pack(); } ShutDownHandler shutDownHandler = new ShutDownHandler(this); Runtime.getRuntime().addShutdownHook(shutDownHandler); } public void addPanel(Component panel, int index) { chartPanel.add(panel,index); } public void removePanel(int index) { chartPanel.remove(index); } private void removeAllPanels() { chartPanel.removeAll(); } public int getPanelCount() { return chartPanel.getComponentCount(); } public void setChartLayout(int rows, int columns) { removeAllPanels(); chartPanel.setLayout( new GridLayout(rows,columns) ); } public static void main(String args[]) { PlotFrame plotFrame = new PlotFrame(); plotFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TimeSeriesPlotPanel plotPanel = new TimeSeriesPlotPanel(); plotFrame.getContentPane().add(plotPanel); plotFrame.pack(); plotFrame.setVisible(true); try { plotPanel.setAttribute(KeyWords.PLOT_NAME, "plot1"); plotPanel.setAttribute(KeyWords.ENABLE_SHAPES, "true"); plotPanel.setAttribute(KeyWords.ENABLE_LINES, "true"); plotPanel.setAttribute(KeyWords.ENABLE_AUTOSCALE, "true"); plotPanel.addPlot(); plotPanel.setAttribute(KeyWords.PLOT_NAME, "plot2"); plotPanel.addPlot(); while(true) { plotPanel.addPlotValue(0,Math.random()); plotPanel.addPlotValue(1,Math.random()*-100); try { Thread.sleep(500); } catch(Exception e) {} } } catch(Exception e) { e.printStackTrace(); } } public void addStatusMessage(String line) { if( showStatusMessages ) { statusBar.println(line); } } public void SetEnableStatusMessages(boolean enabled) { showStatusMessages=enabled; } @Override /** * @brief Process menu selection events */ public void actionPerformed(ActionEvent e) { if( e.getSource() == savePlotsMenuItem ) { captureFrame(); } } /** * @brief Capture all plots to a png file. */ private void captureFrame() { try { int retVal = saveImageJFC.showSaveDialog(null); int width = chartPanel.getWidth(); int height = chartPanel.getHeight(); if( height > 0 && height > 0 ) { if(retVal==JFileChooser.APPROVE_OPTION){ BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); chartPanel.paint(im.getGraphics()); String filename = saveImageJFC.getSelectedFile().getAbsolutePath(); String fileSuffix = ""; if( filename.toLowerCase().endsWith(".gif") ) { fileSuffix="GIF"; } else if( filename.toLowerCase().endsWith(".png") ) { fileSuffix="PNG"; } if( fileSuffix.length() > 0 ) { ImageIO.write(im, fileSuffix, saveImageJFC.getSelectedFile()); } else { JOptionPane.showMessageDialog(this, "Invalid image file type. File extension must be gif or png.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(this, "Plot window to small to save as an image.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (IOException e) { e.printStackTrace(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package network; import Datastructure.Rete.BasicNode; import Datastructure.Rete.Node; import Datastructure.Rewriting.Rewriter_easyMCS; import Entity.*; import Exceptions.FactSizeException; import Exceptions.RuleNotSafeException; import java.io.IOException; import java.rmi.RMISecurityManager; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.*; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.antlr.runtime.ANTLRFileStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import parser.antlr.wocLexer; import parser.antlr.wocParser; /** * * @author Minh Dao-Tran, Antonius Weinzierl */ public class ANodeImpl implements ANodeInterface { private Map<String,ANodeInterface> other_nodes; // for serialization/deserialization public static String serializingFrom = null; // mappings for deserialization // integer to function symbols/constants public static Map<Integer, Object> deser_mapping = new HashMap<Integer, Object>(); // separate map to localize predicate names public static Map<String,HashMap<Integer,Predicate>> predicate_mapping = new HashMap<String,HashMap<Integer, Predicate>>(); private static HashSet< Predicate > local_predicates = new HashSet<Predicate>(); // mapping for serialization: // predicates/function symbols/constants to integers public static Map<Object, Integer> out_mapping = new HashMap<Object, Integer>(); // as an integer uniquely identifies the instance of // the specific class, we only need one map // TODO AW something more specific than Object would be nice // list of predicates required at other nodes used for out-projection of predicates private static Map<Predicate, ArrayList<ANodeInterface>> required_predicates = new HashMap<Predicate, ArrayList<ANodeInterface>>(); //private static Map<String, ArrayList<Predicate>> required_predicates = // new HashMap<String, ArrayList<Predicate>>(); // the local import interface, i.e., which predicates are imported from where private static Map<String, ArrayList<Pair<String,Integer>>> import_predicates = new HashMap<String, ArrayList<Pair<String,Integer>>>(); // mapping from global to local decision levels private Map<Integer, Integer> global_to_local_dc = new HashMap<Integer, Integer>(); private HashSet<Predicate> closed_predicates; private static ContextASPMCSRewriting ctx; //private static int decision_level_before_push; public static String local_name; private String filter; private String filename; private long solving_time; public ANodeImpl(String local_name, String filename, String filter) { super(); solving_time = 0; this.local_name = local_name; this.filename = filename; this.filter = filter; closed_predicates = new HashSet<Predicate>(); other_nodes = new HashMap<String, ANodeInterface>(); if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager() ); } try { ANodeInterface stub = (ANodeInterface) UnicastRemoteObject.exportObject(this,0); // use anonymous/no port Registry registry = LocateRegistry.getRegistry(); registry.rebind(local_name, stub); System.out.println("Node[" + local_name +"]: NodeImpl bound."); } catch (Exception e) { System.err.println("Node[" + local_name +"]: ANodeImpl exception:"); e.printStackTrace(); } //global_to_local_dc.put(0, 0); } public String getName() { return local_name; } @Override public long getSolvingTime() throws RemoteException { return solving_time; } @Override public ReplyMessage init(ArrayList<Pair<String, ANodeInterface>> other_nodes) throws RemoteException { for (Pair<String, ANodeInterface> pair : other_nodes) { this.other_nodes.put(pair.getArg1(), pair.getArg2()); } //this.other_nodes = other_nodes; //System.out.println("Node[" + local_name +"]: received " + other_nodes.size() +" other nodes."); // create context ctx = new ContextASPMCSRewriting(); // parsing with ANTLR try { // setting up lexer and parser wocLexer lex = new wocLexer(new ANTLRFileStream(filename)); wocParser parser = new wocParser(new CommonTokenStream(lex)); // set context parser.setContext(ctx); // parse input parser.woc_program(); //System.out.println("Node[" + local_name +"]: Read in program is: "); //ctx.printContext(); // rewrite context Rewriter_easyMCS rewriter = new Rewriter_easyMCS(); ctx = rewriter.rewrite(ctx); } catch (RuleNotSafeException ex) { Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (FactSizeException ex) { Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (RecognitionException ex) { Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); } long start_computing = System.currentTimeMillis(); ctx.propagate(); //System.out.println("First Propagation finished: " + System.currentTimeMillis()); ctx.getChoiceUnit().DeriveSCC(); //System.out.println("Call killSoloSCC"); ctx.getChoiceUnit().killSoloSCC(); solving_time = solving_time + System.currentTimeMillis() - start_computing; //System.out.println("After killSoloSCC"); //ctx.printAnswerSet(filter); // collecting local predicates //System.out.println("Node[" + local_name +"]: Collecting local predicates."); for (Iterator<Predicate> it = Predicate.getPredicatesIterator(); it.hasNext();) { Predicate pred = it.next(); local_predicates.add(pred); // record if this predicate is external if(pred.getNodeId()!=null) { // collect import interface String from_node = pred.getNodeId(); ArrayList<Pair<String,Integer>> preds_from_node; // check if other node is already listed if(import_predicates.containsKey(from_node)) { preds_from_node = import_predicates.get(from_node); } else { preds_from_node = new ArrayList<Pair<String, Integer>>(); import_predicates.put(from_node, preds_from_node); } //System.out.println("Node[" + local_name +"]: Predicate is from outside: "+pred.toString()); // add import predicate preds_from_node.add(new Pair<String, Integer>(pred.getName(),pred.getArity())); //System.out.println("Node[" + node_name +"]: Currently listed predicates of node ["+from_node+"]: "+preds_from_node); // register predicate at local solver to come from outside // is done in parser already //ANodeImpl.ctx.registerFactFromOutside(pred); } } //System.out.println("Node[" + local_name +"]: import predicates: "+import_predicates); //System.out.println("Node[" + local_name +"]: Initialized node."); return ReplyMessage.SUCCEEDED; } @Override public int exchange_active_domain(int serialize_start) throws RemoteException { // get list of predicate/functions/constants int counter=serialize_start; // this will contain the id that a certain instance // is mapped to, we make it unique over all types. // collect predicate symbols Map<Pair<String,Integer>,Integer> predicates = new HashMap<Pair<String,Integer>,Integer>(); predicate_mapping.put(local_name, new HashMap<Integer, Predicate>()); // mapping to de-serialize local predicates (for receiving import domain) for (Iterator<Predicate> it = local_predicates.iterator(); it.hasNext();) { Predicate pred = it.next(); // if this is an external predicate, assume it is already there at the other context, i.e., ignore it if(pred.getNodeId()!=null) continue; // TODO AW this can trigger some bug in the following case: if we locally import n1:q(X) but the program of n1 does not contain q/1. String name = pred.getName(); Integer arity=pred.getArity(); Integer ser_id = counter++; predicates.put(new Pair<String, Integer>(name,arity), ser_id); //predicate_mapping.get(local_name).put(ser_id, pred); out_mapping.put(pred,ser_id); } // collect constants Map<String, Integer> constants = new HashMap<String,Integer>(); for (Iterator<Constant> it = Constant.getConstantsIterator(); it.hasNext();) { Constant con = it.next(); String name = con.getName(); Integer ser_id = counter++; constants.put(name, ser_id); out_mapping.put(con, ser_id); deser_mapping.put(ser_id, con); } // collect function symbols Map<String,Integer> functions = new HashMap<String, Integer>(); for (Iterator<FunctionSymbol> it = FunctionSymbol.getFunctionSymbolsIterator(); it.hasNext();) { FunctionSymbol func = it.next(); String name = func.getName(); Integer ser_id = counter++; functions.put(name, ser_id); out_mapping.put(func, ser_id); deser_mapping.put(ser_id, func); } for (Entry<String, ANodeInterface> other : other_nodes.entrySet()) { // tell active domain to other nodes except self if(!other.getKey().equals(local_name)) { other.getValue().receive_active_domain(local_name, predicates, functions, constants); } } return counter; } @Override public ReplyMessage exchange_import_domain() throws RemoteException { //System.out.println("Node[" + local_name +"]: Exchanging import domain."); // tell import interface to all nodes for(Entry<String,ANodeInterface> other : other_nodes.entrySet()) { //System.out.println("Node[" + local_name +"]: Import predicates from Node["+other.getKey()+"]: " + import_predicates.get(other.getKey())); // only exchange import if it is non-empty if(import_predicates.get(other.getKey())!=null) { other.getValue().receiveNextFactsFrom(local_name); // needed to de-serialize predicates at other node other.getValue().receive_import_domain(local_name,import_predicates.get(other.getKey())); } } return ReplyMessage.SUCCEEDED; } @Override public ReplyMessage receive_active_domain(String other_node, Map<Pair<String, Integer>, Integer> predicates, Map<String, Integer> functions, Map<String, Integer> constants) throws RemoteException { //System.out.println("Node[" + local_name +"]: Receiving active domain from " + other_node); //System.out.println("Node[" + local_name +"]: Adding predicates: "+predicates); // fill mapping: predicates HashMap<Integer,Predicate> pred_map = new HashMap<Integer, Predicate>(); for (Entry<Pair<String,Integer>,Integer> pred_desc: predicates.entrySet()) { // TODO AW hack to normalize predicate names // n2:q occuring in context n1 locally is q String local_pred_name; if(pred_desc.getKey().getArg1().contains(":")) { throw new RemoteException("Node[" + local_name +"]: Received external predicate from Node["+other_node+"]"); } else { // localize predicate name local_pred_name = other_node+":"+pred_desc.getKey().getArg1(); } Predicate pred = Predicate.getPredicate(local_pred_name, pred_desc.getKey().getArg2()); //ctx.getRete().addPredicatePlus(pred); pred_map.put( pred_desc.getValue(), pred); //System.out.println("Node[" + local_name +"]: Added to mapping: "+pred+" with value "+pred_desc.getValue()+" from "+other_node); } predicate_mapping.put(other_node, pred_map); //System.out.println("Adding function symbols: "+functions); // fill mapping: function symbols for(Entry<String, Integer> func_desc : functions.entrySet()) { FunctionSymbol fun = FunctionSymbol.getFunctionSymbol(func_desc.getKey()); deser_mapping.put(func_desc.getValue(), fun); out_mapping.put(fun, func_desc.getValue()); } //System.out.println("Adding constants: "+constants); // fill mapping: constants for(Entry<String, Integer> con_desc : constants.entrySet()) { Constant con = Constant.getConstant(con_desc.getKey()); deser_mapping.put(con_desc.getValue(), con); out_mapping.put(con, con_desc.getValue()); } //System.out.println("Node[" + local_name +"]: Active domain mapping wrt. node "+other_node+" created."); return ReplyMessage.SUCCEEDED; } @Override public ReplyMessage receiveNextFactsFrom(String from_node) throws RemoteException { serializingFrom = from_node; //System.out.println("Node[" + local_name +"]: The next facts will come from Node[" + from_node+"]"); //ctx.printAnswerSet(filter); return ReplyMessage.SUCCEEDED; } @Override public ReplyMessage receive_import_domain(String from, List<Pair<String,Integer>> required_predicates) throws RemoteException { //System.out.println("Node[" + local_name + "]: got import domain from Node[" + from+"]"); //System.out.println("Node[" + local_name + "]: required predicates are: "+required_predicates); ArrayList<Predicate> required_preds = new ArrayList<Predicate>(); for (Iterator<Pair<String, Integer>> it = required_predicates.iterator(); it.hasNext();) { Pair<String, Integer> pair = it.next(); if(!pair.getArg1().startsWith(local_name+":")) throw new RemoteException("Node[" + local_name +"]: Node identifier of received import predicate ["+pair.getArg1()+"] differs from local name ["+local_name+"]"); String local_pred_name = pair.getArg1().replaceFirst(".*:", ""); //System.out.println("Node[" + local_name +"]: Localized predicate "+ pair.getArg1() + " to "+local_pred_name); // check that the imported predicate exists locally if(!local_predicates.contains(Predicate.getPredicate(local_pred_name, pair.getArg2()))) { throw new RemoteException("Node["+local_name+"]: requested non-existent predicate "+pair.getArg1()+"/"+pair.getArg2()+" from Node "+from); } required_preds.add(Predicate.getPredicate(local_pred_name, pair.getArg2())); } // build list of other nodes that import local predicates for (Predicate predicate : required_preds) { if( !ANodeImpl.required_predicates.containsKey(predicate)) ANodeImpl.required_predicates.put(predicate, new ArrayList<ANodeInterface>()); ANodeInterface from_node = other_nodes.get(from); ANodeImpl.required_predicates.get(predicate).add(from_node); } //ANodeImpl.required_predicates.put(from, (ArrayList<Predicate>)required_preds); return ReplyMessage.SUCCEEDED; } @Override public ReplyMessage firstPropagate() throws RemoteException { //System.out.println("Node[" + local_name + "]: firstPropagate."); long start_propagate = System.currentTimeMillis(); ctx.propagate(); solving_time = solving_time + System.currentTimeMillis() - start_propagate; //System.out.println("Node[" + local_name + "]: after firstPropagate. interpretation is "); //ctx.printAnswerSet(filter); if (ctx.isSatisfiable()) { //System.out.println("Node[" + local_name + "]: firstPropagate. Pushing."); ReplyMessage reply = pushDerivedFacts(0, 0); if (reply == ReplyMessage.SUCCEEDED) { //System.out.println("Node[" + local_name + "]: All neighbors propagated successfully. Return SUCCEEDED"); return ReplyMessage.SUCCEEDED; } else { //System.out.println("Node[" + local_name + "]: A neighbor got inconsistent. Return INCONSISTENT"); return ReplyMessage.INCONSISTENT; } } else { //System.out.println("Node[" + local_name + "]: firstPropagate. Return INCONSISTENT."); return ReplyMessage.INCONSISTENT; } } @Override public ReplyMessage localBacktrack(int global_level) throws RemoteException { //System.out.println("Node[" + local_name + "]: start in backtrack. local_dc = " + ctx.getDecisionLevel()); Integer local_dc = global_to_local_dc.get(global_level); //System.out.println("Node[" + local_name + "]: backtrack to global_level = " + global_level); if (local_dc != null) { //System.out.println("Node[" + local_name + "]: corresponding local level = " + local_dc); long start_backtrack = System.currentTimeMillis(); ctx.backtrackTo(local_dc.intValue()); if (global_to_local_dc.remove(global_level+1) == null) { global_to_local_dc.remove(global_level); } // remove all re-opened predicates from the list of closed predicates for (Iterator<Predicate> it = closed_predicates.iterator(); it.hasNext();) { Predicate predicate = it.next(); if( !ctx.getRete().getBasicNodeMinus(predicate).isClosed() ) it.remove(); } solving_time = solving_time + System.currentTimeMillis() - start_backtrack; //int gl1 = global_level+1; //System.out.println("Node[" + local_name + "]: makeBranch. remove(" + gl1 + ")."); //System.out.println("After backtracking. Current local decision level = " + ctx.getDecisionLevel()); } //else // System.out.println("Node[" + local_name + "]: no corresponding local level found."); return ReplyMessage.SUCCEEDED; } @Override public ReplyMessage printAnswer() throws RemoteException { System.out.println("Node[" + local_name + "]: print interpretation:"); ctx.printAnswerSet(filter); return ReplyMessage.SUCCEEDED; } @Override public ReplyMessage finalClosing(int global_level) throws RemoteException { // increase the outside global_level by one before calling this method //System.out.println("Node[" + local_name + "]: finalClosing. Store (global_level,local_dc) = (" + global_level + ", " + ctx.getDecisionLevel() +")"); long start_final_closing = System.currentTimeMillis(); global_to_local_dc.put(global_level, ctx.getDecisionLevel()); int dec = ctx.getDecisionLevel()+1; for (Predicate predicate : local_predicates) { if( predicate.getNodeId()!= null) { closed_predicates.add(predicate); ctx.closeFactFromOutside(predicate); } } ArrayList<LinkedList<Pair<Node, Instance>>> new_facts = ctx.deriveNewFacts(); for (int dl = dec; dl < new_facts.size(); dl++) { for (Pair<Node, Instance> pair : new_facts.get(dl)) { if(pair.getArg1().getClass().equals(BasicNode.class)) { //System.out.println("Node["+local_name+"]: finalClosing derived new fact: "+((BasicNode)pair.getArg1()).getPred()+" "+ pair.getArg2()); solving_time = solving_time + System.currentTimeMillis() - start_final_closing; return ReplyMessage.INCONSISTENT; } } } /*HashMap<Predicate, HashSet<Instance>> new_facts = ctx.deriveNewFacts(dec); System.out.println("Node["+local_name+"]: finalClosing, new_facts: "+new_facts); for (HashSet<Instance> hashSet : new_facts.values()) { if( !hashSet.isEmpty() ) return ReplyMessage.INCONSISTENT; }*/ if (!ctx.isSatisfiable()) { solving_time = solving_time + System.currentTimeMillis() - start_final_closing; return ReplyMessage.INCONSISTENT; } solving_time = solving_time + System.currentTimeMillis() - start_final_closing; return ReplyMessage.SUCCEEDED; } /*for(Entry<Predicate, ArrayList<Instance>> pred : in_facts.entrySet()) { // print out what was received System.out.println("Node[" + local_name +"]: Predicate "+pred.getKey().getName()+"/"+ pred.getKey().getArity()+ ", "+ pred.getValue().size()+" entries."); for (Iterator it = pred.getValue().iterator(); it.hasNext();) { Instance inst = (Instance)it.next(); System.out.println("Node[" + local_name +"]: Instance: "+inst.toString()); // actual adding of the facts System.out.println("Node[" + local_name +"]: Adding Predicate / Instance = "+pred.getKey()+"/"+inst); ANodeImpl.ctx.addFactFromOutside(pred.getKey(), inst); } }*/ if(closed_predicates != null ) { //System.out.println("Node[" + local_name + "]: Closed predicates are: " + closed_predicates); long start_adding_closed_preds = System.currentTimeMillis(); for (Predicate predicate : closed_predicates) { ctx.closeFactFromOutside(predicate); } solving_time = solving_time + System.currentTimeMillis() - start_adding_closed_preds; } //System.out.println("Node[" + local_name + "]: Received facts end."); //System.out.println("Node[" + local_name + "]: HAF: decision level after push = " + ctx.getDecisionLevel()); return propagateAfterBeingPushed(global_level, decision_level_before_push); } private ReplyMessage pushDerivedFacts(int global_level, int from_decision_level) { //System.out.println("Node[" + local_name +"]: pushDerivedFacts. from decision level = " + from_decision_level); long start_derive_new_facts = System.currentTimeMillis(); ArrayList<LinkedList<Pair<Node,Instance>>> new_facts = ctx.deriveNewFacts(); solving_time = solving_time + System.currentTimeMillis() - start_derive_new_facts; //System.out.println("Node[" + local_name +"]: PushDerivedFacts: required_predicates ="+required_predicates); //System.out.println("Node[" + local_name +"]: PushDerivedFacts: new_facts ="+new_facts); // collect newly derived instances for required facts HashMap<ANodeInterface,HashMap<Predicate,ArrayList<Instance>>> to_push = new HashMap<ANodeInterface, HashMap<Predicate, ArrayList<Instance>>>(); for (int dl= from_decision_level; dl < new_facts.size(); dl++) { LinkedList<Pair<Node,Instance>> added_in_dl = new_facts.get(dl); for (Pair<Node, Instance> pair : added_in_dl) { if( pair.getArg1().getClass().equals(BasicNode.class)) { Predicate pred = ((BasicNode)pair.getArg1()).getPred(); if( required_predicates.containsKey(pred)) { for (ANodeInterface other : required_predicates.get(pred)) { if(!to_push.containsKey(other)) to_push.put(other, new HashMap<Predicate, ArrayList<Instance>>()); if(!to_push.get(other).containsKey(pred)) to_push.get(other).put(pred, new ArrayList<Instance>()); to_push.get(other).get(pred).add(pair.getArg2()); } } } } } // collect all newly closed predicates HashMap<ANodeInterface,ArrayList<Predicate>> closed_preds =new HashMap<ANodeInterface, ArrayList<Predicate>>(); for (Entry<Predicate, ArrayList<ANodeInterface>> entry : required_predicates.entrySet()) { if( ctx.getRete().getBasicNodeMinus(entry.getKey()).isClosed() && !closed_predicates.contains(entry.getKey())) { closed_predicates.add(entry.getKey()); for (ANodeInterface aNodeInterface : entry.getValue()) { if(!closed_preds.containsKey(aNodeInterface) ) closed_preds.put(aNodeInterface, new ArrayList<Predicate>()); closed_preds.get(aNodeInterface).add(entry.getKey()); } } } for (ANodeInterface aNodeInterface : other_nodes.values()) { Map<Predicate,ArrayList<Instance>> in_facts = to_push.get(aNodeInterface); List<Predicate> closed_predicates = closed_preds.get(aNodeInterface); if( in_facts == null && closed_predicates == null ) { //try { // System.out.println("Node["+local_name+"]: Nothing to push for Node[" + aNodeInterface.getName() + "]."); //} catch (RemoteException ex) { // Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); continue; } try { //System.out.println("Node[" + local_name +"]: PushDerivedFacts: to Node[" + aNodeInterface.getName() + "]"); //System.out.println("Node[" + local_name +"]: PushDerivedFacts: closed_predicates = " + closed_predicates); //System.out.println("Node[" + local_name +"]: PushDerivedFacts: to_push = " + to_push); aNodeInterface.receiveNextFactsFrom(local_name); ReplyMessage reply = aNodeInterface.handleAddingFacts(global_level, in_facts, closed_predicates); if (reply == ReplyMessage.INCONSISTENT) { return ReplyMessage.INCONSISTENT; } } catch (RemoteException ex) { //try { // System.out.println("Node[" + local_name +"]: Exception in pushing derived facts to:"+aNodeInterface.getName()); //} catch (RemoteException ex1) { Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); } // Logger.getLogger(ANodeImpl.class.getName()).log(Level.SEVERE, null, ex); } return ReplyMessage.SUCCEEDED; } // only called by makeChoice or makeBranch private ReplyMessage makePropagation(int global_level) { long start_propagate = System.currentTimeMillis(); ctx.propagate(); solving_time = solving_time + System.currentTimeMillis() - start_propagate; if (ctx.isSatisfiable()) { return pushDerivedFacts(global_level, ctx.getDecisionLevel()); } else { return ReplyMessage.INCONSISTENT; } } @Override public ReplyMessage makeChoice(int global_level) throws RemoteException { long start_choice = System.currentTimeMillis(); int dc_before_choice = ctx.getDecisionLevel(); boolean has_choice = ctx.choice(); solving_time = solving_time + System.currentTimeMillis() - start_choice; if (has_choice) { //System.out.println("Node[" + local_name +"]: makeChoice. store(gl,dc_before_make_choice) = (" + global_level + "," + dc_before_choice +")"); global_to_local_dc.put(global_level, dc_before_choice); //System.out.println("Node[" + local_name +"]: makeChoice. now call makePropagation(" + global_level + ")"); return makePropagation(global_level); } else { //System.out.println("Node[" + local_name +"]: makeChoice. return NO_MORE_CHOICE"); return ReplyMessage.NO_MORE_CHOICE; } } @Override public ReplyMessage makeBranch(int global_level) throws RemoteException { long start_branch = System.currentTimeMillis(); int dc_before_branch = ctx.getDecisionLevel(); ReplyMessage has_branch = ctx.nextBranch(); solving_time = solving_time + System.currentTimeMillis() - start_branch; if (has_branch == ReplyMessage.HAS_BRANCH) { //System.out.println("Node[" + local_name +"]: makeBranch. store(gl,dc_before_make_branch) = (" + global_level + "," + dc_before_branch +")"); global_to_local_dc.put(global_level, dc_before_branch); //System.out.println("Node[" + local_name +"]: makeBranch. now call makePropagation(" + global_level + ")"); return makePropagation(global_level); } else { //System.out.println("Node[" + local_name +"]: makeBranch. return NO_MORE_BRANCH"); return ReplyMessage.NO_MORE_BRANCH; } } public static void main(String[] args) { String local_name = args[0]; String filename = args[1]; String filter; if (args.length == 3) { filter = args[2]; } else { filter = null; } //System.out.println("Node[" + local_name +"]: Starting NodeImpl.main(). args[0] = " + local_name); //System.out.println("Node[" + local_name +"]: Input file is: " + filename); // create and export the local node ANodeImpl local_node= new ANodeImpl(local_name, filename, filter); } @Override public ReplyMessage initGlobalLevelZero() throws RemoteException { //System.out.println("Node[" + local_name +"]: init zero global level to: " + ctx.getDecisionLevel()); global_to_local_dc.put(0, ctx.getDecisionLevel()); return ReplyMessage.SUCCEEDED; } }
package com.gravity.root; import java.util.Collection; import java.util.Iterator; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.GameState; import org.newdawn.slick.state.StateBasedGame; import com.gravity.levels.GameplayState; import com.gravity.levels.LevelInfo; public class GameLoaderState extends BasicGameState { public static final int ID = 0; private StateBasedGame game; private GameContainer container; private Collection<LevelInfo> levels; private int loadState = 0; private String loadString = "Writing the proposal..."; private int maxLogicUpdateInterval; private Iterator<LevelInfo> levelItr; private LevelInfo levelInfo; public GameLoaderState(Collection<LevelInfo> levels, int maxLogicUpdateInterval) { this.levels = levels; this.maxLogicUpdateInterval = maxLogicUpdateInterval; } @Override public void init(GameContainer container, StateBasedGame game) throws SlickException { this.loadState = 0; this.levelItr = levels.iterator(); this.levelInfo = levelItr.next(); this.game = game; this.container = container; this.loadString = "Getting research funding..."; } @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { g.drawString(loadString, 50, 50); } protected void updateLoadString() { switch (loadState) { case 0: loadString = "Setting up lab..."; break; case 1: loadString = "Making experiment: " + levelInfo.title + "..."; break; case 2: loadString = "Hiring lawyers..."; break; case 3: loadString = "Carving tombstones..."; break; case 4: loadString = "Buy bunny rewards..."; break; case 5: loadString = "Readying break room..."; break; case 6: loadString = "Finding exit strategy..."; break; case 7: loadString = "Starting grad student bunny raising pipeline..."; break; default: loadString = "Opening the lab..."; break; } } private void addState(GameState state) throws SlickException { game.addState(state); state.init(container, game); } @Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { boolean nextState = true; switch (loadState) { case 0: addState(new MainMenuState(levels.toArray(new LevelInfo[0]))); break; case 1: addState(new GameplayState(levelInfo.title, levelInfo.mapfile, levelInfo.stateId)); if (levelItr.hasNext()) { levelInfo = levelItr.next(); nextState = false; } break; case 2: addState(new CreditsState()); break; case 3: addState(new GameOverState()); break; case 4: addState(new GameWinState()); break; case 5: addState(new PauseState()); break; case 6: addState(new GameQuitState()); break; case 7: addState(new RestartGameplayState()); break; case 8: @SuppressWarnings("unused") // assignment so we can get the classloader to run the static code GameSounds.Event event = GameSounds.Event.BOUNCE; GameSounds.playBGM(); default: game.enterState(MainMenuState.ID); } if (nextState) { loadState++; } updateLoadString(); } @Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { container.setMaximumLogicUpdateInterval(0); } @Override public void leave(GameContainer container, StateBasedGame game) throws SlickException { container.setMaximumLogicUpdateInterval(maxLogicUpdateInterval); } @Override public int getID() { return ID; } }
package org.reactfx.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.IntFunction; public abstract class ListHelper<T> { public static <T> T get(ListHelper<T> listHelper, int index) { Lists.checkIndex(index, size(listHelper)); // always throws for listHelper == null return listHelper.get(index); } public static <T> ListHelper<T> add(ListHelper<T> listHelper, T elem) { if(listHelper == null) { return new SingleElemHelper<>(elem); } else { return listHelper.add(elem); } } public static <T> ListHelper<T> remove(ListHelper<T> listHelper, T elem) { if(listHelper == null) { return listHelper; } else { return listHelper.remove(elem); } } public static <T> void forEach(ListHelper<T> listHelper, Consumer<? super T> f) { if(listHelper != null) { listHelper.forEach(f); } } public static <T> void forEachBetween( ListHelper<T> listHelper, int from, int to, Consumer<? super T> f) { Lists.checkRange(from, to, size(listHelper)); if(from < to) { listHelper.forEachBetween(from, to, f); } } public static <T> Iterator<T> iterator(ListHelper<T> listHelper) { if(listHelper != null) { return listHelper.iterator(); } else { return Collections.emptyIterator(); } } public static <T> Iterator<T> iterator(ListHelper<T> listHelper, int from, int to) { Lists.checkRange(from, to, size(listHelper)); if(from < to) { return listHelper.iterator(from, to); } else { return Collections.emptyIterator(); } } public static <T> Optional<T> reduce(ListHelper<T> listHelper, BinaryOperator<T> f) { if(listHelper == null) { return Optional.empty(); } else { return listHelper.reduce(f); } } public static <T, U> U reduce(ListHelper<T> listHelper, U unit, BiFunction<U, T, U> f) { if(listHelper == null) { return unit; } else { return listHelper.reduce(unit, f); } } public static <T> T[] toArray(ListHelper<T> listHelper, IntFunction<T[]> allocator) { if(listHelper == null) { return allocator.apply(0); } else { return listHelper.toArray(allocator); } } public static <T> boolean isEmpty(ListHelper<T> listHelper) { return listHelper == null; } public static <T> int size(ListHelper<T> listHelper) { if(listHelper == null) { return 0; } else { return listHelper.size(); } } private ListHelper() { // private constructor to prevent subclassing }; abstract T get(int index); abstract ListHelper<T> add(T elem); abstract ListHelper<T> remove(T elem); abstract void forEach(Consumer<? super T> f); abstract void forEachBetween(int from, int to, Consumer<? super T> f); abstract Iterator<T> iterator(); abstract Iterator<T> iterator(int from, int to); abstract Optional<T> reduce(BinaryOperator<T> f); abstract <U> U reduce(U unit, BiFunction<U, T, U> f); abstract T[] toArray(IntFunction<T[]> allocator); abstract int size(); private static class SingleElemHelper<T> extends ListHelper<T> { private final T elem; SingleElemHelper(T elem) { this.elem = elem; } @Override T get(int index) { assert index == 0; return elem; } @Override ListHelper<T> add(T elem) { return new MultiElemHelper<>(this.elem, elem); } @Override ListHelper<T> remove(T elem) { if(Objects.equals(this.elem, elem)) { return null; } else { return this; } } @Override void forEach(Consumer<? super T> f) { f.accept(elem); } @Override void forEachBetween(int from, int to, Consumer<? super T> f) { assert from == 0 && to == 1; f.accept(elem); } @Override Iterator<T> iterator() { return new Iterator<T>() { boolean hasNext = true; @Override public boolean hasNext() { return hasNext; } @Override public T next() { if(hasNext) { hasNext = false; return elem; } else { throw new NoSuchElementException(); } } }; } @Override Iterator<T> iterator(int from, int to) { assert from == 0 && to == 1; return iterator(); } @Override Optional<T> reduce(BinaryOperator<T> f) { return Optional.of(elem); } @Override <U> U reduce(U unit, BiFunction<U, T, U> f) { return f.apply(unit, elem); } @Override T[] toArray(IntFunction<T[]> allocator) { T[] res = allocator.apply(1); res[0] = elem; return res; } @Override int size() { return 1; } } private static class MultiElemHelper<T> extends ListHelper<T> { private final List<T> elems; // when > 0, this ListHelper must be immutable, // i.e. use copy-on-write for mutating operations private int iterating = 0; @SafeVarargs MultiElemHelper(T... elems) { this(Arrays.asList(elems)); } private MultiElemHelper(List<T> elems) { this.elems = new ArrayList<>(elems); } private MultiElemHelper<T> copy() { return new MultiElemHelper<>(elems); } @Override T get(int index) { return elems.get(index); } @Override ListHelper<T> add(T elem) { if(iterating > 0) { return copy().add(elem); } else { elems.add(elem); return this; } } @Override ListHelper<T> remove(T elem) { int idx = elems.indexOf(elem); if(idx == -1) { return this; } else { switch(elems.size()) { case 0: // fall through case 1: throw new AssertionError(); case 2: return new SingleElemHelper<>(elems.get(1-idx)); default: if(iterating > 0) { return copy().remove(elem); } else { elems.remove(elem); return this; } } } } @Override void forEach(Consumer<? super T> f) { ++iterating; try { elems.forEach(f); } finally { --iterating; } } @Override void forEachBetween(int from, int to, Consumer<? super T> f) { ++iterating; try { elems.subList(from, to).forEach(f); } finally { --iterating; } } @Override Iterator<T> iterator() { return iterator(0, elems.size()); } @Override Iterator<T> iterator(int from, int to) { assert from < to; ++iterating; return new Iterator<T>() { int next = from; @Override public boolean hasNext() { return next < to; } @Override public T next() { if(next < to) { T res = elems.get(next); ++next; if(next == to) { --iterating; } return res; } else { throw new NoSuchElementException(); } } }; } @Override Optional<T> reduce(BinaryOperator<T> f) { return elems.stream().reduce(f); } @Override <U> U reduce(U unit, BiFunction<U, T, U> f) { U u = unit; for(T elem: elems) { u = f.apply(u, elem); } return u; } @Override T[] toArray(IntFunction<T[]> allocator) { return elems.toArray(allocator.apply(size())); } @Override int size() { return elems.size(); } } }
package no.hvl.dat104.util; import javax.servlet.http.HttpServletRequest; import no.hvl.dat104.dataaccess.IDeltagerEAO; import no.hvl.dat104.model.DeltagerEntity; /** * @author krist * */ public class DeltagerUtil { /** * Henter input fra skjema, validerer nummeret og henter deltageren hvis den * finnes i databasen * * @param request * @param deltagerEAO * @return Null eller en deltager */ public static DeltagerEntity hentDeltager(HttpServletRequest request, IDeltagerEAO deltagerEAO) { String nummer = ValideringUtil.escapeHTML((String) request.getParameter("password")); if (!ValideringUtil.validerNummer(nummer)) { return null; } return deltagerEAO.finnDeltager(Integer.parseInt(nummer)); } public static void leggTilDeltager(HttpServletRequest request, IDeltagerEAO deltagerEAO) { String fornavn = ValideringUtil.escapeHTML(request.getParameter("fornavn")); String etternavn = ValideringUtil.escapeHTML(request.getParameter("etternavn")); String mobil = ValideringUtil.escapeHTML(request.getParameter("mobil")); String kjoenn = ValideringUtil.escapeHTML(request.getParameter("kjoenn")); boolean erMann = kjoenn.equals("mann") ? true : false; if (ValideringUtil.validerFornavn(fornavn) && ValideringUtil.validerEtternavn(etternavn) && ValideringUtil.validerNummer(mobil)) { DeltagerEntity d = new DeltagerEntity(Integer.parseInt(mobil), fornavn, etternavn, erMann, false, false); deltagerEAO.leggTilDeltager(d); } } }
package share.manager.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import android.os.Environment; import android.util.Pair; public class FileWriter { static private final String filename="portfolio.txt", directoryName = "ShareManager"; static private final File directory=null; static private FileOutputStream fileOutStream; static public ArrayList<Pair<String,Integer> >readFile() { ArrayList<Pair<String,Integer> > arr=new ArrayList<Pair<String,Integer> >(); Pair<String,Integer> row=null; getFileStream(); File file = new File(directory, filename); String scan; if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { } } FileReader fileReader = null; try { fileReader = new FileReader(file); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader br = new BufferedReader(fileReader); try { while ((scan = br.readLine()) != null) { row=new Pair<String, Integer>(scan.split("-.-")[0],Integer.getInteger(scan.split("-.-")[1]) ); arr.add(row); } } catch (IOException e) { e.printStackTrace(); } try { br.close(); } catch (IOException e) { e.printStackTrace(); } return arr; } static private void createFile() { /*String toWrite = "Ticket purchased in "; toWrite += new Date() + " by " + username + '\n'; try { fileOutStream.write(toWrite.getBytes()); } catch (IOException e) { e.printStackTrace(); }*/ } static public void writeToFile() { String toWrite = "Ticket validated in "; toWrite += "\n"; try { fileOutStream.write(toWrite.getBytes()); } catch (IOException e) { e.printStackTrace(); } } static public void getFileStream() { File directory = getAlbumStorageDir(directoryName); File file = new File(directory, filename); fileOutStream = null; try { fileOutStream = new FileOutputStream(file); } catch (FileNotFoundException e) { createFile(); } } static private File getAlbumStorageDir(String filename) { File file = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS), filename); if (!file.mkdirs()) { } return file; } }
package com.plugin.core; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.content.res.Resources; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import com.plugin.content.PluginDescriptor; import com.plugin.content.PluginIntentFilter; import com.plugin.core.manager.PluginCallbackImpl; import com.plugin.core.manager.PluginManagerImpl; import com.plugin.core.manager.PluginCallback; import com.plugin.core.manager.PluginManager; import com.plugin.util.LogUtil; import com.plugin.util.ManifestParser; import com.plugin.util.FileUtil; import com.plugin.util.PackageVerifyer; import com.plugin.util.RefInvoker; import dalvik.system.DexClassLoader; public class PluginLoader { private static final boolean needVefifyCert = true; private static Application sApplication; private static Object activityThread; private static PluginManager pluginManager; private static PluginCallback changeListener; private static boolean isInited = false; private PluginLoader() { } /** * loader, * * @param app */ public static synchronized void initLoader(Application app, PluginManager manager) { if (!isInited) { LogUtil.d("..."); isInited = true; sApplication = app; initApplicationBaseContext(); initActivityThread(); injectInstrumentation(); injectHandlerCallback(); pluginManager = manager; pluginManager.loadInstalledPlugins(); changeListener = new PluginCallbackImpl(); changeListener.onPluginLoaderInited(); LogUtil.d(""); } } public static synchronized void initLoader(Application app) { initLoader(app, new PluginManagerImpl()); } public static Application getApplicatoin() { return sApplication; } /** * ApplicationmBasestartactivitystartservicesendbroadcast */ private static void initApplicationBaseContext() { LogUtil.d("Application baseContext"); Context base = (Context)RefInvoker.getFieldObject(sApplication, ContextWrapper.class.getName(), "mBase"); Context newBase = new PluginBaseContextWrapper(base); RefInvoker.setFieldObject(sApplication, ContextWrapper.class.getName(), "mBase", newBase); } private static void initActivityThread() { // ThreadLocal LogUtil.d("ActivityThread"); activityThread = RefInvoker.invokeStaticMethod("android.app.ActivityThread", "currentActivityThread", (Class[]) null, (Object[]) null); } /*package*/ static Object getActivityThread() { return activityThread; } /** * InstrumentationActivity */ private static void injectInstrumentation() { // Instrumentationapi LogUtil.d("Intstrumentation"); Instrumentation originalInstrumentation = (Instrumentation) RefInvoker.getFieldObject(activityThread, "android.app.ActivityThread", "mInstrumentation"); RefInvoker.setFieldObject(activityThread, "android.app.ActivityThread", "mInstrumentation", new PluginInstrumentionWrapper(originalInstrumentation)); } private static void injectHandlerCallback() { LogUtil.d(""); // getHandler Handler handler = (Handler) RefInvoker.invokeMethod(activityThread, "android.app.ActivityThread", "getHandler", (Class[])null, (Object[])null); //api16 //Handler handler = (Handler) RefInvoker.getStaticFieldObject("android.app.ActivityThread", "sMainThreadHandler"); // handlercallback RefInvoker.setFieldObject(handler, Handler.class.getName(), "mCallback", new PluginAppTrace(handler)); } public static boolean isInstalled(String pluginId, String pluginVersion) { PluginDescriptor pluginDescriptor = getPluginDescriptorByPluginId(pluginId); if (pluginDescriptor != null) { return pluginDescriptor.getVersion().equals(pluginVersion); } return false; } /** * * * @param srcPluginFile * @return */ public static synchronized boolean installPlugin(String srcPluginFile) { LogUtil.d("", srcPluginFile); //0apk //TODO XXX // 1APK //sApplication.getPackageManager().getPackageArchiveInfo(srcPluginFile, PackageManager.GET_SIGNATURES); Signature[] pluginSignatures = PackageVerifyer.collectCertificates(srcPluginFile, false); boolean isDebugable = (0 != (sApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)); if (pluginSignatures == null) { LogUtil.e("", srcPluginFile); return false; } else if (needVefifyCert && isDebugable) { //APK Signature[] mainSignatures = null; try { PackageInfo pkgInfo = sApplication.getPackageManager().getPackageInfo(sApplication.getPackageName(), PackageManager.GET_SIGNATURES); mainSignatures = pkgInfo.signatures; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (!PackageVerifyer.isSignaturesSame(mainSignatures, pluginSignatures)) { LogUtil.d("", srcPluginFile); return false; } } // 2Manifest PluginDescriptor pluginDescriptor = ManifestParser.parseManifest(srcPluginFile); if (pluginDescriptor == null || TextUtils.isEmpty(pluginDescriptor.getPackageName())) { LogUtil.d("Manifest", srcPluginFile); return false; } PluginDescriptor oldPluginDescriptor = getPluginDescriptorByPluginId(pluginDescriptor.getPackageName()); if (oldPluginDescriptor != null) { remove(pluginDescriptor.getPackageName()); } String destPluginFile = genInstallPath(pluginDescriptor.getPackageName(), pluginDescriptor.getVersion()); boolean isCopySuccess = FileUtil.copyFile(srcPluginFile, destPluginFile); if (isCopySuccess) { //5soso, Dexclassloaderso File tempDir = new File(new File(destPluginFile).getParentFile(), "temp"); Set<String> soList = FileUtil.unZipSo(srcPluginFile, tempDir); if (soList != null) { for (String soName : soList) { FileUtil.copySo(tempDir, soName, new File(destPluginFile).getParent() + File.separator + "lib"); } } pluginDescriptor.setInstalledPath(destPluginFile); boolean isInstallSuccess = pluginManager.addOrReplace(pluginDescriptor); if (isInstallSuccess) { changeListener.onPluginInstalled(pluginDescriptor.getPackageName(), pluginDescriptor.getVersion()); LogUtil.d("", srcPluginFile); return true; } } else { LogUtil.d("", srcPluginFile); } LogUtil.d("", srcPluginFile); return false; } /** * classIdclass * * @param clazzId * @return */ @SuppressWarnings("rawtypes") public static Class loadPluginClassById(String clazzId) { LogUtil.d("loadPluginClass for clazzId ", clazzId); PluginDescriptor pluginDescriptor = getPluginDescriptorByFragmenetId(clazzId); if (pluginDescriptor != null) { DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader(); if (pluginClassLoader == null) { initPlugin(pluginDescriptor); pluginClassLoader = pluginDescriptor.getPluginClassLoader(); } if (pluginClassLoader != null) { String clazzName = pluginDescriptor.getPluginClassNameById(clazzId); LogUtil.d("loadPluginClass clazzName=", clazzName); if (clazzName != null) { try { Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName); LogUtil.d("loadPluginClass for classId ", clazzId, " Success"); return pluginClazz; } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } LogUtil.d("loadPluginClass for classId ", clazzId, " Fail"); return null; } @SuppressWarnings("rawtypes") public static Class loadPluginClassByName(String clazzName) { LogUtil.d("loadPluginClass for clazzName ", clazzName); PluginDescriptor pluginDescriptor = getPluginDescriptorByClassName(clazzName); if (pluginDescriptor != null) { DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader(); if (pluginClassLoader == null) { initPlugin(pluginDescriptor); pluginClassLoader = pluginDescriptor.getPluginClassLoader(); } if (pluginClassLoader != null) { try { Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName); LogUtil.d("loadPluginClass Success for clazzName ", clazzName); return pluginClazz; } catch (ClassNotFoundException e) { e.printStackTrace(); } } } LogUtil.d("loadPluginClass Fail for clazzName ", clazzName); return null; } /** * classContext 1DefaultContext,classContext * * @param clazz * @return */ public static Context getDefaultPluginContext(@SuppressWarnings("rawtypes") Class clazz) { // clazz.getClassLoader(); classloader // classloaderloader Context pluginContext = null; PluginDescriptor pluginDescriptor = getPluginDescriptorByClassName(clazz.getName()); if (pluginDescriptor != null) { pluginContext = pluginDescriptor.getPluginContext(); } else { LogUtil.d("PluginDescriptor Not Found for ", clazz.getName()); } if (pluginContext == null) { LogUtil.d("Context Not Found for ", clazz.getName()); } return pluginContext; } /** * classContext classcontext * ActivityActivityContext * * @param clazz * @return */ public static Context getNewPluginContext(@SuppressWarnings("rawtypes") Class clazz) { Context pluginContext = getDefaultPluginContext(clazz); if (pluginContext != null) { pluginContext = PluginCreator.createPluginApplicationContext(((PluginContextTheme)pluginContext).getPluginDescriptor(), sApplication, pluginContext.getResources(), (DexClassLoader) pluginContext.getClassLoader()); pluginContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme); } return pluginContext; } /** * * * @param */ private static void initPlugin(PluginDescriptor pluginDescriptor) { LogUtil.d("Resources, DexClassLoader, Context, Application "); LogUtil.d("", pluginDescriptor.isStandalone()); Resources pluginRes = PluginCreator.createPluginResource(sApplication, pluginDescriptor.getInstalledPath(), pluginDescriptor.isStandalone()); DexClassLoader pluginClassLoader = PluginCreator.createPluginClassLoader(pluginDescriptor.getInstalledPath(), pluginDescriptor.isStandalone()); Context pluginContext = PluginCreator .createPluginApplicationContext(pluginDescriptor, sApplication, pluginRes, pluginClassLoader); pluginContext.setTheme(sApplication.getApplicationContext().getApplicationInfo().theme); pluginDescriptor.setPluginContext(pluginContext); pluginDescriptor.setPluginClassLoader(pluginClassLoader); //openAtlasExtentionPublic.xml //checkPluginPublicXml(pluginDescriptor, pluginRes); callPluginApplicationOncreate(pluginDescriptor); LogUtil.d("" + pluginDescriptor.getPackageName() + ""); } private static void callPluginApplicationOncreate(PluginDescriptor pluginDescriptor) { Application application = null; if (pluginDescriptor.getApplicationName() != null && pluginDescriptor.getPluginApplication() == null && pluginDescriptor.getPluginClassLoader() != null) { try { application = new Instrumentation().newApplication(pluginDescriptor.getPluginClassLoader(), pluginDescriptor.getApplicationName(), sApplication); pluginDescriptor.setPluginApplication(application); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } LogUtil.d("ContextProvider", pluginDescriptor.getProviderInfos().size()); PluginContentProviderInstaller.installContentProviders(sApplication, pluginDescriptor.getProviderInfos().values()); if (application != null) { application.onCreate(); } changeListener.onPluginStarted(pluginDescriptor.getPackageName()); } /** * for eclipse with public.xml * * unused * @param pluginDescriptor * @param res * @return */ private static boolean checkPluginPublicXml(PluginDescriptor pluginDescriptor, Resources res) { // "plugin_layout_1"idpublic.xml // public.xml, int publicStub = res.getIdentifier("plugin_layout_1", "layout", pluginDescriptor.getPackageName()); if (publicStub == 0) { publicStub = res.getIdentifier("plugin_layout_1", "layout", sApplication.getPackageName()); } if (publicStub == 0) { try { Class layoutClass = ((ClassLoader) pluginDescriptor.getPluginClassLoader()).loadClass(pluginDescriptor .getPackageName() + ".R$layout"); Integer layouId = (Integer) RefInvoker.getFieldObject(null, layoutClass, "plugin_layout_1"); if (layouId != null) { publicStub = layouId; } } catch (ClassNotFoundException e) { e.printStackTrace(); } } if (publicStub == 0) { throw new IllegalStateException("\npublic.xmlid\n" + "public.xmlid\n" + "public.xmlid\n" + ""); } return true; } /** * class,class */ public static synchronized void removeAll() { boolean isSuccess = pluginManager.removeAll(); if (isSuccess) { changeListener.onPluginRemoveAll(); } } public static synchronized void remove(String pluginId) { boolean isSuccess = pluginManager.remove(pluginId); if (isSuccess) { changeListener.onPluginRemoved(pluginId); } } @SuppressWarnings("unchecked") public static Collection<PluginDescriptor> getPlugins() { return pluginManager.getPlugins(); } /** * for Fragment * * @param clazzId * @return */ public static PluginDescriptor getPluginDescriptorByFragmenetId(String clazzId) { return pluginManager.getPluginDescriptorByFragmenetId(clazzId); } public static PluginDescriptor getPluginDescriptorByPluginId(String pluginId) { return pluginManager.getPluginDescriptorByPluginId(pluginId); } public static PluginDescriptor getPluginDescriptorByClassName(String clazzName) { return pluginManager.getPluginDescriptorByClassName(clazzName); } public static synchronized void enablePlugin(String pluginId, boolean enable) { pluginManager.enablePlugin(pluginId, enable); } /** * //If getComponent returns an explicit class, that is returned without any * further consideration. //If getAction is non-NULL, the activity must * handle this action. //If resolveType returns non-NULL, the activity must * handle this type. //If addCategory has added any categories, the activity * must handle ALL of the categories specified. //If getPackage is non-NULL, * only activity components in that application package will be considered. * * @param intent * @return */ public static String isMatchPlugin(Intent intent) { Iterator<PluginDescriptor> itr = getPlugins().iterator(); while (itr.hasNext()) { PluginDescriptor plugin = itr.next(); if (intent.getComponent() != null) { if (plugin.containsName(intent.getComponent().getClassName())) { return intent.getComponent().getClassName(); } } else { // IntentFilter String clazzName = findClassNameByIntent(intent, plugin.getActivitys()); if (clazzName == null) { clazzName = findClassNameByIntent(intent, plugin.getServices()); } if (clazzName == null) { clazzName = findClassNameByIntent(intent, plugin.getReceivers()); } if (clazzName != null) { return clazzName; } } } return null; } /** * activity or service or broadcast * @param intent * @return */ public static int getTargetType(Intent intent) { Iterator<PluginDescriptor> itr = getPlugins().iterator(); while (itr.hasNext()) { PluginDescriptor plugin = itr.next(); if (intent.getComponent() != null) { if (plugin.containsName(intent.getComponent().getClassName())) { return plugin.getType(intent.getComponent().getClassName()); } } else { String clazzName = findClassNameByIntent(intent, plugin.getActivitys()); if (clazzName == null) { clazzName = findClassNameByIntent(intent, plugin.getServices()); } if (clazzName == null) { clazzName = findClassNameByIntent(intent, plugin.getReceivers()); } if (clazzName != null) { return plugin.getType(clazzName); } } } return PluginDescriptor.UNKOWN; } private static String findClassNameByIntent(Intent intent, HashMap<String, ArrayList<PluginIntentFilter>> intentFilter) { if (intentFilter != null) { Iterator<Entry<String, ArrayList<PluginIntentFilter>>> entry = intentFilter.entrySet().iterator(); while (entry.hasNext()) { Entry<String, ArrayList<PluginIntentFilter>> item = entry.next(); Iterator<PluginIntentFilter> values = item.getValue().iterator(); while (values.hasNext()) { PluginIntentFilter filter = values.next(); int result = filter.match(intent.getAction(), intent.getType(), intent.getScheme(), intent.getData(), intent.getCategories()); if (result != PluginIntentFilter.NO_MATCH_ACTION && result != PluginIntentFilter.NO_MATCH_CATEGORY && result != PluginIntentFilter.NO_MATCH_DATA && result != PluginIntentFilter.NO_MATCH_TYPE) { return item.getKey(); } } } } return null; } /** * , apk */ private static String genInstallPath(String pluginId, String pluginVersoin) { return sApplication.getDir("plugin_dir", Context.MODE_PRIVATE).getAbsolutePath() + "/" + pluginId + "/" + pluginVersoin + ".apk"; } }
package omniSpectrum.Quizzium.DAL; import java.io.Serializable; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.DetachedCriteria; public abstract class GenericDao<T, PK extends Serializable> implements IGenericDao<T, PK> { private SessionFactory sessionFactory; protected final Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } @Override public PK save(T newInstance) { return (PK) getCurrentSession().save(newInstance); } @Override public void update(T transientObject) { // TODO Auto-generated method stub getCurrentSession().update(transientObject); } @Override public void saveOrUpdate(T transientObject) { // TODO Auto-generated method stub getCurrentSession().saveOrUpdate(transientObject); } @Override public void delete(T persistentObject) { // TODO Auto-generated method stub getCurrentSession().delete(persistentObject); } @Override public T findById(PK id) { return (T) getCurrentSession().get(getEntityClass(), id); } @Override public List<T> findAll() { // TODO Auto-generated method stub return null; } @Override public List<T> findByProperty(String propertyName, Object value) { // TODO Auto-generated method stub return null; } protected abstract Class<T> getEntityClass(); protected DetachedCriteria createDetachedCriteria() { return DetachedCriteria.forClass(getEntityClass()); }; }
package outbackcdx; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import outbackcdx.NanoHTTPD.Response; import outbackcdx.WbCdxApi.JsonFormat; import outbackcdx.WbCdxApi.OutputFormat; import outbackcdx.WbCdxApi.TextFormat; import outbackcdx.auth.Permission; import javax.xml.stream.XMLStreamException; import java.io.*; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.lang.System.out; import static java.nio.charset.StandardCharsets.UTF_8; import static outbackcdx.Json.GSON; import static outbackcdx.NanoHTTPD.Method.*; import static outbackcdx.NanoHTTPD.Response.Status.*; import static outbackcdx.Web.*; import org.rocksdb.TransactionLogIterator; import org.rocksdb.TransactionLogIterator.BatchResult; class Webapp implements Web.Handler { private final boolean verbose; private final DataStore dataStore; private final Web.Router router; private final Map<String,Object> dashboardConfig; private Response configJson(Web.Request req) { return jsonResponse(dashboardConfig); } private Response listAccessPolicies(Web.Request req) throws IOException, Web.ResponseException { return jsonResponse(getIndex(req).accessControl.listPolicies()); } private Response deleteAccessRule(Web.Request req) throws IOException, Web.ResponseException, RocksDBException { long ruleId = Long.parseLong(req.param("ruleId")); boolean found = getIndex(req).accessControl.deleteRule(ruleId); return found ? ok() : notFound(); } Webapp(DataStore dataStore, boolean verbose, Map<String, Object> dashboardConfig) { this.dataStore = dataStore; this.verbose = verbose; this.dashboardConfig = dashboardConfig; router = new Router(); router.on(GET, "/", serve("dashboard.html")); router.on(GET, "/api", serve("api.html")); router.on(GET, "/api.js", serve("api.js")); router.on(GET, "/add.svg", serve("add.svg")); router.on(GET, "/database.svg", serve("database.svg")); router.on(GET, "/outback.svg", serve("outback.svg")); router.on(GET, "/favicon.ico", serve("outback.svg")); router.on(GET, "/swagger.json", serve("swagger.json")); router.on(GET, "/lib/vue-router/2.0.0/vue-router.js", serve("lib/vue-router/2.0.0/vue-router.js")); router.on(GET, "/lib/vue/2.0.1/vue.js", serve("/META-INF/resources/webjars/vue/2.0.1/dist/vue.js")); router.on(GET, "/lib/lodash/4.15.0/lodash.min.js", serve("/META-INF/resources/webjars/lodash/4.15.0/lodash.min.js")); router.on(GET, "/lib/moment/2.15.2/moment.min.js", serve("/META-INF/resources/webjars/moment/2.15.2/min/moment.min.js")); router.on(GET, "/lib/pikaday/1.4.0/pikaday.js", serve("/META-INF/resources/webjars/pikaday/1.4.0/pikaday.js")); router.on(GET, "/lib/pikaday/1.4.0/pikaday.css", serve("/META-INF/resources/webjars/pikaday/1.4.0/css/pikaday.css")); router.on(GET, "/lib/redoc/1.4.1/redoc.min.js", serve("/META-INF/resources/webjars/redoc/1.4.1/dist/redoc.min.js")); router.on(GET, "/api/collections", request1 -> listCollections(request1)); router.on(GET, "/config.json", req1 -> configJson(req1)); router.on(GET, "/<collection>", request -> query(request)); router.on(POST, "/<collection>", request -> post(request), Permission.INDEX_EDIT); router.on(POST, "/<collection>/delete", request -> delete(request), Permission.INDEX_EDIT); router.on(GET, "/<collection>/stats", req2 -> stats(req2)); router.on(GET, "/<collection>/captures", request -> captures(request)); router.on(GET, "/<collection>/aliases", request -> aliases(request)); router.on(GET, "/<collection>/changes", request -> changeFeed(request)); if (FeatureFlags.experimentalAccessControl()) { router.on(GET, "/<collection>/ap/<accesspoint>", request -> query(request)); router.on(GET, "/<collection>/ap/<accesspoint>/check", request1 -> checkAccess(request1)); router.on(POST, "/<collection>/ap/<accesspoint>/check", request -> checkAccessBulk(request)); router.on(GET, "/<collection>/access/rules", request -> listAccessRules(request)); router.on(POST, "/<collection>/access/rules", request -> postAccessRules(request), Permission.RULES_EDIT); router.on(GET, "/<collection>/access/rules/new", request1 -> getNewAccessRule(request1), Permission.RULES_EDIT); router.on(GET, "/<collection>/access/rules/<ruleId>", req -> getAccessRule(req)); router.on(DELETE, "/<collection>/access/rules/<ruleId>", req1 -> deleteAccessRule(req1), Permission.RULES_EDIT); router.on(GET, "/<collection>/access/policies", req1 -> listAccessPolicies(req1)); router.on(POST, "/<collection>/access/policies", request -> postAccessPolicy(request), Permission.POLICIES_EDIT); router.on(GET, "/<collection>/access/policies/<policyId>", req -> getAccessPolicy(req)); router.on(POST, "/<collection>/truncate_replication", request -> flushWal(request)); } } Response flushWal(Web.Request request) throws Web.ResponseException, IOException, RocksDBException{ Index index = getIndex(request); index.flushWal(); Map<String,Boolean> map = new HashMap<>(); map.put("success", true); return jsonResponse(map); } Response listCollections(Web.Request request) { return jsonResponse(dataStore.listCollections()); } Response stats(Web.Request req) throws IOException, Web.ResponseException { Index index = getIndex(req); Map<String,Object> map = new HashMap<>(); map.put("estimatedRecordCount", index.estimatedRecordCount()); Response response = new Response(Response.Status.OK, "application/json", GSON.toJson(map)); response.addHeader("Access-Control-Allow-Origin", "*"); return response; } Response captures(Web.Request request) throws IOException, Web.ResponseException { Index index = getIndex(request); String key = request.param("key", ""); long limit = Long.parseLong(request.param("limit", "1000")); List<Capture> results = StreamSupport.stream(index.capturesAfter(key).spliterator(), false) .limit(limit) .collect(Collectors.<Capture>toList()); return jsonResponse(results); } Response aliases(Web.Request request) throws IOException, Web.ResponseException { Index index = getIndex(request); String key = request.param("key", ""); long limit = Long.parseLong(request.param("limit", "1000")); List<Alias> results = StreamSupport.stream(index.listAliases(key).spliterator(), false) .limit(limit) .collect(Collectors.<Alias>toList()); return jsonResponse(results); } Response delete(Web.Request request) throws IOException { String collection = request.param("collection"); final Index index = dataStore.getIndex(collection); BufferedReader in = new BufferedReader(new InputStreamReader(request.inputStream())); long deleted = 0; try (Index.Batch batch = index.beginUpdate()) { while (true) { String line = in.readLine(); if (verbose) { out.println("DELETE " + line); } if (line == null) break; if (line.startsWith(" CDX")) continue; try { if (line.startsWith("@alias ")) { throw new UnsupportedOperationException("Deleting of aliases is not yet implemented"); } batch.deleteCapture(Capture.fromCdxLine(line)); deleted++; } catch (Exception e) { return new Response(BAD_REQUEST, "text/plain", "At line: " + line + "\n" + formatStackTrace(e)); } } batch.commit(); } return new Response(OK, "text/plain", "Deleted " + deleted + " records\n"); } Response post(Web.Request request) throws IOException { String collection = request.param("collection"); final Index index = dataStore.getIndex(collection, true); BufferedReader in = new BufferedReader(new InputStreamReader(request.inputStream())); long added = 0; try (Index.Batch batch = index.beginUpdate()) { while (true) { String line = in.readLine(); if (verbose) { out.println(line); } if (line == null) break; if (line.startsWith(" CDX")) continue; try { if (line.startsWith("@alias ")) { String[] fields = line.split(" "); String aliasSurt = UrlCanonicalizer.surtCanonicalize(fields[1]); String targetSurt = UrlCanonicalizer.surtCanonicalize(fields[2]); batch.putAlias(aliasSurt, targetSurt); } else { batch.putCapture(Capture.fromCdxLine(line)); } added++; } catch (Exception e) { return new Response(BAD_REQUEST, "text/plain", "At line: " + line + "\n" + formatStackTrace(e)); } } batch.commit(); } return new Response(OK, "text/plain", "Added " + added + " records\n"); } private String formatStackTrace(Exception e) { StringWriter stacktrace = new StringWriter(); e.printStackTrace(new PrintWriter(stacktrace)); return stacktrace.toString(); } Response changeFeed(Web.Request request) throws Web.ResponseException, IOException { String collection = request.param("collection"); long since = Long.parseLong(request.param("since")); final Index index = getIndex(request); TransactionLogIterator logReader = index.getUpdatesSince(since); if(verbose) { out.println(String.format("Received request %s. Retrieved deltas for collection <%s> since sequenceNumber %s", request, collection, since)); } Response response = new Response(OK, "application/json", outputStream -> { JsonWriter output = GSON.newJsonWriter(new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8))); output.beginArray(); while (logReader.isValid()) { BatchResult batch = logReader.getBatch(); // only return results _after_ the 'since' number if((Long) batch.sequenceNumber() < since){ continue; } output.beginObject(); output.name("sequenceNumber").value(((Long) batch.sequenceNumber()).toString()); String base64WriteBatch; try { base64WriteBatch = Base64.getEncoder().encodeToString(batch.writeBatch().data()); } catch (RocksDBException e) { throw new IOException(e); } output.name("writeBatch").value(base64WriteBatch); output.endObject(); logReader.next(); } output.endArray(); output.flush(); }); response.addHeader("Access-Control-Allow-Origin", "*"); return response; } Response query(Web.Request request) throws IOException, Web.ResponseException { if (verbose) { out.println(request); } Index index = getIndex(request); Map<String,String> params = request.params(); if (params.containsKey("q")) { return XmlQuery.query(request, index); } else if (params.containsKey("url")) { return WbCdxApi.query(request, index); } else { return collectionDetails(index.db); } } private Index getIndex(Web.Request request) throws IOException, Web.ResponseException { String collection = request.param("collection"); final Index index = dataStore.getIndex(collection); if (index == null) { throw new Web.ResponseException(new Response(NOT_FOUND, "text/plain", "Collection does not exist")); } return index; } private Response collectionDetails(RocksDB db) { String page = "<form>URL: <input name=url type=url><button type=submit>Query</button></form>\n<pre>"; try { page += db.getProperty("rocksdb.stats"); page += "\nEstimated number of records: " + db.getLongProperty("rocksdb.estimate-num-keys"); } catch (RocksDBException e) { page += e.toString(); e.printStackTrace(); } return new Response(OK, "text/html", page); } private <T> T fromJson(Web.Request request, Class<T> clazz) { return GSON.fromJson(new InputStreamReader(request.inputStream(), UTF_8), clazz); } private Response getAccessPolicy(Web.Request req) throws IOException, Web.ResponseException { long policyId = Long.parseLong(req.param("policyId")); AccessPolicy policy = getIndex(req).accessControl.policy(policyId); if (policy == null) { return notFound(); } return jsonResponse(policy); } private Response postAccessPolicy(Web.Request request) throws IOException, Web.ResponseException, RocksDBException { AccessPolicy policy = fromJson(request, AccessPolicy.class); Long id = getIndex(request).accessControl.put(policy); return id == null ? ok() : created(id); } private Response postAccessRules(Web.Request request) throws IOException, Web.ResponseException, RocksDBException { AccessControl accessControl = getIndex(request).accessControl; // parse rules List<AccessRule> rules; boolean single = false; if ("application/xml".equals(request.header("content-type"))) { try { rules = AccessRuleXml.parseRules(request.inputStream()); } catch (XMLStreamException e) { return new Response(BAD_REQUEST, "text/plain", formatStackTrace(e)); } } else { // JSON format JsonReader reader = GSON.newJsonReader(new InputStreamReader(request.inputStream(), UTF_8)); if (reader.peek() == JsonToken.BEGIN_ARRAY) { reader.beginArray(); rules = new ArrayList<>(); while (reader.hasNext()) { AccessRule rule = GSON.fromJson(reader, AccessRule.class); rules.add(rule); } reader.endArray(); } else { // single rule rules = Arrays.asList((AccessRule)GSON.fromJson(reader, AccessRule.class)); single = true; } } // validate rules List<AccessRuleError> errors = new ArrayList<>(); for (AccessRule rule: rules) { errors.addAll(rule.validate()); } // return an error response if any failed if (!errors.isEmpty()) { Response response = jsonResponse(errors); response.setStatus(BAD_REQUEST); return response; } // save all the rules List<Long> ids = new ArrayList<>(); for (AccessRule rule : rules) { ids.add(accessControl.put(rule, request.username())); } // return successful response if (single) { Long id = ids.get(0); return id == null ? ok() : created(id); } else { return jsonResponse(ids); } } private Response ok() { return new Response(OK, null, ""); } private Response created(long id) { Map<String,String> map = new HashMap<>(); map.put("id", Long.toString(id)); return new Response(CREATED, "application/json", GSON.toJson(map)); } private Response getAccessRule(Web.Request req) throws IOException, Web.ResponseException, RocksDBException { Index index = getIndex(req); Long ruleId = Long.parseLong(req.param("ruleId")); AccessRule rule = index.accessControl.rule(ruleId); if (rule == null) { return notFound(); } return jsonResponse(rule); } private Response getNewAccessRule(Web.Request request) { AccessRule rule = new AccessRule(); return jsonResponse(rule); } private Response listAccessRules(Web.Request request) throws IOException, Web.ResponseException { Index index = getIndex(request); // search filter String search = request.param("search"); List<AccessRule> rules = new ArrayList<>(); for (AccessRule rule : index.accessControl.list()) { if (search == null || rule.contains(search)) { rules.add(rule); } } // sort rules String sort = request.param("sort", "id"); if (sort.replaceFirst("^-", "").equals("surt")) { Comparator<AccessRule> cmp = Comparator.comparingInt(rule -> rule.pinned ? 0 : 1); cmp = cmp.thenComparing(rule -> rule.ssurtPrefixes().findFirst().orElse("")); cmp = cmp.thenComparingLong(rule -> rule.id); rules.sort(cmp); } if (sort.startsWith("-")) { Collections.reverse(rules); } // output format String type; String extension; RuleFormatter formatter; if (request.param("output", "json").equals("csv")) { type = "text/csv"; extension = "csv"; formatter = AccessRule::toCSV; } else { type = "application/json"; extension = "json"; formatter = AccessRule::toJSON; } Response response = new Response(OK, type, out -> { try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, UTF_8))) { formatter.format(rules, policyId -> index.accessControl.policy(policyId).name, bw); } }); String filename = index.name.replace("\"", "") + "-access-rules." + extension; response.addHeader("Content-Disposition", "filename=\"" + filename + "\""); return response; } private interface RuleFormatter { void format(Collection<AccessRule> rules, Function<Long,String> policyNames, Writer out) throws IOException; } Response checkAccess(Web.Request request) throws IOException, ResponseException { String accesspoint = request.param("accesspoint"); String url = request.mandatoryParam("url"); String timestamp = request.mandatoryParam("timestamp"); Date captureTime = Date.from(LocalDateTime.parse(timestamp, Capture.arcTimeFormat).toInstant(ZoneOffset.UTC)); Date accessTime = new Date(); return jsonResponse(getIndex(request).accessControl.checkAccess(accesspoint, url, captureTime, accessTime)); } public static class AccessQuery { public String url; public String timestamp; } Response checkAccessBulk(Web.Request request) throws IOException, ResponseException { String accesspoint = request.param("accesspoint"); Index index = getIndex(request); AccessQuery[] queries = fromJson(request, AccessQuery[].class); List<AccessDecision> responses = new ArrayList<>(); for (AccessQuery query: queries) { Date captureTime = Date.from(LocalDateTime.parse(query.timestamp, Capture.arcTimeFormat).toInstant(ZoneOffset.UTC)); Date accessTime = new Date(); responses.add(index.accessControl.checkAccess(accesspoint, query.url, captureTime, accessTime)); } return jsonResponse(responses); } @Override public Response handle(Web.Request request) throws Exception { Response response = router.handle(request); if (response != null) { response.addHeader("Access-Control-Allow-Origin", "*"); } return response; } }
package com.sotwtm.util; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Locale; /** * A class to run logcat to record app's log. * The logcat process will be running still until the app is force stopped or device restarted. * * @author sheungon */ public class ECLogcatUtil { private static final String COMMAND_SEPARATOR = "\n\r"; static final String SHARED_PREF_FILE_KEY = "LogcatPref"; public static final int DEFAULT_LOGCAT_FILE_SIZE = 256; public static final LogFormat DEFAULT_LOGCAT_FORMAT = LogFormat.Time; public static final int DEFAULT_LOGCAT_MAX_NO_OF_LOG_FILES = 1; static final String LOG_TAG = "ECLogcatUtil"; static final String PREF_KEY_APP_LINUX_USER_NAME = "AppLinuxUserName"; static final String PREF_KEY_LOGCAT_SINCE = "LogcatSince"; static final String PREF_KEY_LOGCAT_FILE_MAX_SIZE = "LogcatFileMaxSize"; static final String PREF_KEY_LOGCAT_FORMAT = "LogcatFormat"; static final String PREF_KEY_LOGCAT_MAX_LOG_FILE = "LogcatMaxLogFile"; static final String PREF_KEY_LOGCAT_FILTER_LOG_TAG = "LogcatFilterLogTag"; static final String PREF_KEY_LOGCAT_PATH = "LogcatPath"; static final SimpleDateFormat LOGCAT_SINCE_FORMAT = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US); static final String REGEX_COLUMN_SEPARATOR = "(\\s+[A-Z]?\\s+|\\s+)"; static final String PS_COL_USER = "USER"; static final String PS_COL_PID = "PID"; static final String PS_COL_NAME = "NAME"; private static volatile ECLogcatUtil _instance; private final WeakReference<Context> mContextRef; @NonNull public static synchronized ECLogcatUtil getInstance(@NonNull Context context) { if (_instance == null || _instance.mContextRef.get() == null) { _instance = new ECLogcatUtil(context); } return _instance; } private ECLogcatUtil(@NonNull Context context) { mContextRef = new WeakReference<>(context.getApplicationContext()); } /** * Start a logcat process and log the log to {@code logFile}. * Only one concurrent logcat process will be created even call this method multiple times. * * @return {@code true} if a logcat process created successfully or a logcat process already running before. * @throws NullPointerException if the logcat path is not set by {@link #setLogcatDest(File)} yet. * @see #startLogcat(boolean) * */ public synchronized boolean startLogcat() { return startLogcat(true); } /** * Start a logcat process and log the log to {@code logFile}. * Only one concurrent logcat process will be created even call this method multiple times. * * @param clearPreviousLog {@code true} to clear the destination log file. Otherwise, new log is appended to the end of the file. * @return {@code true} if a logcat process created successfully or a logcat process already running before. * @throws NullPointerException if the logcat path is not set by {@link #setLogcatDest(File)} yet. * */ public synchronized boolean startLogcat(boolean clearPreviousLog) { Context context = mContextRef.get(); if (context == null) { Log.e("No Context!!!"); return false; } String username = getAppRunByUser(context); if (username == null) { // Not starting logcat in this case to avoid repeatedly start many logcat process Log.w(LOG_TAG, "Cannot start logcat due to app user is unknown."); return false; } Log.v(LOG_TAG, "App running by : " + username); if (isLogcatRunningBy(username)) { Log.v(LOG_TAG, "logcat running already"); return true; } SharedPreferences sharedPreferences = getSharedPreferences(context); String logcatPath = sharedPreferences.getString(PREF_KEY_LOGCAT_PATH, null); if (TextUtils.isEmpty(logcatPath)) { throw new NullPointerException("Logcat path is not set yet!!!"); } if (clearPreviousLog) { File oldLog = new File(logcatPath); boolean deletedOldLog = !oldLog.isFile() || oldLog.delete(); if (deletedOldLog) { Log.d(LOG_TAG, "Deleted old log."); } else { Log.e(LOG_TAG, "Error on delete old log."); } } StringBuilder commandBuilder = new StringBuilder("logcat"); commandBuilder .append(COMMAND_SEPARATOR).append("-f").append(COMMAND_SEPARATOR).append(logcatPath) .append(COMMAND_SEPARATOR).append("-r").append(COMMAND_SEPARATOR).append(sharedPreferences.getInt(PREF_KEY_LOGCAT_FILE_MAX_SIZE, DEFAULT_LOGCAT_FILE_SIZE)) .append(COMMAND_SEPARATOR).append("-n").append(COMMAND_SEPARATOR).append(sharedPreferences.getInt(PREF_KEY_LOGCAT_MAX_LOG_FILE, DEFAULT_LOGCAT_MAX_NO_OF_LOG_FILES)) .append(COMMAND_SEPARATOR).append("-v").append(COMMAND_SEPARATOR).append(sharedPreferences.getString(PREF_KEY_LOGCAT_FORMAT, DEFAULT_LOGCAT_FORMAT.toString())); String logcatSince = sharedPreferences.getString(PREF_KEY_LOGCAT_SINCE, null); if (logcatSince != null) { commandBuilder.append(COMMAND_SEPARATOR).append("-T").append(COMMAND_SEPARATOR).append("0"); } String filterTag = sharedPreferences.getString(PREF_KEY_LOGCAT_FILTER_LOG_TAG, null); if (filterTag != null) { // Filter all logs by the log tag commandBuilder.append(COMMAND_SEPARATOR).append("*:S").append(COMMAND_SEPARATOR).append(filterTag); } String[] processParams = commandBuilder.toString().split(COMMAND_SEPARATOR); // Run logcat here ProcessBuilder processBuilder = new ProcessBuilder(processParams); processBuilder.redirectErrorStream(true); try { processBuilder.start(); Log.v(LOG_TAG, "Started logcat"); return isLogcatRunningBy(username); } catch (Exception e) { Log.e(LOG_TAG, "Error on starting logcat", e); } return false; } /** * Stop any running logcat instance * * @return {@code true} if a logcat can be stopped by this. Or no logcat process was running. * */ public boolean stopLogcat() { Context context = mContextRef.get(); if (context == null) { Log.e("No Context!!!"); return false; } String username = getAppRunByUser(context); if (username == null) { Log.e(LOG_TAG, "Cannot get ps user!!!"); return false; } String pid = getLogcatPIDRunningBy(username); if (pid == null) { return true; } ProcessBuilder processBuilder = new ProcessBuilder("kill", pid); Log.d(Arrays.toString(processBuilder.command().toArray())); try { Process process = processBuilder.start(); process.waitFor(); int exitCode = process.exitValue(); Log.v(LOG_TAG, "Stopped logcat exit code : " + exitCode); return true; } catch (Exception e) { Log.e(LOG_TAG, "Error on kill logcat", e); } return false; } /** * Reset logcat to log down all logs again. * * @return {@code true} if a logcat process has been recreated. * @see #clearLogcat() * */ public boolean resetLogcat() { Context context = mContextRef.get(); if (context == null) { Log.e("No Context!!!"); return false; } boolean logcatStopped = stopLogcat(); Log.d("Logcat stopped : " + logcatStopped); getEditor(context).remove(PREF_KEY_LOGCAT_SINCE).apply(); Log.d("Reset logcat"); return startLogcat(); } /** * Reset and start to print log since now only * * @return {@code true} if a logcat process has been recreated. * @see #resetLogcat() * */ public boolean clearLogcat() { Context context = mContextRef.get(); if (context == null) { Log.e("No Context!!!"); return false; } String logcatSince = LOGCAT_SINCE_FORMAT.format(new Date()); boolean logcatStopped = stopLogcat(); Log.d("Logcat stopped : " + logcatStopped); getEditor(context).putString(PREF_KEY_LOGCAT_SINCE, logcatSince).apply(); Log.d("Clear logcat since : " + logcatSince); return startLogcat(); } /** * Set the maximum size of each logcat file. * * @param logcatFileMaxSize Size in KB * @see #setMaxLogFile(int) * */ public void setLogcatFileMaxSize(int logcatFileMaxSize) { Context context = mContextRef.get(); if (context == null) { return; } getEditor(context).putInt(PREF_KEY_LOGCAT_FILE_MAX_SIZE, logcatFileMaxSize).apply(); } /** * Set the format of logcat. * * @param logFormat Possible values are {@link LogFormat} * */ public void setLogcatFormat(@NonNull LogFormat logFormat) { Context context = mContextRef.get(); if (context == null) { return; } getEditor(context).putString(PREF_KEY_LOGCAT_FORMAT, logFormat.toString()).apply(); } /** * Set the num of log file will be created if a log file excesses the max size * * @param maxLogFile The maximum number of log file will be created before overwriting the first log file. * @see #setLogcatFileMaxSize(int) * */ public void setMaxLogFile(int maxLogFile) { Context context = mContextRef.get(); if (context == null) { return; } getEditor(context).putInt(PREF_KEY_LOGCAT_MAX_LOG_FILE, maxLogFile).apply(); } /** * Set logcat should be filtered by the given log tag. * * @param filterLogTag The log tag. {@code null} means filtered by nothing. * */ public void setFilterLogTag(@Nullable String filterLogTag) { Context context = mContextRef.get(); if (context == null) { return; } SharedPreferences.Editor editor = getEditor(context); if (TextUtils.isEmpty(filterLogTag)) { editor.remove(PREF_KEY_LOGCAT_FILTER_LOG_TAG); } else { editor.putString(PREF_KEY_LOGCAT_FILTER_LOG_TAG, filterLogTag); } editor.apply(); } /** * Set the destination the logcat should save to. * * @param file The file indicate the path to save the logcat (e.g. /sdcard/log.txt) * */ public void setLogcatDest(@NonNull File file) { Context context = mContextRef.get(); if (context == null) { return; } getEditor(context).putString(PREF_KEY_LOGCAT_PATH, file.getAbsolutePath()).apply(); } /** * @return The app executed by which Linux user. * */ @Nullable static String getAppRunByUser(@NonNull Context context) { SharedPreferences sharedPreferences = getSharedPreferences(context); String myUserName = sharedPreferences.getString(PREF_KEY_APP_LINUX_USER_NAME, null); if (TextUtils.isEmpty(myUserName)) { String packageName = context.getPackageName(); Log.d(LOG_TAG, "Retrieving application username. ApplicationPackage = " + packageName); /*Don't user `grep` as it could be not available on some devices.*/ // Execute `ps` ProcessBuilder psBuilder = new ProcessBuilder("ps"); Process ps; try { ps = psBuilder.start(); } catch (IOException e) { Log.e(LOG_TAG, "Not able to run command on this device!!!", e); return null; } // Read the output InputStream is = ps.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(is)); try { Log.d(LOG_TAG, "======`ps` output start======"); // Read the first line and find the target column String line = bf.readLine(); if (line == null) { Log.e(LOG_TAG, "'ps' no output?!"); return null; } Log.d(LOG_TAG, line); // Split by space String[] columns = line.split(REGEX_COLUMN_SEPARATOR); int userColumn = -1; int nameColumn = -1; for (int i = 0; i < columns.length; i++) { if (PS_COL_USER.equalsIgnoreCase(columns[i])) { userColumn = i; } else if (PS_COL_NAME.equalsIgnoreCase(columns[i])) { nameColumn = i; } } if (userColumn == -1 || nameColumn == -1) { Log.e(LOG_TAG, "Some column cannot be found from output."); return null; } while ((line = bf.readLine()) != null) { Log.d(LOG_TAG, line); // Split by space columns = line.split(REGEX_COLUMN_SEPARATOR); if (packageName.equals(columns[nameColumn])) { myUserName = columns[userColumn]; Log.d(LOG_TAG, "Application executed by user : " + myUserName); break; } } Log.d(LOG_TAG, "======`ps` output end======"); if (TextUtils.isEmpty(myUserName)) { Log.e(LOG_TAG, "Cannot find the owner of current app..."); } else { // Cache the user name in preference as it remind the same since installed getEditor(context).putString(PREF_KEY_APP_LINUX_USER_NAME, myUserName).apply(); } } catch (IOException e) { Log.e(LOG_TAG, "Error on reading output from 'ps'", e); } finally { try { is.close(); } catch (IOException e) { // Don't care } try { ps.waitFor(); ps.exitValue(); } catch (Exception e) { Log.e(LOG_TAG, "Error on destroy ps", e); } } } return myUserName; } @Nullable static String getLogcatPIDRunningBy(@NonNull String user) { String pid = null; /*Don't user `grep` as it could be not available on some devices.*/ // Execute `ps logcat` to find all logcat process ProcessBuilder processBuilder = new ProcessBuilder("ps", "logcat"); Process ps; try { ps = processBuilder.start(); } catch (IOException e) { Log.e(LOG_TAG, "Not able to run command on this device!!!", e); return null; } // Read the output InputStream is = ps.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(is)); try { Log.d(LOG_TAG, "======`ps logcat` output start======"); // Read the first line and find the target column String line = bf.readLine(); if (line == null) { Log.e(LOG_TAG, "'ps' no output?!"); return null; } Log.d(LOG_TAG, line); // Split by space String[] columns = line.split(REGEX_COLUMN_SEPARATOR); int userColumn = -1; int pidColumn = -1; for (int i = 0; i < columns.length; i++) { if (PS_COL_USER.equalsIgnoreCase(columns[i])) { userColumn = i; } else if (PS_COL_PID.equalsIgnoreCase(columns[i])) { pidColumn = i; } } if (userColumn == -1 || pidColumn == -1) { Log.e(LOG_TAG, "Some column cannot be found from output."); return null; } while ((line = bf.readLine()) != null) { Log.d(LOG_TAG, line); // Split by space columns = line.split(REGEX_COLUMN_SEPARATOR); if (user.equals(columns[userColumn])) { // Found the current user's process pid = columns[pidColumn]; Log.v(LOG_TAG, "Logcat is already running by user [" + user + "] pid : " + pid); } } Log.d(LOG_TAG, "======`ps logcat` output end======"); } catch (IOException e) { Log.e(LOG_TAG, "Error on reading output from 'ps'", e); } finally { try { is.close(); } catch (IOException e) { // Don't care } try { ps.waitFor(); ps.exitValue(); } catch (Exception e) { Log.e(LOG_TAG, "Error on destroy ps", e); } } return pid; } static boolean isLogcatRunningBy(@NonNull String user) { return getLogcatPIDRunningBy(user) != null; } @NonNull private static SharedPreferences.Editor getEditor(@NonNull Context context) { SharedPreferences sharedPref = context.getSharedPreferences(SHARED_PREF_FILE_KEY, Context.MODE_PRIVATE); return sharedPref.edit(); } @NonNull private static SharedPreferences getSharedPreferences(@NonNull Context context) { return context.getSharedPreferences(SHARED_PREF_FILE_KEY, Context.MODE_PRIVATE); } // Class /** * The log format for command {@code logcat} * */ public enum LogFormat { Brief, Process, Tag, Thread, Raw, Time, ThreadTime, Long; @Override public String toString() { return name().toLowerCase(); } } }
package scal.io.liger; import android.content.Context; import android.util.Log; import android.widget.Toast; public class DownloadHelper { public static boolean checkExpansionFiles(Context context, String mainOrPatch, int version) { String expansionFilePath = ZipHelper.getExpansionFileFolder(context, mainOrPatch, version); if (expansionFilePath != null) { Log.d("DOWNLOAD", "EXPANSION FILE " + ZipHelper.getExpansionZipFilename(context, mainOrPatch, version) + " FOUND IN " + expansionFilePath); return true; } else { Log.d("DOWNLOAD", "EXPANSION FILE " + ZipHelper.getExpansionZipFilename(context, mainOrPatch, version) + " NOT FOUND"); return false; } } public static void checkAndDownload(Context context) { if (checkExpansionFiles(context, Constants.MAIN, Constants.MAIN_VERSION)) { Log.d("DOWNLOAD", "MAIN EXPANSION FILE FOUND (NO DOWNLOAD)"); } else { Log.d("DOWNLOAD", "MAIN EXPANSION FILE NOT FOUND (DOWNLOADING)"); final LigerDownloadManager mainDownload = new LigerDownloadManager(Constants.MAIN, Constants.MAIN_VERSION, context, true); Thread mainDownloadThread = new Thread(mainDownload); Toast.makeText(context, "Starting download of content pack.", Toast.LENGTH_LONG).show(); // FIXME move to strings mainDownloadThread.start(); } if (Constants.PATCH_VERSION > 0) { if (checkExpansionFiles(context, Constants.PATCH, Constants.PATCH_VERSION)) { Log.d("DOWNLOAD", "PATCH EXPANSION FILE FOUND (NO DOWNLOAD)"); } else { Log.d("DOWNLOAD", "PATCH EXPANSION FILE NOT FOUND (DOWNLOADING)"); final LigerDownloadManager patchDownload = new LigerDownloadManager(Constants.PATCH, Constants.PATCH_VERSION, context, true); Thread patchDownloadThread = new Thread(patchDownload); Toast.makeText(context, "Starting download of path for content pack.", Toast.LENGTH_LONG).show(); // FIXME move to strings patchDownloadThread.start(); } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.mihosoft.vrl.fxwindows; import javafx.animation.Animation; import javafx.animation.ScaleTransition; import javafx.animation.Transition; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Bounds; import javafx.scene.control.Control; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.util.Duration; public class Window extends Control { /** * Default style class for css. */ public static final String DEFAULT_STYLE_CLASS = "window"; /** * Defines whether window is moved to front when user clicks on it */ private boolean moveToFront = true; /** * Window title property (used by titlebar) */ private StringProperty titleProperty = new SimpleStringProperty("Title"); /** * Minimize property (defines whether to minimize the window,performed by * skin) */ private BooleanProperty minimizeProperty = new SimpleBooleanProperty(); /** * Content pane property. The content pane is the pane that is responsible * for showing user defined nodes/content. */ private Property<Pane> contentPaneProperty = new SimpleObjectProperty<Pane>(); /** * List of icons shown on the left. TODO replace left/right with more * generic position property? */ private ObservableList<WindowIcon> leftIcons = FXCollections.observableArrayList(); /** * List of icons shown on the right. TODO replace left/right with more * generic position property? */ private ObservableList<WindowIcon> rightIcons = FXCollections.observableArrayList(); /** * Defines the width of the border /area where the user can grab the window * and resize it. */ private DoubleProperty resizableBorderWidthProperty = new SimpleDoubleProperty(5); /** * Defines the titlebar class name. This can be used to define css * properties specifically for the titlebar, e.g., background. */ private StringProperty titleBarStyleClassProperty = new SimpleStringProperty("window-titlebar"); /** * defines the action that shall be performed before the window is closed. */ private ObjectProperty<EventHandler<ActionEvent>> onCloseActionProperty = new SimpleObjectProperty<EventHandler<ActionEvent>>(); /** * defines the action that shall be performed after the window has been * closed. */ private ObjectProperty<EventHandler<ActionEvent>> onClosedActionProperty = new SimpleObjectProperty<EventHandler<ActionEvent>>(); /** * defines the transition that shall be played when closing the window. */ private ObjectProperty<Transition> closeTransitionProperty = new SimpleObjectProperty<Transition>(); /** * Constructor. */ public Window() { init(); } /** * Constructor. * * @param title */ public Window(String title) { setTitle(title); init(); } private void init() { getStyleClass().setAll(DEFAULT_STYLE_CLASS); setContentPane(new StackPane()); // TODO ugly to do this in control? probably violates pattern rules? boundsInParentProperty().addListener(new ChangeListener<Bounds>() { @Override public void changed(ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) { if (t1.equals(t)) { return; } getParent().requestLayout(); double x = Math.max(0, getLayoutX()); double y = Math.max(0, getLayoutY()); setLayoutX(x); setLayoutY(y); } }); closeTransitionProperty.addListener(new ChangeListener<Transition>() { @Override public void changed(ObservableValue<? extends Transition> ov, Transition t, Transition t1) { t1.statusProperty().addListener(new ChangeListener<Animation.Status>() { @Override public void changed(ObservableValue<? extends Animation.Status> observableValue, Animation.Status oldValue, Animation.Status newValue) { if (newValue == Animation.Status.STOPPED) { if (getOnCloseAction() != null) { getOnCloseAction().handle(new ActionEvent(this, Window.this)); } VFXNodeUtils.removeFromParent(Window.this); if (getOnClosedAction() != null) { getOnClosedAction().handle(new ActionEvent(this, Window.this)); } } } }); } }); ScaleTransition st = new ScaleTransition(); st.setNode(this); st.setFromX(1); st.setFromY(1); st.setToX(0); st.setToY(0); st.setDuration(Duration.seconds(0.2)); setCloseTransition(st); } @Override protected String getUserAgentStylesheet() { return Constants.DEFAULT_STYLE; } /** * @return the content pane of this window */ public Pane getContentPane() { return contentPaneProperty.getValue(); } /** * Defines the content pane of this window. * * @param contentPane content pane to set */ public void setContentPane(Pane contentPane) { contentPaneProperty.setValue(contentPane); } /** * Content pane property. * * @return content pane property */ public Property<Pane> contentPaneProperty() { return contentPaneProperty; } /** * Defines whether this window shall be moved to front when a user clicks on * the window. * * @param moveToFront the state to set */ public void setMoveToFront(boolean moveToFront) { this.moveToFront = moveToFront; } /** * Indicates whether the window shall be moved to front when a user clicks * on the window. * * @return <code>true</code> if the window shall be moved to front when a * user clicks on the window; <code>false</code> otherwise */ public boolean isMoveToFront() { return moveToFront; } /** * Returns the window title. * * @return the title */ public final String getTitle() { return titleProperty.get(); } /** * Defines the window title. * * @param title the title to set */ public final void setTitle(String title) { this.titleProperty.set(title); } /** * Returns the window title property. * * @return the window title property */ public final StringProperty titleProperty() { return titleProperty; } /** * Returns a list that contains the icons that are placed on the left side * of the titlebar. Add icons to the list to add them to the left side of * the window titlebar. * * @return a list containing the left icons * * @see #getRightIcons() */ public ObservableList<WindowIcon> getLeftIcons() { return leftIcons; } /** * Returns a list that contains the icons that are placed on the right side * of the titlebar. Add icons to the list to add them to the right side of * the window titlebar. * * @return a list containing the right icons * * @see #getLeftIcons() */ public ObservableList<WindowIcon> getRightIcons() { return rightIcons; } /** * Defines whether this window shall be minimized. * * @param v the state to set */ public void setMinimized(Boolean v) { minimizeProperty.set(v); } /** * Indicates whether the window is currently minimized. * * @return <code>true</code> if the window is currently minimized; * <code>false</code> otherwise */ public boolean isMinimized() { return minimizeProperty.get(); } /** * Returns the minimize property. * * @return the minimize property */ public BooleanProperty minimizedProperty() { return minimizeProperty; } /** * Returns the titlebar style class property. * * @return the titlebar style class property */ public StringProperty titleBarStyleClassProperty() { return titleBarStyleClassProperty; } /** * Defines the CSS style class of the titlebar. * * @param name the CSS style class name */ public void setTitleBarStyleClass(String name) { titleBarStyleClassProperty.set(name); } /** * Returns the CSS style class of the titlebar. * * @return the CSS style class of the titlebar */ public String getTitleBarStyleClass() { return titleBarStyleClassProperty.get(); } /** * Returns the resizable border width property. * * @return the resizable border width property * * @see #setResizableBorderWidth(double) */ public DoubleProperty resizableBorderWidthProperty() { return resizableBorderWidthProperty; } /** * Defines the width of the "resizable border" of the window. The resizable * border is usually defined as a rectangular border around the layout * bounds of the window where the mouse cursor changes to "resizable" and * which allows to resize the window by performing a "dragging gesture", * i.e., the user can "grab" the window border and change the size of the * window. * * @param v border width */ public void setResizableBorderWidth(double v) { resizableBorderWidthProperty.set(v); } /** * Returns the width of the "resizable border" of the window. * * @return the width of the "resizable border" of the window * * @see #setResizableBorderWidth(double) */ public double getResizableBorderWidth() { return resizableBorderWidthProperty.get(); } /** * Closes this window. */ public void close() { if (getCloseTransition() != null) { getCloseTransition().play(); } else { VFXNodeUtils.removeFromParent(Window.this); } } /** * Returns the "on-closed-action" property. * * @return the "on-closed-action" property. * * @see #setOnClosedAction(javafx.event.EventHandler) */ public ObjectProperty<EventHandler<ActionEvent>> onClosedActionProperty() { return onClosedActionProperty; } /** * Defines the action that shall be performed after the window has been * closed. * * @param onClosedActionProperty the action to set */ public void setOnClosedAction(EventHandler<ActionEvent> onClosedAction) { this.onClosedActionProperty.set(onClosedAction); } /** * Returns the action that shall be performed after the window has been * closed. * * @return the action that shall be performed after the window has been * closed or <code>null</code> if no such action has been defined */ public EventHandler<ActionEvent> getOnClosedAction() { return this.onClosedActionProperty.get(); } /** * Returns the "on-close-action" property. * * @return the "on-close-action" property. * * @see #setOnCloseAction(javafx.event.EventHandler) */ public ObjectProperty<EventHandler<ActionEvent>> onCloseActionProperty() { return onCloseActionProperty; } /** * Defines the action that shall be performed before the window will be * closed. * * @param onClosedActionProperty the action to set */ public void setOnCloseAction(EventHandler<ActionEvent> onClosedAction) { this.onCloseActionProperty.set(onClosedAction); } /** * Returns the action that shall be performed before the window will be * closed. * * @return the action that shall be performed before the window will be * closed or <code>null</code> if no such action has been defined */ public EventHandler<ActionEvent> getOnCloseAction() { return this.onCloseActionProperty.get(); } /** * Returns the "close-transition" property. * * @return the "close-transition" property. * * @see #setCloseTransition(javafx.animation.Transition) */ public ObjectProperty<Transition> closeTransitionProperty() { return closeTransitionProperty; } /** * Defines the transition that shall be used to indicate window closing. * * @param t the transition that shall be used to indicate window closing or * <code>null</code> if no transition shall be used. */ public void setCloseTransition(Transition t) { closeTransitionProperty.set(t); } /** * Returns the transition that shall be used to indicate window closing. * * @return the transition that shall be used to indicate window closing or * <code>null</code> if no such transition has been defined */ public Transition getCloseTransition() { return closeTransitionProperty.get(); } }
package jolie.lang.parse; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import jolie.Constants.OperandType; import jolie.lang.parse.ast.AndConditionNode; import jolie.lang.parse.ast.AssignStatement; import jolie.lang.parse.ast.CompareConditionNode; import jolie.lang.parse.ast.CompensateStatement; import jolie.lang.parse.ast.ConstantIntegerExpression; import jolie.lang.parse.ast.ConstantRealExpression; import jolie.lang.parse.ast.ConstantStringExpression; import jolie.lang.parse.ast.CorrelationSetInfo; import jolie.lang.parse.ast.CurrentHandlerStatement; import jolie.lang.parse.ast.DeepCopyStatement; import jolie.lang.parse.ast.EmbeddedServiceNode; import jolie.lang.parse.ast.ExecutionInfo; import jolie.lang.parse.ast.ExitStatement; import jolie.lang.parse.ast.ExpressionConditionNode; import jolie.lang.parse.ast.ForEachStatement; import jolie.lang.parse.ast.ForStatement; import jolie.lang.parse.ast.IfStatement; import jolie.lang.parse.ast.InstallFixedVariableExpressionNode; import jolie.lang.parse.ast.InstallStatement; import jolie.lang.parse.ast.IsTypeExpressionNode; import jolie.lang.parse.ast.LinkInStatement; import jolie.lang.parse.ast.LinkOutStatement; import jolie.lang.parse.ast.NDChoiceStatement; import jolie.lang.parse.ast.NotConditionNode; import jolie.lang.parse.ast.NotificationOperationStatement; import jolie.lang.parse.ast.NullProcessStatement; import jolie.lang.parse.ast.OLSyntaxNode; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OneWayOperationStatement; import jolie.lang.parse.ast.OperationDeclaration; import jolie.lang.parse.ast.OrConditionNode; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.ParallelStatement; import jolie.lang.parse.ast.PointerStatement; import jolie.lang.parse.ast.PostDecrementStatement; import jolie.lang.parse.ast.PostIncrementStatement; import jolie.lang.parse.ast.PreDecrementStatement; import jolie.lang.parse.ast.PreIncrementStatement; import jolie.lang.parse.ast.ProductExpressionNode; import jolie.lang.parse.ast.Program; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.RequestResponseOperationStatement; import jolie.lang.parse.ast.RunStatement; import jolie.lang.parse.ast.Scope; import jolie.lang.parse.ast.SequenceStatement; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.SolicitResponseOperationStatement; import jolie.lang.parse.ast.DefinitionCallStatement; import jolie.lang.parse.ast.DefinitionNode; import jolie.lang.parse.ast.SpawnStatement; import jolie.lang.parse.ast.SumExpressionNode; import jolie.lang.parse.ast.SynchronizedStatement; import jolie.lang.parse.ast.ThrowStatement; import jolie.lang.parse.ast.TypeCastExpressionNode; import jolie.lang.parse.ast.UndefStatement; import jolie.lang.parse.ast.ValueVectorSizeExpressionNode; import jolie.lang.parse.ast.VariableExpressionNode; import jolie.lang.parse.ast.VariablePathNode; import jolie.lang.parse.ast.WhileStatement; import jolie.util.Pair; /** * Checks the well-formedness and validity of a JOLIE program. * @see Program * @author Fabrizio Montesi */ public class SemanticVerifier implements OLVisitor { private Program program; private boolean valid = true; private Map< String, InputPortInfo > inputPorts = new HashMap< String, InputPortInfo >(); private Map< String, OutputPortInfo > outputPorts = new HashMap< String, OutputPortInfo >(); private Set< String > subroutineNames = new HashSet< String > (); private HashMap< String, OperationDeclaration > operations = new HashMap< String, OperationDeclaration >(); private boolean mainDefined = false; private final Logger logger = Logger.getLogger( "JOLIE" ); public SemanticVerifier( Program program ) { this.program = program; } private void error( OLSyntaxNode node, String message ) { valid = false; if ( node != null ) { ParsingContext context = node.context(); logger.severe( context.sourceName() + ":" + context.line() + ": " + message ); } else { logger.severe( message ); } } public boolean validate() { visit( program ); if ( mainDefined == false ) { error( null, "Main procedure not defined" ); } if ( !valid ) { logger.severe( "Aborting: input file semantically invalid." ); return false; } return valid; } public void visit( SpawnStatement n ) { n.body().accept( this ); } public void visit( Program n ) { for( OLSyntaxNode node : n.children() ) node.accept( this ); } public void visit( VariablePathNode n ) {} public void visit( InputPortInfo n ) { if ( inputPorts.get( n.id() ) != null ) error( n, "input port " + n.id() + " has been already defined" ); inputPorts.put( n.id(), n ); for( OperationDeclaration op : n.operations() ) { op.accept( this ); } } public void visit( OutputPortInfo n ) { if ( outputPorts.get( n.id() ) != null ) error( n, "output port " + n.id() + " has been already defined" ); outputPorts.put( n.id(), n ); for( OperationDeclaration op : n.operations() ) { op.accept( this ); } } private boolean isDefined( String id ) { if ( operations.get( id ) != null || subroutineNames.contains( id ) ) return true; return false; } public void visit( OneWayOperationDeclaration n ) { /* if ( isDefined( n.id() ) ) error( n, "Operation " + n.id() + " uses an already defined identifier" ); else operations.put( n.id(), n ); **/ } public void visit( RequestResponseOperationDeclaration n ) { /* if ( isDefined( n.id() ) ) error( n, "Operation " + n.id() + " uses an already defined identifier" ); else operations.put( n.id(), n ); */ } public void visit( DefinitionNode n ) { if ( isDefined( n.id() ) ) error( n, "Procedure " + n.id() + " uses an already defined identifier" ); else subroutineNames.add( n.id() ); if ( "main".equals( n.id() ) ) mainDefined = true; n.body().accept( this ); } public void visit( ParallelStatement stm ) { for( OLSyntaxNode node : stm.children() ) node.accept( this ); } public void visit( SequenceStatement stm ) { for( OLSyntaxNode node : stm.children() ) node.accept( this ); } public void visit( NDChoiceStatement stm ) { for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) { pair.key().accept( this ); pair.value().accept( this ); } } public void visit( NotificationOperationStatement n ) { OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() ); else if ( !( decl instanceof OneWayOperationDeclaration ) ) error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() ); } } public void visit( SolicitResponseOperationStatement n ) { OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) error( n, n.outputPortId() + " is not a valid output port" ); else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() ); else if ( !( decl instanceof RequestResponseOperationDeclaration ) ) error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() ); } } public void visit( ThrowStatement n ) { verify( n.expression() ); } public void visit( CompensateStatement n ) {} public void visit( InstallStatement n ) { for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) { pair.value().accept( this ); } } public void visit( Scope n ) { n.body().accept( this ); } /* * TODO Must check operation names in opNames and links in linkNames and locks in lockNames */ public void visit( OneWayOperationStatement n ) { verify( n.inputVarPath() ); } public void visit( RequestResponseOperationStatement n ) { verify( n.inputVarPath() ); verify( n.process() ); } public void visit( LinkInStatement n ) {} public void visit( LinkOutStatement n ) {} public void visit( SynchronizedStatement n ) { n.body().accept( this ); } /** * TODO Must assign to a variable in varNames */ public void visit( AssignStatement n ) { n.variablePath().accept( this ); n.expression().accept( this ); } private void verify( OLSyntaxNode n ) { if ( n != null ) { n.accept( this ); } } public void visit( PointerStatement n ) {} public void visit( DeepCopyStatement n ) {} public void visit( IfStatement n ) { for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) { choice.key().accept( this ); choice.value().accept( this ); } verify( n.elseProcess() ); } public void visit( DefinitionCallStatement n ) {} public void visit( WhileStatement n ) { n.condition().accept( this ); n.body().accept( this ); } public void visit( OrConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( AndConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } public void visit( NotConditionNode n ) { n.condition().accept( this ); } public void visit( CompareConditionNode n ) { n.leftExpression().accept( this ); n.rightExpression().accept( this ); } public void visit( ExpressionConditionNode n ) { n.expression().accept( this ); } public void visit( ConstantIntegerExpression n ) {} public void visit( ConstantRealExpression n ) {} public void visit( ConstantStringExpression n ) {} public void visit( ProductExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } public void visit( SumExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } public void visit( VariableExpressionNode n ) { n.variablePath().accept( this ); } public void visit( InstallFixedVariableExpressionNode n ) { n.variablePath().accept( this ); } public void visit( NullProcessStatement n ) {} public void visit( ExitStatement n ) {} public void visit( ExecutionInfo n ) {} public void visit( CorrelationSetInfo n ) {} public void visit( RunStatement n ) {} public void visit( ValueVectorSizeExpressionNode n ) { n.variablePath().accept( this ); } public void visit( PreIncrementStatement n ) { n.variablePath().accept( this ); } public void visit( PostIncrementStatement n ) { n.variablePath().accept( this ); } public void visit( PreDecrementStatement n ) { n.variablePath().accept( this ); } public void visit( PostDecrementStatement n ) { n.variablePath().accept( this ); } public void visit( UndefStatement n ) { n.variablePath().accept( this ); } public void visit( ForStatement n ) { n.init().accept( this ); n.condition().accept( this ); n.post().accept( this ); n.body().accept( this ); } public void visit( ForEachStatement n ) { n.keyPath().accept( this ); n.targetPath().accept( this ); n.body().accept( this ); } public void visit( IsTypeExpressionNode n ) { n.variablePath().accept( this ); } public void visit( TypeCastExpressionNode n ) { n.expression().accept( this ); } public void visit( EmbeddedServiceNode n ) {} /** * @todo Must check if it's inside an install function */ public void visit( CurrentHandlerStatement n ) {} }
package jolie.lang.parse; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Logger; import jolie.lang.Constants.ExecutionMode; import jolie.lang.Constants.OperandType; import jolie.lang.Constants.OperationType; import jolie.lang.parse.CorrelationFunctionInfo.CorrelationPairInfo; import jolie.lang.parse.ast.AddAssignStatement; import jolie.lang.parse.ast.AssignStatement; import jolie.lang.parse.ast.CompareConditionNode; import jolie.lang.parse.ast.CompensateStatement; import jolie.lang.parse.ast.CorrelationSetInfo; import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationAliasInfo; import jolie.lang.parse.ast.CurrentHandlerStatement; import jolie.lang.parse.ast.DeepCopyStatement; import jolie.lang.parse.ast.DefinitionCallStatement; import jolie.lang.parse.ast.DefinitionNode; import jolie.lang.parse.ast.DivideAssignStatement; import jolie.lang.parse.ast.DocumentationComment; import jolie.lang.parse.ast.EmbeddedServiceNode; import jolie.lang.parse.ast.ExecutionInfo; import jolie.lang.parse.ast.ExitStatement; import jolie.lang.parse.ast.ForEachArrayItemStatement; import jolie.lang.parse.ast.ForEachSubNodeStatement; import jolie.lang.parse.ast.ForStatement; import jolie.lang.parse.ast.IfStatement; import jolie.lang.parse.ast.InputPortInfo; import jolie.lang.parse.ast.InstallFixedVariableExpressionNode; import jolie.lang.parse.ast.InstallStatement; import jolie.lang.parse.ast.InterfaceDefinition; import jolie.lang.parse.ast.InterfaceExtenderDefinition; import jolie.lang.parse.ast.LinkInStatement; import jolie.lang.parse.ast.LinkOutStatement; import jolie.lang.parse.ast.MultiplyAssignStatement; import jolie.lang.parse.ast.NDChoiceStatement; import jolie.lang.parse.ast.NotificationOperationStatement; import jolie.lang.parse.ast.NullProcessStatement; import jolie.lang.parse.ast.OLSyntaxNode; import jolie.lang.parse.ast.OneWayOperationDeclaration; import jolie.lang.parse.ast.OneWayOperationStatement; import jolie.lang.parse.ast.OperationDeclaration; import jolie.lang.parse.ast.OutputPortInfo; import jolie.lang.parse.ast.ParallelStatement; import jolie.lang.parse.ast.PointerStatement; import jolie.lang.parse.ast.PostDecrementStatement; import jolie.lang.parse.ast.PostIncrementStatement; import jolie.lang.parse.ast.PreDecrementStatement; import jolie.lang.parse.ast.PreIncrementStatement; import jolie.lang.parse.ast.Program; import jolie.lang.parse.ast.ProvideUntilStatement; import jolie.lang.parse.ast.RequestResponseOperationDeclaration; import jolie.lang.parse.ast.RequestResponseOperationStatement; import jolie.lang.parse.ast.RunStatement; import jolie.lang.parse.ast.Scope; import jolie.lang.parse.ast.SequenceStatement; import jolie.lang.parse.ast.SolicitResponseOperationStatement; import jolie.lang.parse.ast.SpawnStatement; import jolie.lang.parse.ast.SubtractAssignStatement; import jolie.lang.parse.ast.SynchronizedStatement; import jolie.lang.parse.ast.ThrowStatement; import jolie.lang.parse.ast.TypeCastExpressionNode; import jolie.lang.parse.ast.UndefStatement; import jolie.lang.parse.ast.ValueVectorSizeExpressionNode; import jolie.lang.parse.ast.VariablePathNode; import jolie.lang.parse.ast.WhileStatement; import jolie.lang.parse.ast.courier.CourierChoiceStatement; import jolie.lang.parse.ast.courier.CourierDefinitionNode; import jolie.lang.parse.ast.courier.NotificationForwardStatement; import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement; import jolie.lang.parse.ast.expression.AndConditionNode; import jolie.lang.parse.ast.expression.ConstantBoolExpression; import jolie.lang.parse.ast.expression.ConstantDoubleExpression; import jolie.lang.parse.ast.expression.ConstantIntegerExpression; import jolie.lang.parse.ast.expression.ConstantLongExpression; import jolie.lang.parse.ast.expression.ConstantStringExpression; import jolie.lang.parse.ast.expression.FreshValueExpressionNode; import jolie.lang.parse.ast.expression.InlineTreeExpressionNode; import jolie.lang.parse.ast.expression.InstanceOfExpressionNode; import jolie.lang.parse.ast.expression.IsTypeExpressionNode; import jolie.lang.parse.ast.expression.NotExpressionNode; import jolie.lang.parse.ast.expression.OrConditionNode; import jolie.lang.parse.ast.expression.ProductExpressionNode; import jolie.lang.parse.ast.expression.SumExpressionNode; import jolie.lang.parse.ast.expression.VariableExpressionNode; import jolie.lang.parse.ast.expression.VoidExpressionNode; import jolie.lang.parse.ast.types.TypeChoiceDefinition; import jolie.lang.parse.ast.types.TypeDefinition; import jolie.lang.parse.ast.types.TypeDefinitionLink; import jolie.lang.parse.ast.types.TypeInlineDefinition; import jolie.lang.parse.context.URIParsingContext; import jolie.util.ArrayListMultiMap; import jolie.util.MultiMap; import jolie.util.Pair; /** * Checks the well-formedness and validity of a JOLIE program. * @see Program * @author Fabrizio Montesi */ public class SemanticVerifier implements OLVisitor { public static class Configuration { private boolean checkForMain = true; public void setCheckForMain( boolean checkForMain ) { this.checkForMain = checkForMain; } public boolean checkForMain() { return checkForMain; } } private final Program program; private boolean valid = true; private final SemanticException semanticException = new SemanticException(); private final Configuration configuration; private ExecutionInfo executionInfo = new ExecutionInfo( URIParsingContext.DEFAULT, ExecutionMode.SINGLE ); private final Map< String, InputPortInfo > inputPorts = new HashMap<>(); private final Map< String, OutputPortInfo > outputPorts = new HashMap<>(); private final Set< String > subroutineNames = new HashSet<> (); private final Map< String, OneWayOperationDeclaration > oneWayOperations = new HashMap<>(); private final Map< String, RequestResponseOperationDeclaration > requestResponseOperations = new HashMap<>(); private final Map< TypeDefinition, List< TypeDefinition > > typesToBeEqual = new HashMap<>(); private final Map< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > owToBeEqual = new HashMap<>(); private final Map< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > rrToBeEqual = new HashMap<>(); private final List< CorrelationSetInfo > correlationSets = new LinkedList<>(); private boolean insideInputPort = false; private boolean insideInit = false; private boolean mainDefined = false; private CorrelationFunctionInfo correlationFunctionInfo = new CorrelationFunctionInfo(); private final MultiMap< String, String > inputTypeNameMap = new ArrayListMultiMap<>(); // Maps type names to the input operations that use them private ExecutionMode executionMode = ExecutionMode.SINGLE; private static final Logger logger = Logger.getLogger( "JOLIE" ); private final Map< String, TypeDefinition > definedTypes; private final List< TypeDefinitionLink > definedTypeLinks = new LinkedList<>(); //private TypeDefinition rootType; // the type representing the whole session state private final Map< String, Boolean > isConstantMap = new HashMap<>(); private OperationType insideCourierOperationType = null; public SemanticVerifier( Program program, Configuration configuration ) { this.program = program; this.definedTypes = OLParser.createTypeDeclarationMap( program.context() ); this.configuration = configuration; /*rootType = new TypeInlineDefinition( new ParsingContext(), "#RootType", NativeType.VOID, jolie.lang.Constants.RANGE_ONE_TO_ONE );*/ } public SemanticVerifier( Program program ) { this( program, new Configuration() ); } public CorrelationFunctionInfo correlationFunctionInfo() { return correlationFunctionInfo; } public ExecutionMode executionMode() { return executionMode; } private void encounteredAssignment( String varName ) { if ( isConstantMap.containsKey( varName ) ) { isConstantMap.put( varName, false ); } else { isConstantMap.put( varName, true ); } } private void addTypeEqualnessCheck( TypeDefinition key, TypeDefinition type ) { List< TypeDefinition > toBeEqualList = typesToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList<>(); typesToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( type ); } private void addOneWayEqualnessCheck( OneWayOperationDeclaration key, OneWayOperationDeclaration oneWay ) { List< OneWayOperationDeclaration > toBeEqualList = owToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList<>(); owToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( oneWay ); } private void addRequestResponseEqualnessCheck( RequestResponseOperationDeclaration key, RequestResponseOperationDeclaration requestResponse ) { List< RequestResponseOperationDeclaration > toBeEqualList = rrToBeEqual.get( key ); if ( toBeEqualList == null ) { toBeEqualList = new LinkedList<>(); rrToBeEqual.put( key, toBeEqualList ); } toBeEqualList.add( requestResponse ); } private void encounteredAssignment( VariablePathNode path ) { encounteredAssignment( ((ConstantStringExpression)path.path().get( 0 ).key()).value() ); } public Map< String, Boolean > isConstantMap() { return isConstantMap; } private void warning( OLSyntaxNode node, String message ) { if ( node == null ) { logger.warning( message ); } else { logger.warning( node.context().sourceName() + ":" + node.context().line() + ": " + message ); } } private void error( OLSyntaxNode node, String message ) { valid = false; semanticException.addSemanticError( node, message); } private void resolveLazyLinks() { for( TypeDefinitionLink l : definedTypeLinks ) { l.setLinkedType( definedTypes.get( l.linkedTypeName() ) ); if ( l.linkedType() == null ) { error( l, "type " + l.id() + " points to an undefined type (" + l.linkedTypeName() + ")" ); } } } private void checkToBeEqualTypes() { for( Entry< TypeDefinition, List< TypeDefinition > > entry : typesToBeEqual.entrySet() ) { for( TypeDefinition type : entry.getValue() ) { if ( entry.getKey().isEquivalentTo( type ) == false ) { error( type, "type " + type.id() + " has already been defined with a different structure" ); } } } for( Entry< OneWayOperationDeclaration, List< OneWayOperationDeclaration > > entry : owToBeEqual.entrySet() ) { for( OneWayOperationDeclaration ow : entry.getValue() ) { checkEqualness( entry.getKey(), ow ); } } for( Entry< RequestResponseOperationDeclaration, List< RequestResponseOperationDeclaration > > entry : rrToBeEqual.entrySet() ) { for( RequestResponseOperationDeclaration rr : entry.getValue() ) { checkEqualness( entry.getKey(), rr ); } } } private void checkCorrelationSets() { Collection< String > operations; Set< String > correlatingOperations = new HashSet<>(); Set< String > currCorrelatingOperations = new HashSet<>(); for( CorrelationSetInfo cset : correlationSets ) { correlationFunctionInfo.correlationSets().add( cset ); currCorrelatingOperations.clear(); for( CorrelationSetInfo.CorrelationVariableInfo csetVar : cset.variables() ) { for( CorrelationAliasInfo alias : csetVar.aliases() ) { checkCorrelationAlias( alias ); operations = inputTypeNameMap.get( alias.guardName() ); for( String operationName : operations ) { currCorrelatingOperations.add( operationName ); correlationFunctionInfo.putCorrelationPair( operationName, new CorrelationPairInfo( csetVar.correlationVariablePath(), alias.variablePath() ) ); } } } for( String operationName : currCorrelatingOperations ) { if ( correlatingOperations.contains( operationName ) ) { error( cset, "Operation " + operationName + " is specified on more than one correlation set. Each operation can correlate using only one correlation set." ); } else { correlatingOperations.add( operationName ); correlationFunctionInfo.operationCorrelationSetMap().put( operationName, cset ); correlationFunctionInfo.correlationSetOperations().put( cset, operationName ); } } } Collection< CorrelationPairInfo > pairs; for( Map.Entry< String, CorrelationSetInfo > entry : correlationFunctionInfo.operationCorrelationSetMap().entrySet() ) { pairs = correlationFunctionInfo.getOperationCorrelationPairs( entry.getKey() ); if ( pairs.size() != entry.getValue().variables().size() ) { error( entry.getValue(), "Operation " + entry.getKey() + " has not an alias specified for every variable in the correlation set." ); } } } private void checkCorrelationAlias( CorrelationAliasInfo alias ) { TypeDefinition type = definedTypes.get( alias.guardName() ); if ( type == null ) { error( alias.variablePath(), "type " + alias.guardName() + " is undefined" ); } else if ( type.containsPath( alias.variablePath() ) == false ) { error( alias.variablePath(), "type " + alias.guardName() + " does not contain the specified path" ); } } public void validate() throws SemanticException { program.accept( this ); resolveLazyLinks(); checkToBeEqualTypes(); checkCorrelationSets(); if ( configuration.checkForMain && mainDefined == false ) { error( null, "Main procedure not defined" ); } if ( !valid ) { logger.severe( "Aborting: input file semantically invalid." ); /* for( SemanticException.SemanticError e : semanticException.getErrorList() ){ logger.severe( e.getMessage() ); } */ throw semanticException; } } private boolean isTopLevelType = true; @Override public void visit( TypeInlineDefinition n ) { checkCardinality( n ); boolean backupRootType = isTopLevelType; if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } } isTopLevelType = false; if ( n.hasSubTypes() ) { for( Entry< String, TypeDefinition > entry : n.subTypes() ) { entry.getValue().accept( this ); } } isTopLevelType = backupRootType; if ( isTopLevelType ) { definedTypes.put( n.id(), n ); } } @Override public void visit( TypeDefinitionLink n ) { checkCardinality( n ); if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } definedTypes.put( n.id(), n ); } definedTypeLinks.add( n ); } public void visit( TypeChoiceDefinition n ) { checkCardinality( n ); boolean backupRootType = isTopLevelType; if ( isTopLevelType ) { // Check if the type has already been defined with a different structure TypeDefinition type = definedTypes.get( n.id() ); if ( type != null ) { addTypeEqualnessCheck( type, n ); } } isTopLevelType = false; verify( n.left() ); verify( n.right() ); isTopLevelType = backupRootType; if ( isTopLevelType ) { definedTypes.put( n.id(), n ); } } private void checkCardinality( TypeDefinition type ) { if ( type.cardinality().min() < 0 ) { error( type, "type " + type.id() + " specifies an invalid minimum range value (must be positive)" ); } if ( type.cardinality().max() < 0 ) { error( type, "type " + type.id() + " specifies an invalid maximum range value (must be positive)" ); } } @Override public void visit( SpawnStatement n ) { n.body().accept( this ); } @Override public void visit( DocumentationComment n ) {} @Override public void visit( Program n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } @Override public void visit( VariablePathNode n ) { if ( insideInit && n.isCSet() ) { error( n, "Correlation variable access is forbidden in init procedures" ); } if ( n.isCSet() && !n.isStatic() ) { error( n, "Correlation paths must be statically defined" ); } if ( !(n.path().get( 0 ).key() instanceof ConstantStringExpression) ) { if ( n.isGlobal() ) { error( n, "the global keyword in paths must be followed by an identifier" ); } else if ( n.isCSet() ) { error( n, "the csets keyword in paths must be followed by an identifier" ); } else { error( n, "paths must start with an identifier" ); } } } @Override public void visit( final InputPortInfo n ) { if ( inputPorts.get( n.id() ) != null ) { error( n, "input port " + n.id() + " has been already defined" ); } inputPorts.put( n.id(), n ); insideInputPort = true; Set< String > opSet = new HashSet<>(); for( OperationDeclaration op : n.operations() ) { if ( opSet.contains( op.id() ) ) { error( n, "input port " + n.id() + " declares operation " + op.id() + " multiple times" ); } else { opSet.add( op.id() ); op.accept( this ); } } for( InputPortInfo.AggregationItemInfo item : n.aggregationList() ) { for( String portName : item.outputPortList() ) { final OutputPortInfo outputPort = outputPorts.get( portName ); if ( outputPort == null ) { error( n, "input port " + n.id() + " aggregates an undefined output port (" + portName + ")" ); } else { if ( item.interfaceExtender() != null ) { outputPort.operations().forEach( opDecl -> { final TypeDefinition requestType = opDecl instanceof OneWayOperationDeclaration ? ((OneWayOperationDeclaration)opDecl).requestType() : ((RequestResponseOperationDeclaration)opDecl).requestType(); if ( requestType instanceof TypeInlineDefinition == false ) { error( n, "input port " + n.id() + " is trying to extend the type of operation " + opDecl.id() + " in output port " + outputPort.id() + " but such operation has an unsupported type structure (type reference or type choice)" ); } else if ( ((TypeInlineDefinition)requestType).untypedSubTypes() ) { error( n, "input port " + n.id() + " is trying to extend the type of operation " + opDecl.id() + " in output port " + outputPort.id() + " but such operation has undefined subnode types ({ ? } or undefined)" ); } } ); } } /* else { for( OperationDeclaration op : outputPort.operations() ) { if ( opSet.contains( op.id() ) ) { error( n, "input port " + n.id() + " declares duplicate operation " + op.id() + " from aggregated output port " + outputPort.id() ); } else { opSet.add( op.id() ); } } }*/ } } insideInputPort = false; } @Override public void visit( OutputPortInfo n ) { if ( outputPorts.get( n.id() ) != null ) error( n, "output port " + n.id() + " has been already defined" ); outputPorts.put( n.id(), n ); encounteredAssignment( n.id() ); for( OperationDeclaration op : n.operations() ) { op.accept( this ); } } @Override public void visit( OneWayOperationDeclaration n ) { if ( definedTypes.get( n.requestType().id() ) == null ) { error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() ); } if ( insideInputPort ) { // Input operation if ( oneWayOperations.containsKey( n.id() ) ) { OneWayOperationDeclaration other = oneWayOperations.get( n.id() ); addOneWayEqualnessCheck( n, other ); } else { oneWayOperations.put( n.id(), n ); inputTypeNameMap.put( n.requestType().id(), n.id() ); } } } @Override public void visit( RequestResponseOperationDeclaration n ) { if ( definedTypes.get( n.requestType().id() ) == null ) { error( n, "unknown type: " + n.requestType().id() + " for operation " + n.id() ); } if ( definedTypes.get( n.responseType().id() ) == null ) { error( n, "unknown type: " + n.responseType().id() + " for operation " + n.id() ); } for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) { if ( definedTypes.containsKey( fault.getValue().id() ) == false ) { error( n, "unknown type for fault " + fault.getKey() ); } } if ( insideInputPort ) { // Input operation if ( requestResponseOperations.containsKey( n.id() ) ) { RequestResponseOperationDeclaration other = requestResponseOperations.get( n.id() ); addRequestResponseEqualnessCheck( n, other ); } else { requestResponseOperations.put( n.id(), n ); inputTypeNameMap.put( n.requestType().id(), n.id() ); } } } private void checkEqualness( OneWayOperationDeclaration n, OneWayOperationDeclaration other ) { if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) { error( n, "input operations sharing the same name cannot declare different request types (One-Way operation " + n.id() + ")" ); } } private void checkEqualness( RequestResponseOperationDeclaration n, RequestResponseOperationDeclaration other ) { if ( n.requestType().isEquivalentTo( other.requestType() ) == false ) { error( n, "input operations sharing the same name cannot declare different request types (Request-Response operation " + n.id() + ")" ); } if ( n.responseType().isEquivalentTo( other.responseType() ) == false ) { error( n, "input operations sharing the same name cannot declare different response types (Request-Response operation " + n.id() + ")" ); } if ( n.faults().size() != other.faults().size() ) { error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() ); } for( Entry< String, TypeDefinition > fault : n.faults().entrySet() ) { if ( fault.getValue() != null ) { if ( !other.faults().containsKey( fault.getKey() ) || !other.faults().get( fault.getKey() ).isEquivalentTo( fault.getValue() ) ) { error( n, "input operations sharing the same name cannot declared different fault types (Request-Response operation " + n.id() ); } } } } @Override public void visit( DefinitionNode n ) { if ( subroutineNames.contains( n.id() ) ) { error( n, "Procedure " + n.id() + " uses an already defined identifier" ); } else { subroutineNames.add( n.id() ); } if ( "main".equals( n.id() ) ) { mainDefined = true; if ( executionInfo.mode() != ExecutionMode.SINGLE ) { if ( ( n.body() instanceof NDChoiceStatement || n.body() instanceof RequestResponseOperationStatement || n.body() instanceof OneWayOperationStatement ) == false ) { // The main body is not an input if ( n.body() instanceof SequenceStatement ) { OLSyntaxNode first = ((SequenceStatement)n.body()).children().get( 0 ); if ( (first instanceof RequestResponseOperationStatement || first instanceof OneWayOperationStatement) == false ) { // The main body is not even a sequence starting with an input error( n.body(), "The first statement of the main procedure must be an input if the execution mode is not single" ); } } else { // The main body is not even a sequence error( n.body(), "The first statement of the main procedure must be an input if the execution mode is not single" ); } } } } if ( n.id().equals( "init" ) ) { insideInit = true; } n.body().accept( this ); insideInit = false; } @Override public void visit( ParallelStatement stm ) { for( OLSyntaxNode node : stm.children() ) { node.accept( this ); } } @Override public void visit( SequenceStatement stm ) { for( OLSyntaxNode node : stm.children() ) { node.accept( this ); } } @Override public void visit( NDChoiceStatement stm ) { Set< String > operations = new HashSet<>(); String name = null; for( Pair< OLSyntaxNode, OLSyntaxNode > pair : stm.children() ) { if ( pair.key() instanceof OneWayOperationStatement ) { name = ((OneWayOperationStatement)pair.key()).id(); } else if ( pair.key() instanceof RequestResponseOperationStatement ) { name = ((RequestResponseOperationStatement)pair.key()).id(); } else { error( pair.key(), "Input choices can contain only One-Way or Request-Response guards" ); } if ( operations.contains( name ) ) { error( pair.key(), "Input choices can not have duplicate input guards (input statement for operation " + name + ")" ); } else { operations.add( name ); } pair.key().accept( this ); pair.value().accept( this ); } } @Override public void visit( NotificationOperationStatement n ) { OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) error( n, "Operation " + n.id() + " has not been declared in output port type " + p.id() ); else if ( !( decl instanceof OneWayOperationDeclaration ) ) error( n, "Operation " + n.id() + " is not a valid one-way operation in output port " + p.id() ); } } @Override public void visit( SolicitResponseOperationStatement n ) { if ( n.inputVarPath() != null ) { encounteredAssignment( n.inputVarPath() ); } OutputPortInfo p = outputPorts.get( n.outputPortId() ); if ( p == null ) { error( n, n.outputPortId() + " is not a valid output port" ); } else { OperationDeclaration decl = p.operationsMap().get( n.id() ); if ( decl == null ) { error( n, "Operation " + n.id() + " has not been declared in output port " + p.id() ); } else if ( !(decl instanceof RequestResponseOperationDeclaration) ) { error( n, "Operation " + n.id() + " is not a valid request-response operation in output port " + p.id() ); } } /*if ( n.inputVarPath() != null && n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); }*/ } @Override public void visit( ThrowStatement n ) { verify( n.expression() ); } @Override public void visit( CompensateStatement n ) {} @Override public void visit( InstallStatement n ) { for( Pair< String, OLSyntaxNode > pair : n.handlersFunction().pairs() ) { pair.value().accept( this ); } } @Override public void visit( Scope n ) { n.body().accept( this ); } @Override public void visit( OneWayOperationStatement n ) { if ( insideCourierOperationType != null ) { error( n, "input statements are forbidden inside courier definitions" ); } verify( n.inputVarPath() ); if ( n.inputVarPath() != null ) { if ( n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); } encounteredAssignment( n.inputVarPath() ); } } @Override public void visit( RequestResponseOperationStatement n ) { if ( insideCourierOperationType != null ) { error( n, "input statements are forbidden inside courier definitions" ); } verify( n.inputVarPath() ); verify( n.process() ); if ( n.inputVarPath() != null ) { if ( n.inputVarPath().isCSet() ) { error( n, "Receiving a message in a correlation variable is forbidden" ); } encounteredAssignment( n.inputVarPath() ); } } @Override public void visit( LinkInStatement n ) {} @Override public void visit( LinkOutStatement n ) {} @Override public void visit( SynchronizedStatement n ) { n.body().accept( this ); } @Override public void visit( AssignStatement n ) { n.variablePath().accept( this ); encounteredAssignment( n.variablePath() ); n.expression().accept( this ); } @Override public void visit( InstanceOfExpressionNode n ) { n.expression().accept( this ); } @Override public void visit( AddAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } @Override public void visit( SubtractAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } @Override public void visit( MultiplyAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } @Override public void visit( DivideAssignStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); n.expression().accept( this ); } private void verify( OLSyntaxNode n ) { if ( n != null ) { n.accept( this ); } } @Override public void visit( PointerStatement n ) { encounteredAssignment( n.leftPath() ); encounteredAssignment( n.rightPath() ); n.leftPath().accept( this ); n.rightPath().accept( this ); if ( n.rightPath().isCSet() ) { error( n, "Making an alias to a correlation variable is forbidden" ); } } @Override public void visit( DeepCopyStatement n ) { encounteredAssignment( n.leftPath() ); n.leftPath().accept( this ); n.rightExpression().accept( this ); if ( n.leftPath().isCSet() ) { error( n, "Deep copy on a correlation variable is forbidden" ); } } @Override public void visit( IfStatement n ) { for( Pair< OLSyntaxNode, OLSyntaxNode > choice : n.children() ) { verify( choice.key() ); verify( choice.value() ); } verify( n.elseProcess() ); } @Override public void visit( DefinitionCallStatement n ) { if ( !subroutineNames.contains( n.id() ) ) { error( n, "Call to undefined definition: " + n.id() ); } } @Override public void visit( WhileStatement n ) { n.condition().accept( this ); n.body().accept( this ); } @Override public void visit( OrConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } @Override public void visit( AndConditionNode n ) { for( OLSyntaxNode node : n.children() ) { node.accept( this ); } } @Override public void visit( NotExpressionNode n ) { n.expression().accept( this ); } @Override public void visit( CompareConditionNode n ) { n.leftExpression().accept( this ); n.rightExpression().accept( this ); } @Override public void visit( ConstantIntegerExpression n ) {} @Override public void visit( ConstantDoubleExpression n ) {} @Override public void visit( ConstantStringExpression n ) {} @Override public void visit( ConstantLongExpression n ) {} @Override public void visit( ConstantBoolExpression n ) {} @Override public void visit( ProductExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } @Override public void visit( SumExpressionNode n ) { for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) { pair.value().accept( this ); } } @Override public void visit( VariableExpressionNode n ) { n.variablePath().accept( this ); } @Override public void visit( InstallFixedVariableExpressionNode n ) { n.variablePath().accept( this ); } @Override public void visit( NullProcessStatement n ) {} @Override public void visit( ExitStatement n ) {} @Override public void visit( ExecutionInfo n ) { executionMode = n.mode(); executionInfo = n; } @Override public void visit( CorrelationSetInfo n ) { VariablePathSet pathSet = new VariablePathSet(); VariablePathNode path; for( CorrelationSetInfo.CorrelationVariableInfo csetVar : n.variables() ) { path = csetVar.correlationVariablePath(); if ( path.isGlobal() ) { error( path, "Correlation variables can not be global" ); } else if ( path.isCSet() ) { error( path, "Correlation variables can not be in the csets structure" ); } else { if ( path.isStatic() == false ) { error( path, "correlation variable paths can not make use of dynamic evaluation" ); } } if ( pathSet.contains( path ) ) { error( path, "Duplicate correlation variable" ); } else { pathSet.add( path ); } for( CorrelationAliasInfo alias : csetVar.aliases() ) { if ( alias.variablePath().isGlobal() ) { error( alias.variablePath(), "Correlation variables can not be global" ); } else if ( path.isCSet() ) { error( alias.variablePath(), "Correlation variables can not be in the csets structure" ); } else { if ( alias.variablePath().isStatic() == false ) { error( alias.variablePath(), "correlation variable path aliases can not make use of dynamic evaluation" ); } } } } correlationSets.add( n ); /*VariablePathNode varPath; List< Pair< OLSyntaxNode, OLSyntaxNode > > path; for( List< VariablePathNode > list : n.variables() ) { varPath = list.get( 0 ); if ( varPath.isGlobal() ) { error( list.get( 0 ), "Correlation variables can not be global" ); } path = varPath.path(); if ( path.size() > 1 ) { error( varPath, "Correlation variables can not be nested paths" ); } else if ( path.get( 0 ).value() != null ) { error( varPath, "Correlation variables can not use arrays" ); } else { correlationSet.add( ((ConstantStringExpression)path.get( 0 ).key()).value() ); } }*/ } @Override public void visit( RunStatement n ) { warning( n, "Run statement is not a stable feature yet." ); } @Override public void visit( ValueVectorSizeExpressionNode n ) { n.variablePath().accept( this ); } @Override public void visit( InlineTreeExpressionNode n ) { n.rootExpression().accept( this ); for( Pair< VariablePathNode, OLSyntaxNode > pair : n.assignments() ) { pair.key().accept( this ); pair.value().accept( this ); } } @Override public void visit( PreIncrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } @Override public void visit( PostIncrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } @Override public void visit( PreDecrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } @Override public void visit( PostDecrementStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); } @Override public void visit( UndefStatement n ) { encounteredAssignment( n.variablePath() ); n.variablePath().accept( this ); if ( n.variablePath().isCSet() ) { error( n, "Undefining a correlation variable is forbidden" ); } } @Override public void visit( ForStatement n ) { n.init().accept( this ); n.condition().accept( this ); n.post().accept( this ); n.body().accept( this ); } @Override public void visit( ForEachSubNodeStatement n ) { n.keyPath().accept( this ); n.targetPath().accept( this ); n.body().accept( this ); } @Override public void visit(ForEachArrayItemStatement n) { n.keyPath().accept( this ); n.targetPath().accept( this ); n.body().accept( this ); } @Override public void visit( IsTypeExpressionNode n ) { n.variablePath().accept( this ); } @Override public void visit( TypeCastExpressionNode n ) { n.expression().accept( this ); } @Override public void visit( EmbeddedServiceNode n ) {} @Override public void visit( InterfaceExtenderDefinition n ) {} @Override public void visit( CourierDefinitionNode n ) { if ( inputPorts.containsKey( n.inputPortName() ) == false ) { error( n, "undefined input port: " + n.inputPortName() ); } verify( n.body() ); } @Override public void visit( CourierChoiceStatement n ) { for( CourierChoiceStatement.InterfaceOneWayBranch branch : n.interfaceOneWayBranches() ) { insideCourierOperationType = OperationType.ONE_WAY; verify( branch.body ); } for( CourierChoiceStatement.InterfaceRequestResponseBranch branch : n.interfaceRequestResponseBranches() ) { insideCourierOperationType = OperationType.REQUEST_RESPONSE; verify( branch.body ); } for( CourierChoiceStatement.OperationOneWayBranch branch : n.operationOneWayBranches() ) { insideCourierOperationType = OperationType.ONE_WAY; verify( branch.body ); } for( CourierChoiceStatement.OperationRequestResponseBranch branch : n.operationRequestResponseBranches() ) { insideCourierOperationType = OperationType.REQUEST_RESPONSE; verify( branch.body ); } insideCourierOperationType = null; } /* * todo: Check that the output port of the forward statement is right wrt the input port aggregation definition. */ @Override public void visit( NotificationForwardStatement n ) { if ( insideCourierOperationType == null ) { error( n, "the forward statement may be used only inside a courier definition" ); } else if ( insideCourierOperationType != OperationType.ONE_WAY ) { error( n, "forward statement is a notification, but is inside a request-response courier definition. Maybe you wanted to specify a solicit-response forward?" ); } } /** * todo: Check that the output port of the forward statement is right wrt the input port aggregation definition. */ @Override public void visit( SolicitResponseForwardStatement n ) { if ( insideCourierOperationType == null ) { error( n, "the forward statement may be used only inside a courier definition" ); } else if ( insideCourierOperationType != OperationType.REQUEST_RESPONSE ) { error( n, "forward statement is a solicit-response, but is inside a one-way courier definition. Maybe you wanted to specify a notification forward?" ); } } /** * todo: Must check if it's inside an install function */ @Override public void visit( CurrentHandlerStatement n ) {} @Override public void visit( InterfaceDefinition n ) {} @Override public void visit( FreshValueExpressionNode n ) {} @Override public void visit( VoidExpressionNode n ) {} @Override public void visit( ProvideUntilStatement n ) { if ( !( n.provide() instanceof NDChoiceStatement ) ) { error( n, "provide branch is not an input choice" ); } else if ( !( n.until() instanceof NDChoiceStatement ) ) { error( n, "until branch is not an input choice" ); } NDChoiceStatement provide = (NDChoiceStatement) n.provide(); NDChoiceStatement until = (NDChoiceStatement) n.until(); NDChoiceStatement total = new NDChoiceStatement( n.context() ); total.children().addAll( provide.children() ); total.children().addAll( until.children() ); total.accept( this ); } }
package pl.magosa.microbe; import java.util.ArrayList; import java.util.Random; import java.util.function.Consumer; public class Neuron { protected double threshold; protected double output; protected boolean hasBias; protected ArrayList<Input> inputs; protected TransferFunction transferFunction; public Neuron() { threshold = Math.random(); inputs = new ArrayList<Input>(); } public void setTransferFunction(TransferFunction transferFunction) { this.transferFunction = transferFunction; } public TransferFunction getTransferFunction() { return transferFunction; } public Input getInput(final int index) { return inputs.get(hasBias() ? index+1 : index); } public void createInputs(final int count) { for (int i = 1; i <= count; i++) { createInput((Input input) -> {}); } } public void createInputs(final int count, Consumer<Input> initFunction) { for (int i = 1; i <= count; i++) { createInput(initFunction); } } public void createInput(Consumer<Input> initFunction) { Input input = new Input(); initFunction.accept(input); inputs.add(input); } public ArrayList<Input> getInputs() { return inputs; } public void setThreshold(final double threshold) { this.threshold = threshold; } public void applyThresholdCorrection(final double correction) { this.threshold += correction; } public double getThreshold() { return threshold; } public double getOutput() { return output; } public void activate() { double sum = -threshold; for (Input input : inputs) { sum += (input.getWeight() * input.getValue()); } output = transferFunction.function(sum); } public void createBias() { if (!inputs.isEmpty()) { throw new RuntimeException("Bias must be created before inputs."); } if (hasBias) { throw new RuntimeException("Neuron can have just one bias."); } createInput((Input input) -> { input.setValue(1); }); hasBias = true; } public boolean hasBias() { return hasBias; } }
package cpw.mods.fml.relauncher; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.security.CodeSigner; import java.security.CodeSource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.Attributes.Name; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Level; import cpw.mods.fml.common.FMLLog; public class RelaunchClassLoader extends URLClassLoader { private List<URL> sources; private ClassLoader parent; private List<IClassTransformer> transformers; private Map<String, Class> cachedClasses; private Set<String> invalidClasses; private Set<String> classLoaderExceptions = new HashSet<String>(); private Set<String> transformerExceptions = new HashSet<String>(); private Map<Package,Manifest> packageManifests = new HashMap<Package,Manifest>(); private static Manifest EMPTY = new Manifest(); private static final String[] RESERVED = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public RelaunchClassLoader(URL[] sources) { super(sources, null); this.sources = new ArrayList<URL>(Arrays.asList(sources)); this.parent = getClass().getClassLoader(); this.cachedClasses = new HashMap<String,Class>(1000); this.invalidClasses = new HashSet<String>(1000); this.transformers = new ArrayList<IClassTransformer>(2); // ReflectionHelper.setPrivateValue(ClassLoader.class, null, this, "scl"); Thread.currentThread().setContextClassLoader(this); // standard classloader exclusions addClassLoaderExclusion("java."); addClassLoaderExclusion("sun."); addClassLoaderExclusion("org.lwjgl."); addClassLoaderExclusion("cpw.mods.fml.relauncher."); addClassLoaderExclusion("net.minecraftforge.classloading."); // standard transformer exclusions addTransformerExclusion("javax."); addTransformerExclusion("org.objectweb.asm."); addTransformerExclusion("com.google.common."); } public void registerTransformer(String transformerClassName) { try { transformers.add((IClassTransformer) loadClass(transformerClassName).newInstance()); } catch (Exception e) { FMLRelaunchLog.log(Level.SEVERE, e, "A critical problem occured registering the ASM transformer class %s", transformerClassName); } } @Override public Class<?> findClass(String name) throws ClassNotFoundException { if (invalidClasses.contains(name)) { throw new ClassNotFoundException(name); } for (String st : classLoaderExceptions) { if (name.startsWith(st)) { return parent.loadClass(name); } } if (cachedClasses.containsKey(name)) { return cachedClasses.get(name); } for (String st : transformerExceptions) { if (name.startsWith(st)) { try { Class<?> cl = super.findClass(name); cachedClasses.put(name, cl); return cl; } catch (ClassNotFoundException e) { invalidClasses.add(name); throw e; } } } try { CodeSigner[] signers = null; int lastDot = name.lastIndexOf('.'); String pkgname = lastDot == -1 ? "" : name.substring(0, lastDot); String fName = name.replace('.', '/').concat(".class"); String pkgPath = pkgname.replace('.', '/'); URLConnection urlConnection = findCodeSourceConnectionFor(fName); if (urlConnection instanceof JarURLConnection && lastDot > -1) { JarURLConnection jarUrlConn = (JarURLConnection)urlConnection; JarFile jf = jarUrlConn.getJarFile(); if (jf != null && jf.getManifest() != null) { Manifest mf = jf.getManifest(); JarEntry ent = jf.getJarEntry(fName); Package pkg = getPackage(pkgname); getClassBytes(name); signers = ent.getCodeSigners(); if (pkg == null) { pkg = definePackage(pkgname, mf, jarUrlConn.getJarFileURL()); packageManifests.put(pkg, mf); } else { if (pkg.isSealed() && !pkg.isSealed(jarUrlConn.getJarFileURL())) { FMLLog.severe("The jar file %s is trying to seal already secured path %s", jf.getName(), pkgname); } else if (isSealed(pkgname, mf)) { FMLLog.severe("The jar file %s has a security seal for path %s, but that path is defined and not secure", jf.getName(), pkgname); } } } } else if (lastDot > -1) { Package pkg = getPackage(pkgname); if (pkg == null) { pkg = definePackage(pkgname, null, null, null, null, null, null, null); packageManifests.put(pkg, EMPTY); } else if (pkg.isSealed()) { FMLLog.severe("The URL %s is defining elements for sealed path %s", urlConnection.getURL(), pkgname); } } byte[] basicClass = getClassBytes(name); byte[] transformedClass = runTransformers(name, basicClass); Class<?> cl = defineClass(name, transformedClass, 0, transformedClass.length, new CodeSource(urlConnection.getURL(), signers)); cachedClasses.put(name, cl); return cl; } catch (Throwable e) { invalidClasses.add(name); throw new ClassNotFoundException(name, e); } } private boolean isSealed(String path, Manifest man) { Attributes attr = man.getAttributes(path); String sealed = null; if (attr != null) { sealed = attr.getValue(Name.SEALED); } if (sealed == null) { if ((attr = man.getMainAttributes()) != null) { sealed = attr.getValue(Name.SEALED); } } return "true".equalsIgnoreCase(sealed); } private URLConnection findCodeSourceConnectionFor(String name) { URL res = findResource(name); if (res != null) { try { return res.openConnection(); } catch (IOException e) { throw new RuntimeException(e); } } else { return null; } } private byte[] runTransformers(String name, byte[] basicClass) { for (IClassTransformer transformer : transformers) { basicClass = transformer.transform(name, basicClass); } return basicClass; } @Override public void addURL(URL url) { super.addURL(url); sources.add(url); } public List<URL> getSources() { return sources; } private byte[] readFully(InputStream stream) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(stream.available()); int r; while ((r = stream.read()) != -1) { bos.write(r); } return bos.toByteArray(); } catch (Throwable t) { FMLLog.log(Level.WARNING, t, "Problem loading class"); return new byte[0]; } } public List<IClassTransformer> getTransformers() { return Collections.unmodifiableList(transformers); } private void addClassLoaderExclusion(String toExclude) { classLoaderExceptions.add(toExclude); } void addTransformerExclusion(String toExclude) { transformerExceptions.add(toExclude); } public byte[] getClassBytes(String name) throws IOException { if (name.indexOf('.') == -1) { for (String res : RESERVED) { if (name.toUpperCase(Locale.ENGLISH).startsWith(res)) { byte[] data = getClassBytes("_" + name); if (data != null) { return data; } } } } InputStream classStream = null; try { URL classResource = findResource(name.replace('.', '/').concat(".class")); if (classResource == null) { return null; } classStream = classResource.openStream(); return readFully(classStream); } finally { if (classStream != null) { try { classStream.close(); } catch (IOException e) { // Swallow the close exception } } } } }