answer
stringlengths
17
10.2M
package net.md_5.bungee; import io.netty.buffer.ByteBuf; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.PacketWrapper; /** * Class to rewrite integers within packets. */ public class EntityMap { public final static int[][] entityIds = new int[ 256 ][]; static { entityIds[0x0A] = new int[] { 0 }; entityIds[0x0D] = new int[] { 4 }; entityIds[0x12] = new int[] { 0 }; entityIds[0x1B] = new int[] { 0, 4 }; entityIds[0x1C] = new int[] { 0 // TODO: Meta }; entityIds[0x1D] = new int[] { 0 }; entityIds[0x1E] = new int[] { 0 }; entityIds[0x20] = new int[] { 0 }; } public static void rewrite(ByteBuf packet, int oldId, int newId) { int readerIndex = packet.readerIndex(); int packetId = DefinedPacket.readVarInt( packet ); int packetIdLength = packet.readerIndex() - readerIndex; int[] idArray = entityIds[packetId]; if ( idArray != null ) { for ( int pos : idArray ) { int readId = packet.getInt( packetIdLength + pos ); if ( readId == oldId ) { packet.setInt( packetIdLength + pos, newId ); } } } if ( packetId == 0x0E ) { DefinedPacket.readVarInt( packet ); byte type = packet.readByte(); if ( type == 60 || type == 90 ) { packet.skipBytes( 14 ); int pos = packet.readerIndex(); int shooterId = packet.getInt( pos ); if ( shooterId == oldId ) { packet.setInt( pos, newId ); } } } packet.readerIndex( readerIndex ); } }
package mafiaserver; /** * ServerClientConnector.java * Contains the server client connector class * @author Cory Gehr (cmg5573) */ public class ServerClientConnector extends Thread { private final MafiaServer serverObject; // MafiaServer object private final Participant client; // The client we're connected to /** * ServerClientConnector() * Constructor for the ServerClientConnector class * @param client Participant object * @param serverObject IMServer Object */ public ServerClientConnector(Participant client, MafiaServer serverObject) { this.client = client; this.serverObject = serverObject; } /** * run() * Main thread execution procedures */ @Override public void run() { while(true) { // Wait for a message from the participant this.parseInput(client.getInput()); } } /** * parseInput() * Determines an action to perform based on user input * @param input User Input */ public void parseInput(String input) { // Separator string String separator = " // input Cases if(input.equals("SHOW USERS")) { client.pushOutput(separator); client.pushOutput("CURRENTLY CONNECTED USERS:"); client.pushOutput(separator); client.pushOutput(this.serverObject.getClientList()); } else if(input.startsWith("PLAYER")) { // Check status of player } else if(input.startsWith("STATUS")) { // Get game status } else if(input.startsWith("VOTE")) { // If player can vote // Run vote action } else { // Broadcast message ServerMessageBroadcaster broadcast = new ServerMessageBroadcaster(this.client, this.serverObject.clients, input); broadcast.start(); } } }
package lavaRunner; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import org.dreambot.api.methods.Calculations; import org.dreambot.api.methods.container.impl.bank.BankMode; import org.dreambot.api.methods.map.Area; import org.dreambot.api.methods.map.Tile; import org.dreambot.api.methods.walking.path.impl.LocalPath; import org.dreambot.api.methods.walking.pathfinding.impl.dijkstra.DijkstraPathFinder; import org.dreambot.api.script.AbstractScript; import org.dreambot.api.script.Category; import org.dreambot.api.script.ScriptManifest; import org.dreambot.api.script.listener.MessageListener; import org.dreambot.api.utilities.Timer; import org.dreambot.api.wrappers.interactive.GameObject; import org.dreambot.api.wrappers.interactive.Player; import org.dreambot.api.wrappers.widgets.message.Message; import tools.Local; import tools.Misc; @ScriptManifest(name = "Lava Runner", author = "A q p", description = "[DEV] Lava Runner\nNow with better pathing, faster trading, and responding to trades.", version = 1.2, category = Category.RUNECRAFTING) public class Script extends AbstractScript implements MessageListener { //Variables private final Tile bankTile = new Tile(3381, 3268, 0); //The specific tile to use in the bank private final Tile altarTile = new Tile(3310, 3252, 0); private final Tile exitAltarTile = new Tile(2575, 4849, 0); private final Tile awayFromRampTile = new Tile(3324, 3259, 0); private final Area bankArea = new Area(3380, 3273, 3384, 3267, 0); //The area of the bank private final Area innerAltarArea = new Area(2560, 4860, 2600, 4820, 0); //The area of the (inner) altar private final Area outerAltarArea = new Area(new Tile(3317, 3259), new Tile(3309, 3251)); //The area of the (outer) altar private final Area badCameraArea = new Area(altarTile, awayFromRampTile); private Timer t = new Timer(); //A timer private Timer lastTrade = new Timer(); private Timer resetCamera = new Timer(); private boolean acc1 = true; private boolean acc2 = true; private boolean skipFirstTradeWait = true; public boolean walkPathToBank() { log("Dfjk*path to bank"); DijkstraPathFinder df = getWalking().getDijPathFinder(); Tile start = altarTile; Tile end = awayFromRampTile; LocalPath<Tile> path = df.calculate(start, end); return path.walk(); } /*public boolean walkPathToAltar() { log("a*Path to altar"); AStarPathFinder pf = getWalking().getAStarPathFinder(); Tile start = bankTile; Tile end = altarTile; LocalPath<Tile> path = pf.calculate(start, end); return path.walk(); }*/ @Override public void onStart() { this.getWalking().setRunThreshold(50); lastTrade.setRunTime(Config.TRADE_COOLDOWN+1); Misc.printDev("Started Lava Runner: "+Misc.getTimeStamp()); resetRunThreshold(); } public void resetRunThreshold() { getWalking().setRunThreshold(Calculations.random(40, 50)); } @Override public int onLoop() { checkForMods(); //must be logged in if (!getClient().isLoggedIn()) { smallSleep(); return 100; } /*if (tiltCameraArea.contains(getLocalPlayer())) { turnCamera(); }*/ if (resetCamera.elapsed() > Config.CAMERA_RESET) { resetCamera(); resetCamera.reset(); } //if we should bank if (needToBank()) { resetRunThreshold(); if (Config.EXTREME_DEBUGGING) { log("We need to bank!"); } //check if we're in runecrafting area if (innerAltarArea.contains(getLocalPlayer())) { if (Config.EXTREME_DEBUGGING) { log("We're inside the inner Altar."); } //then walk out of runecrafting area if (Config.EXTREME_DEBUGGING) { log("We're trying to exit the inner altar!"); } if (getWalking().walk(exitAltarTile)) { smallSleep(); } smallSleep(); if (Config.EXTREME_DEBUGGING) { log("We want to use the portal!"); } GameObject portal = getGameObjects().closest("Portal"); if (portal != null) { if (portal.interact("Use")) { medSleep(); } smallSleep(); } } else //if we are not in the bank, if (!bankArea.contains(getLocalPlayer())) { if (Config.EXTREME_DEBUGGING) { log("We are not in the bank"); log("So we'll walk to the bank!"); } //walk to the bank. if (badCameraArea.contains(getLocalPlayer())) { walkPathToBank(); } else if (getWalking().walk(bankTile)) { medSleep(); } //we are in the bank } else { if (Config.EXTREME_DEBUGGING) { log("We are in the bank!"); } //so, bank handleBanking(); } //don't need to bank } else { if (!outerAltarArea.contains(getLocalPlayer()) && !innerAltarArea.contains(getLocalPlayer())) { //if we not inside any altaer if (Config.EXTREME_DEBUGGING) { log("We aren't in ruins and aren't inside ruins, so we want to walk into the outer ruins!"); } if (getWalking().walk(altarTile)) { medSleep(); } } if (outerAltarArea.contains(getLocalPlayer())){ //if we're inside the outside altar area if (Config.EXTREME_DEBUGGING) { log("We want to use the Ruins!"); } GameObject ruins = getGameObjects().closest("Mysterious ruins"); if (ruins != null) { if (ruins.interact("Enter")) { //enter the ruins medSleep(); } smallSleep(); } } if (innerAltarArea.contains(getLocalPlayer())) { //if we're in the inner area if (Config.EXTREME_DEBUGGING) { log("We would handle trading here."); } handleTrading(); } } return 100; } public void turnCamera() { getCamera().rotateToYaw(Calculations.random(1, 10)); getCamera().rotateToPitch(383); } public void resetCamera() { if (getCamera().getYaw() > 1500 || getCamera().getYaw() < 500) { if (Config.EXTREME_DEBUGGING) { log("Our yaw: "+getCamera().getYaw()+", needs to be reset! "+Misc.getTimeStamp()); } getCamera().rotateToYaw(Calculations.random(1, 10)); if (getCamera().getPitch() < 200) { if (Config.EXTREME_DEBUGGING) { log("Our pitch: "+getCamera().getPitch()+", needs to be reset! "+Misc.getTimeStamp()); } getCamera().rotateToPitch(383); } } } public void checkForMods() { if (!getPlayers().all(f -> f != null && f.getName().contains("Mod")).isEmpty()) { log("We just found a JMod! Logged out, quickly... Time: " + Misc.getTimeStamp()); getTabs().logout(); stop(); } } public void handleTrading() { Player target = getPlayers().closest(Local.lavaBoss); //(p -> p != null && p.getName().equals(Local.lavaBoss)).get(0); if (target == null) { log("Attempting to trade a nulled master! We're lost! Error #404: "+Misc.getTimeStamp()); return; } if (!innerAltarArea.contains(target)) { log("The master is not inside the altar area. Eror #405"); return; } if (!getTrade().isOpen()) { //if the trade is not open if (Config.EXTREME_DEBUGGING) { log("trade is not open"); } if (target.getAnimation() == -1) { //and out master isn't busy if (Config.EXTREME_DEBUGGING) { log("master is not busy"); } if (lastTrade.elapsed() > Config.TRADE_COOLDOWN || skipFirstTradeWait) { //and we aren't spamming the master if (skipFirstTradeWait) { skipFirstTradeWait = false; } if (Config.EXTREME_DEBUGGING) { log("we're passed countdown"); } if (getTrade().tradeWithPlayer(target.getName())) { //we can try to trade master if (Config.EXTREME_DEBUGGING) { log("we try to trade master"); } lastTrade.reset(); //reset timer acc1 = false; acc2 = false; smallSleep(); //sleep on that thought } } } } else if (getTrade().isOpen(1)) { //if the trade(1) is open if (!getTrade().contains(true, 1, "Pure essence")) { if (getTrade().addItem("Pure essence", Config.ESSENCE_TO_WITHDRAW)) { if (Config.EXTREME_DEBUGGING) { log("Attempting to trade "+Config.ESSENCE_TO_WITHDRAW+" x Pure Essence"); } smallSleep(); } } if (getTrade().acceptTrade() && !acc1) { // accept trade if (Config.EXTREME_DEBUGGING) { log("Accepting trade (1)"); } acc1 = true; smallSleep(); } } else if (getTrade().isOpen(2) && !acc2) { //if the trade(2) is open if (getTrade().acceptTrade()) { // accept trade if (Config.EXTREME_DEBUGGING) { log("Accepting trade (2)"); } acc2 = true; smallSleep(); } } } public boolean needToBank() { if (getTrade().isOpen()) { return false; } if (!getInventory().contains("Pure essence") || getInventory().count("Pure essence") < Config.NEED_BANK_THRESHOLD) { return true; } return false; } public void handleBanking() { if (!getBank().isOpen()) { if (getBank().openClosest()) { smallSleep(); } } else { //bank is open if (!getBank().placeHoldersEnabled()) { getBank().togglePlaceholders(true); smallSleep(); } if (getBank().getWithdrawMode() == BankMode.NOTE) { getBank().setWithdrawMode(BankMode.ITEM); smallSleep(); } if (!getInventory().isEmpty()) { getBank().depositAllItems(); smallSleep(); } getBank().withdraw("Pure essence", Config.ESSENCE_TO_WITHDRAW); //smallSleep(); //getBank().close(); smallSleep(); } } /** * Useful for small sleeps * @return an int between 200 and 600 */ public static void smallSleep() { sleep(Calculations.random(200, 600)); } /** * Useful for medium sleeps * @return an int between 600 and 1400 */ public static void medSleep() { sleep(Calculations.random(600, 1400)); } /** * Useful for long sleeps * @return an int between 1400 and 4500 */ public static void longSleep() { sleep(Calculations.random(1400, 4500)); } /** * Useful for a small afk * @return an int between 3500 and 6000 */ public static void smallAfkSleep() { sleep(Calculations.random(3500, 6000)); } @Override public void onExit() { Misc.printDev("Ended: "+Misc.getTimeStamp()); } public void onPaint(Graphics2D g) { g.setColor(Color.WHITE); g.setFont(new Font("Arial", 1, 11)); g.drawString("Time Running: " + t.formatTime(), 25, 50); } @Override public void onGameMessage(Message msg) { if (Config.EXTREME_DEBUGGING) { log("onGameMessage trading offer"); } } @Override public void onPlayerMessage(Message msg) { if (Config.EXTREME_DEBUGGING) { log("onPlayerMessage trading offer"); } } @Override public void onPrivateInMessage(Message msg) { if (Config.EXTREME_DEBUGGING) { log("onPrivateInMessage trading offer"); } } @Override public void onPrivateOutMessage(Message msg) { if (Config.EXTREME_DEBUGGING) { log("onPrivateOutMessage trading offer"); } } @Override public void onTradeMessage(Message msg) { //trade master log("onTradeMessage trading offer"); Player target = getPlayers().closest(Local.lavaBoss); if (target == null) { log("Attempting to trade a nulled master! We're lost! Error #404: "+Misc.getTimeStamp()); return; } if (getTrade().tradeWithPlayer(target.getName())) { //we can try to trade master if (Config.EXTREME_DEBUGGING) { log("we try to trade master"); } lastTrade.reset(); //reset timer acc1 = false; acc2 = false; smallSleep(); //sleep on that thought } } }
package be.peopleware.jsf_II.persistence; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.event.ActionEvent; import javax.servlet.ServletRequestListener; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import be.peopleware.bean_V.CompoundPropertyException; import be.peopleware.exception_I.TechnicalException; import be.peopleware.jsf_II.FatalFacesException; import be.peopleware.jsf_II.RobustCurrent; import be.peopleware.jsf_II.util.AbstractUnmodifiableMap; import be.peopleware.persistence_II.IdNotFoundException; import be.peopleware.persistence_II.PersistentBean; import be.peopleware.persistence_II.dao.AsyncCrudDao; import be.peopleware.servlet.navigation.NavigationInstance; import be.peopleware.servlet.sessionMopup.Removable; import be.peopleware.servlet.sessionMopup.Skimmable; /** * <p>Handler for {@link PersistentBean} detail CRUD pages.</p> * <p>This handler can be used in a number of circumstances. The main use * is as the backing bean for a detail CRUD page of an instance of semantics. * For this to work, the handler needs a {@link #getAsyncCrudDao()} the * {@link #getPersistentBeanType()} filled out, * needs to know the previous {@link #getViewMode()}, * and it needs an {@link #getInstance() instance}.</p> * <p>The instance can be set explicitly with {@link #setInstance(PersistentBean)}. * This immediately also sets the {@link #getId()}. If the * {@link #getInstance() instance} is <code>null</code> when it is requested, * we will retrieve the instance with id {@link #getId()} and type * {@link #getPersistentBeanType()} from persistent storage, and cache it. If at this time * {@link #getId()} is <code>null</code>, a new instance of {@link #getPersistentBeanType()} * will be created.</p> * <p>In conclusion this means that, before an instance of this class can be used, * you need to set the<p> * <ul> * <li>the {@link #setPersistentBeanType(Class) type} and</li> * <li>the {@link #setViewMode(String) previous view mode}, and</li> * <li>either * <ul> * <li>an {@link #setInstance(PersistentBean) instance},</li> * <li>or * <ul> * <li>a {@link #setDaoVariableName(String) dao variable name}, and</li> * <li>an {@link #setId(Long) id}.</li> * </ul> * </li> * </ul> * </li> * </ul> * * <h2>States &amp; Transitions</h2> * <p>An <code>InstanceHandler</code> has 4 states and * a number of state transitions. The states are actually <dfn>view modes</dfn> * for the JSF page.</p> * <img src="doc-files/persistence.gif" style="width: 100%;" /> * * <h3>Retrieving the {@link be.peopleware.persistence_II.PersistentBean Instance}</h3> * <p>With each HTTP request (except the request for a screen to fill out the * values for a new instance, the request to create a new instance, the request * to show a list of persistent beans and a request to go back to the * previous page) we expect the * {@link be.peopleware.persistence_II.PersistentBean#getId() primary key of a * persistent bean} as request parameter. This id is filled in in the handler's * {@link #getId()} property. Before * the Update Model Values phase is reached, we need to load the * {@link be.peopleware.persistence_II.PersistentBean} with * {@link #getId() this id} and type {@link #getPersistentBeanType()} from * persistent storage. This instance will be stored in the * {@link #getInstance() instance handler property}.</p> * <p>It is always possible that no instance with {@link * #getId() this id} and {@link #getPersistentBeanType() type} can be found * in persistent storage, because it never existed, or because such instance * was removed in-between user requests from persistent storage. Whenever this * occurs, the user will be directed back to the page he originally came from, * before he accessed this page.</p> * <p>Again it is possible that the previous instance does not exist in persistent * storage anymore, so this process is recursive, until the first page after * login is reached.</p> * <p>If the user itself is removed from the system while logged in, the session * will be stopped as early as possible, and the user will return to the login * page.</p> * <p>HOW IS THIS ACHIEVED?</p> * <h3>Entry</h3> * <p>The state machine is entered by a navigation request (<code>navigate(id) * [found(id)]</code>), or a request to edit a new instance * (<code>editNew()</code>).</p> * <p>Entry is requested always from the handler of a previous page. When entry * succeeds, the previous page is recorded in the TODO NavigationStack, so we * can go back to it later.</p> * <h3>Display</h3> * <p>In view mode <code>display</code>, the data of the {@link * be.peopleware.persistence_II.PersistentBean} is shown, in a non-editable * way.</p> * <h4>delete</h4> * <p>From this state, we can try to delete the {@link * be.peopleware.persistence_II.PersistentBean}. When the bean is not found in * persistent storage (<code>delete(id) [! found(id)]</code>), the user is * brought back to the previous page, and a message is shown. If the bean is * found in persistent storage, deletion might fail for semantic reasons * (<code>delete(id) [found(id) &amp;&amp; exception]</code>). In this case, we * stay in <code>display</code> state, and show a message to the user about the * exception. When deletion succeeds (<code>delete(id) [found(id) &amp;&amp; * nominal] / DELETE</code>), the instance is deleted from persistent storage, * and the handler goes to the <code>deleted</code> state.</p> * <p>This is implemented in the action method {@link #delete()}. The user can * request the deletion by clicking a button defined as:</p> * <pre> * &lt;h:commandButton action=&quot;#{<var>myHandler</var>.delete}&quot; * value=&quot;#{<var>myHandler</var>.buttonLabels['delete']}&quot; * rendered=&quot;#{<var>myHandler</var>.viewMode eq 'display'}&quot; * immediate=&quot;true&quot;/&gt; * </pre> * <h4>edit</h4> * <p>In <code>display</code> mode, the user can also ask for <code>edit</code> mode. When the * bean is not found in persistent storage (<code>edit(id) [! found(id)]</code>), * the user is brought back to the previous page, and a message is shown. If the * bean is found in persistent storage (<code>edit(id) [found(id)]</code>), the * handler goes to the <code>edit</code> state.</p> * <p>This is implemented in action method {@link #edit()}. The user can request * view mode <code>edit</code> by clicking a button defined as:</p> * <pre> * &lt;h:commandButton action=&quot;#{<var>myHandler</var>.edit}&quot; * value=&quot;#{<var>myHandler</var>.buttonLabels['edit']}&quot; * rendered=&quot;#{<var>myHandler</var>.viewMode eq 'display'}&quot; * immediate=&quot;true&quot;/&gt; * </pre> * <h4>goBack</h4> * <p>From display mode, the user can request to go back to the previous * page (<code>goBack()</code>). If the previous instance cannot be found, this * action propagates the user to instances visited earlier, recursively.</p> * <p>HOW IS THIS IMPLEMENTED? The user can request to go back by clicking a * button defined as:</p> * <pre> * MUDO (jand) NO IDEA YET * </pre> * <h4>navigate</h4> * <p>Finally, the user can request to navigate to another page * (<code>nextPageHandler.navigate(nextPageId) [found(nextPageId)]</code>). * Presumably, he clicks on a link to navigate to a related bean. This state * transition is a placeholder for any number of possible navigation points in * the page. The intention is to show the user a page for the next instance, in * <code>display</code> mode. It is possible that this next instance cannot be * found in persistent storage <code>(nextPageHandler.navigate(nextPageId) [! * found(nextPageId)]</code>). In that case, we stay in <code>display</code> * state in this page, and show the user a message.</p> * <p>This is not implemented in this generic handler.</p> * <h3>Edit</h3> * <p>In view mode <code>edit</code>, the data of the {@link * be.peopleware.persistence_II.PersistentBean} is shown, in an editable way. This * means that the user can change the current values of the properties of the * persistent bean or fill in the value of properties that were not specified * before.</p> * <h4>cancel</h4> * <p>From this state, we can try to return to the <code>display</code> state * without applying the changes. When the bean is not found in persistent storage * (<code>cancel(id) [!found(id)]</code>), the user is brought back to the * previous page, and a message is shown. If the bean is found in persistent * storage (<code>cancel(id) [found(id)]</code>), we return to the * <code>display</code> state and the values that were filled in in the * <code>edit</code> state are forgotten; this means that the old * values of the bean are shown in the <code>display</code> state and that the * persistent bean is unchanged.</p> * <p>This is implemented in action method {@link #cancelEdit()}. The user can * request cancellation by clicking a button defined as:</p> * <pre> * &lt;h:commandButton action=&quot;#{<var>myHandler</var>.cancelEdit}&quot; * value=&quot;#{<var>myHandler</var>.buttonLabels['cancel']}&quot; * rendered=&quot;#{<var>myHandler</var>.viewMode eq 'edit'}&quot; * immediate=&quot;true&quot;/&gt; * </pre> * <h4>update</h4> * <p>From the <code>edit</code> state, we can try to update the {@link * be.peopleware.persistence_II.PersistentBean} with the values filled in by the * user. When the bean is not found in persistent storage (<code>update(id, data) * [! found(id)]</code>), the user is brought back to the * previous page, and a message is shown. If the bean is found in persistent * storage, updating might fail for semantic reasons (<code>update(id, data) * [found(id) &amp;&amp; exception]</code>). In this case, we stay in the * <code>edit</code> state, and show a message to the user about the exception. * When updating succeeds (<code>update(id, data) [found(id) &amp;&amp; * nominal]</code>), the handler goes to the <code>display</code> state and the * persistent bean is updated in persistent storage.</p> * <p>This is implemented in action method {@link #update()}. The user can request * storing the new information by clicking a button defined as:</p> * <pre> * &lt;h:commandButton action=&quot;#{<var>myHandler</var>.update}&quot; * value=&quot;#{<var>myHandler</var>.buttonLabels['commit']}&quot; * rendered=&quot;#{<var>myHandler</var>.viewMode eq 'edit'}&quot; /&gt; * </pre> * <h3>Edit New</h3> * <p>In view mode <code>editNew</code>, the user is shown a page, with empty, * editable fields for him to fill in. These fields represent a new bean of type * {@link #getPersistentBeanType()}. It is * possible that some data is filled out when this page is shown, e.g., default * data, or good guesses.</p> * <h4>cancel</h4> * <p>If the user changes his mind, he can request to cancel the * <code>editNew</code> state (<code>cancel()</code>). This amounts to the user * issuing a request to go back to the previous page (<code>goBack()</code>). If * the previous instance cannot be found, this action propagates the user to * instances visited earlier, recursively.</p> * <p>This is implemented in action method {@link #cancelEditNew()}. The user can * request cancellation by clicking a button defined as:</p> * <pre> * &lt;h:commandButton action=&quot;#{<var>myHandler</var>.cancelEditNew}&quot; * value=&quot;#{<var>myHandler</var>.buttonLabels['cancel']}&quot; * rendered=&quot;#{<var>myHandler</var>.viewMode eq 'editNew'}&quot; * immediate=&quot;true&quot;/&gt; * </pre> * <h4>create</h4> * <p>From view mode <code>editNew</code>, the user can submit data for the actual * creation of a new bean in persistent storage. This can fail with semantic * exceptions (<code>create(data) [exception]</code>). We stay in the * <code>editNew</code> state, and show the user messages about the errors. If * creation succeeds (<code>create(data) [nominal]</code>), the new instance is * created in persistent storage, and the handler goes to the * <code>display</code> state.</p> * <p>This is implemented in action method {@link #create()}. The user can request * storing the new information by clicking a button defined as:</p> * <pre> * &lt;h:commandButton action=&quot;#{<var>myHandler</var>.create}&quot; * value=&quot;#{<var>myHandler</var>.buttonLabels['commit']}&quot; * rendered=&quot;#{<var>myHandler</var>.viewMode eq 'editNew'}&quot; /&gt; * </pre> * <h3>Deleted</h3> * <p>In view mode <code>deleted</code>, the data of the deleted {@link * be.peopleware.persistence_II.PersistentBean} is shown, in a non-editable way, * with visual feedback about the fact that it was deleted (e.g., strikethrough). * <h4>goBack</h4> * <p>From this mode, the only action of the user can be to request to go back to * the previous page (<code>goBack()</code>). If the previous instance cannot be * found, this action propagates the user to instances visited earlier, * recursively.</p> * <p>HOW IS THIS IMPLEMENTED? BUTTON?</p> * <h2>Remembering State</h2> * <p>With this setup, the only state that must be remembered in-between HTTP * requests is the id of the {@link PersistentBean} we are working with, and the * view mode of the handler. By storing this information in the actual HTML page, * we essentially make the handler stateless.</p> * <p>This information needs to be filled out in the handler properties ({@link * #getId()} and {@link #getViewMode()} before the action methods are executed. This * can be achieved by storing these values in hidden text fields in the JSF page * with the <code>immediate</code> attribute set to <code>true</code>:</p> * <pre> * &lt;h:inputHidden value=&quot;#{<var>myHandler</var>.id}&quot; immediate=&quot;true&quot; /&gt; * &lt;h:inputHidden value=&quot;#{<var>myHandler</var>.viewMode}&quot; immediate=&quot;true&quot; /&gt;</pre> * <p> * Since the <code>immediate</code> attribute of these inputHidden tags is set * to true, the corresponding setters {@link #setId(Long)} and * {@link #setViewMode(String)} will be called early in the request / response * cycle, namely during the Apply Request Values Phase. We give the * {@link #setId(Long)} method side-effects that initialise the persistent bean * and all other resources that are needed during the request / response cycle. * In this way, the handler is initialised early in the request / response cycle. * This is necessary, because, e.g., for some of the action methods * ({@link #update()} and {@link #create()}), the bean must be available in * {@link #getInstance()} before the Update Model Values phase, to receive * values from the UIView.</br> * If no instance with the requested id can be found in persistent storage, * {@link #getInstance()} will be <code>null</code> afterwards to signal this. * <br /> * The {@link #setId(Long)} method cannot however be used to create a new bean * for entry into view mode <code>editNew</code>, and for the {@link #create()} * action method. This is because the setter {@link #setId(Long)} will not be * called when the request parameter for the id is <code>null</code>, * since the id property is <code>null</code> already (see below). * Therefore, creating a new bean is done as a side-effect in the * {@link #setViewMode(String)} method, whenever the requested view mode * is <code>editNew</code>.</p> * <p>To make sure that the hidden fields described above contain the correct values at the * beginning of a request / response cycle, the corresponding handler must hold * the correct values for the properties {@link #getId()} and {@link #getViewMode()} * before the Render Response phase of the previous cycle is entered.</p> * <p>To guarantee that the setters {@link #setId(Long)} and * {@link #setViewMode(String)} are called during the Apply Request Values * Phase, the {@link #getId()} and {@link #getViewMode()} should be set to null * after the Render Response Phase. This is because * the {@link #setId(Long)} (resp. {@link #setViewMode(String)}) method is only * executed when the old value of {@link #getId()} (resp. {@link #getViewMode()}) * and the <code>id</code> (resp. <code>viewMode</code>) that comes as a * parameter with the HTTP request are different. To achieve this, the * {@link #getId()} (resp. {@link #getViewMode()}) should be set to null at the * end of each cycle.</p> * <p>JavaServer Faces does not offer the possibility to do anything after the * response is rendered. So we need an extra mechanism that clears the handler. * This is done by a special {@link ServletRequestListener} that magically knows which * handler to reset.</p> * <h2>Not Remembering State</h2> * <p>After the response is rendered completely, the {@link #getId()} and {@link * #getInstance()} (and possibly other resources) are no longer needed, and * should be set to <code>null</code>, to avoid clogging memory in-between user * requests. Setting the {@link #getId()} and {@link #getViewMode()} to null * is also necessary for functional reasons, as described above. Releasing * resources can be achieved by setting the handlers in request scope.</p> * <h2>Configuration</h2> * <p>This class requires the definition of 2 filters in * <kbd>WEB-INF/web.xml</kbd>:</p> * <pre> * &lt;listener&gt; * &lt;listener-class&gt;be.peopleware.servlet_I.hibernate.SessionFactoryController&lt;/listener-class&gt; * &lt;listener-class&gt;be.peopleware.servlet_I.hibernate.SessionInView&lt;/listener-class&gt; * &lt;/listener&gt; * </pre> * * * @author Jan Dockx * @author Nele Smeets * @author Peopleware n.v. * * @invar (getViewMode() != null) * ? isViewMode(getViewMode()) * : true; * @invar (getInstance() != null) * ? getType().isInstance(getInstance()) * : true; * @invar getViewMode() != null; * * @idea (jand) gather viewmode in separate class * @mudo (jand) security */ public class InstanceHandler extends PersistentBeanHandler { /*<section name="Meta Information">*/ /** {@value} */ public static final String CVS_REVISION = "$Revision$"; /** {@value} */ public static final String CVS_DATE = "$Date$"; /** {@value} */ public static final String CVS_STATE = "$State$"; /** {@value} */ public static final String CVS_TAG = "$Name$"; /*</section>*/ private static final Log LOG = LogFactory.getLog(InstanceHandler.class); public InstanceHandler() { LOG.debug("constructor of InstanceHandler"); } /*<property name="id">*/ /** * The id of the {@link PersistentBean} that is handled by the requests. * The id is not changed by {@link #skim()}. * * @basic * @init null; */ public final Long getId() { return $id; } /** * Store the given id in {@link #getId()}. * * @param id * The id of the {@link PersistentBean} that will be handled in the * requests. * @post new.getId().equals(id); */ public final void setId(final Long id) { // set the id $id = id; LOG.debug("id of " + this + " set to " + id); } /** * <p>Set {@link #getId()} from the request parameter with name * <code>name</code>. If no such parameter is found, we do * nothing.</p> * <p>For some reason, expressions like * <code>#{param.myParamName}</code> * return <code>0</code> when used in the <kbd>faces-config.xml</kbd>, where * there is a parameter like <code>myParamName=4567</code> in the HTTP * request. This is a workaround that does seem to work.</p> */ public final void setIdFromRequestParameterName(String name) { Map requestParameters = RobustCurrent.paramMap(); String idString = (String)requestParameters.get(name); if (idString != null) { if (idString.equals(EMPTY)) { setId(null); } else { try { Long id = Long.valueOf(idString); // NumberFormatException setId(id); } catch (NumberFormatException nfExc) { RobustCurrent.fatalProblem("The id value in the request is not a Long (" + idString + ")", nfExc, LOG); // IDEA (jand) this is not fatal; do goback() } } } // else (idString not in request param), do NOP } /** * The id of the {@link PersistentBean} that will be handled * by the requests. */ private Long $id; /*</property>*/ /*<property name="viewMode">*/ /** {@value} */ public final static String VIEWMODE_EDITNEW = "editNew"; /** {@value} */ public final static String VIEWMODE_DELETED = "deleted"; /** * { {@link #VIEWMODE_EDITNEW}, {@link #VIEWMODE_DELETED} }; */ public final static String[] VIEWMODES = {VIEWMODE_EDITNEW, VIEWMODE_DELETED}; /** * Does <code>viewMode</code> represent a valid view mode? * * @param viewMode * The viewMode to be checked. * @return super.isViewMode(viewMode) || * Arrays.asList(VIEWMODES).contains(viewMode); */ public boolean isValidViewMode(String viewMode) { return super.isValidViewMode(viewMode) || Arrays.asList(VIEWMODES).contains(viewMode); } /** * Returns true when the handler is editable, i.e. when the view mode is * equal to {@link PersistentBeanHandler#VIEWMODE_EDIT} or * {@link #VIEWMODE_EDITNEW}. Returns <code>false</code> otherwise. * * This method is introduces to avoid writing * <code>myHandler.viewmode eq 'edit' or myHandler.viewmode eq 'editNew'</code> * and * <code>myHandler.viewmode neq 'edit' and myHandler.viewmode neq 'editNew'</code> * as value of the rendered attributes of in- and output fields in JSF pages, * which is cumbersome. * Now we can write * <code>myHandler.inViewModeEditOrEditNew</code> * and * <code>not myHandler.inViewModeEditOrEditNew</code>. * * @return getViewMode().equals(PersistentBeanHandler.VIEWMODE_EDIT) || * getViewMode().equals(VIEWMODE_EDITNEW); * @throws FatalFacesException * getViewMode() == null; * * @deprecated */ public final boolean isInViewModeEditOrEditNew() throws FatalFacesException { if (getViewMode() == null) { RobustCurrent.fatalProblem("ViewMode is null", LOG); return false; } else { return getViewMode().equals(PersistentBeanHandler.VIEWMODE_EDIT) || getViewMode().equals(VIEWMODE_EDITNEW); } } /** * @result false ? (! getViewMode().equals(VIEWMODE_EDITNEW)); */ public boolean isShowFields() throws FatalFacesException { return super.isShowFields() || getViewMode().equals(VIEWMODE_EDITNEW); } /*</property>*/ /*<property name="instance">*/ /** * <p>The {@link PersistentBean} that is handled in the requests. * If {@link #getStoredInstance()} is not <code>null</code>, * it is returned. If it is <code>null</code>, an instance * is loaded from persistent storage with {@link #getAsyncCrudDao()}, * with type {@link #getPersistentBeanType()} and id {@link #getId()}. * If {@link #getStoredInstance()} and {@link #getId()} are * both <code>null</code>, a fresh instance of {@link #getPersistentBeanType()} * will be created using the default constructor. If * {@link #getPersistentBeanType()} is <code>null</code> when * {@link #getStoredInstance()} is <code>null</code>, * we cannot procede.</p> * <p>In the default implementation, {@link #skim()} removes the instances if * {@link #getId()} is not <code>null</code>. * * @return new.getStoredInstance(); * @post ((getStoredInstance() == null) && (getId() != null)) ? * new.getStoredInstance() == getDao().retrievePersistentBean(getId(), getType()); * @post ((getStoredInstance() == null) && (getId() == null)) ? * new.getStoredInstance() == getType().fresh; * @throws FatalFacesException * (getStoredInstance() == null) && (getType() == null); * @throws FatalFacesException * (getStoredInstance() == null) && (getId() != null) && problems loading bean from DB; */ public final PersistentBean getInstance() throws FatalFacesException { LOG.debug("instance requested; id = " + getId()); if ($instance == null) { LOG.debug("instance is not cached"); if (getPersistentBeanType() == null) { RobustCurrent.fatalProblem("should load instance from db or create fresh instance, " + "but type is null", LOG); } if (getId() != null) { LOG.debug("id = " + getId() + "; loading from DB"); $instance = loadInstance(); } else { LOG.debug("id is null; creating fresh"); $instance = createInstance(); } LOG.debug("instance = " + $instance); } else { LOG.debug("returning instance from cache: " + $instance); } return $instance; } /** * @basic * @init null; */ public final PersistentBean getStoredInstance() { return $instance; } public final void setInstance(PersistentBean instance) throws IllegalArgumentException { LOG.debug("setting instance to " + instance); if ((instance != null) && (! getPersistentBeanType().isAssignableFrom(instance.getClass()))) { throw new IllegalArgumentException("instance " + instance + " is not a subtype of " + getPersistentBeanType()); } $instance = instance; if (instance != null) { setId(instance.getId()); } else { // else, we do NOT set the ID to null LOG.debug("instance set to null; id is left untouched (" + getId() + ")"); } } /** * {@link #postLoadInstance(PersistentBean)} is called on the fresh * bean to do whatever configuration necessary. * * @pre getDao() != null; * @throws FatalFacesException * {@link AsyncCrudDao#retrievePersistentBean(java.lang.Long, java.lang.Class)} / {@link TechnicalException} * @throws FatalFacesException * MUDO (jand) other occurences must be replaced by goBack() */ protected final PersistentBean loadInstance() throws FatalFacesException { LOG.debug("loading instance with id = " + getId() + " and type = " + getPersistentBeanType()); assert getAsyncCrudDao() != null; PersistentBean result = null; try { if (getId() == null) { RobustCurrent.fatalProblem("id is null", LOG); // MUDO (jand) replace with goback? } if (getPersistentBeanType() == null) { RobustCurrent.fatalProblem("type is null", LOG); // MUDO (jand) replace with goback? } LOG.debug("retrieving persistent bean with id " + getId() + " and type " + getPersistentBeanType() + "..."); result = getAsyncCrudDao().retrievePersistentBean(getId(), getPersistentBeanType()); // IdNotFoundException, TechnicalException assert result != null; assert result.getId().equals(getId()); assert getPersistentBeanType().isInstance(result); if (LOG.isDebugEnabled()) { // if makes that there really is lazy loading if not in debug LOG.debug("retrieved persistent bean is " + result); } LOG.debug("Calling postLoadInstance"); postLoadInstance(result); LOG.debug("retrieved instance after postLoadInstance: " + result); } catch (IdNotFoundException infExc) { // this will force $instance null LOG.info("could not find instance of type " + getPersistentBeanType() + " with id " + getId(), infExc); // MUDO goback() instead of exception RobustCurrent.fatalProblem("could not find persistent bean with id " + getId() + " of type " + getPersistentBeanType(), infExc, LOG); } catch (TechnicalException tExc) { RobustCurrent.fatalProblem("could not retrieve persistent bean with id " + getId() + " of type " + getPersistentBeanType(), tExc, LOG); } return result; } /** * Method called by {@link #loadInstance()}, * to do additional configuration of retrieved beans of type * {@link #getPersistentBeanType()}. * This default does nothing, but subclasses should overwrite * when needed. * * @pre pb != null; * @pre pb.getClass() == getPersistentBeanType() */ protected void postLoadInstance(PersistentBean pb) { // NOP } /** * Method to be called after Render Response phase, to clear * semantic data from the session. * * @post $instance == null; */ private void releaseInstance() { $instance = null; } /** * The {@link PersistentBean} that is handled in the requests. */ private PersistentBean $instance; /*</property>*/ /** * This implementation automatically delegates this call * to all {@link #getUsedAssociationHandlers()}. */ protected void updateValues() { if (getInstance() == null) { RobustCurrent.fatalProblem("could not update values of null instance", LOG); } Iterator iter = getUsedAssociationHandlers().values().iterator(); while (iter.hasNext()) { PersistentBeanHandler pbh = (PersistentBeanHandler)iter.next(); pbh.updateValues(); } super.updateValues(); } /** * <p>This method should be called to navigate to detail page * for this {@link #getInstance()} in <code>viewMode</code>.</p> * <p>This handler is made available to the JSP/JSF page in request scope, * as a variable with name * {@link #RESOLVER}{@link PersistentBeanHandlerResolver#handlerVariableNameFor(Class) .PersistentBeanHandlerResolver#handlerVariableNameFor(getType())}. * And we navigate to {@link #getViewId()}.</p> * <p>The {@link #getPersistentBeanType() type} and an {@link #getInstance()} should * be set before this method is called.</p> * * @post isViewMode(viewMode) ? new.getViewMode().equals(viewMode) * : new.getViewMode().equals(VIEWMODE_DISPLAY); * @post RobustCurrent.lookup(RESOLVER.handlerVariableNameFor(getType())) == this; * @throws FatalFacesException * getType() == null; * @throws FatalFacesException * getInstance() == null; * * @mudo (jand) security */ public final void navigateHere(String viewMode) throws FatalFacesException { LOG.debug("InstanceHandler.navigate called; id = " + getId() + ", instance = " + getInstance()); if (getInstance() == null) { LOG.fatal("cannot navigate to detail, because no instance is set (" + this); } super.navigateHere(viewMode); } /** * @pre getType() != null; * @return VIEW_ID_PREFIX + s/\./\//(getType().getName()) + VIEW_ID_SUFFIX; */ public String getViewId() { assert getPersistentBeanType() != null : "type cannot be null"; String typeName = getPersistentBeanType().getName(); typeName = typeName.replace('.', '/'); return VIEW_ID_PREFIX + typeName + VIEW_ID_SUFFIX; } public void putInSessionScope() { RESOLVER.putInSessionScope(this); } /** * <p>Action method to navigate to collection page for this * {@link #getPersistentBeanType()} via a call to {@link CollectionHandler#navigateHere()}.</p> * <p>The collection handler handler is made available to the JSP/JSF page in request scope, * as a variable with the appropiate name (see {@link CollectionHandler#navigateHere()}. * And we navigate to {@link CollectionHandler#getViewId()}.</p> * * @post (CollectionHandler)CollectionHandler.RESOLVER.handlerFor(getType(), getDao()).navigateHere(); * @except (CollectionHandler)CollectionHandler.RESOLVER.handlerFor(getType(), getDao()).navigateHere(); */ public final void navigateToList(ActionEvent aEv) throws FatalFacesException { LOG.debug("InstanceHandler.navigateToList called"); CollectionHandler handler = (CollectionHandler)CollectionHandler.RESOLVER.handlerFor(getPersistentBeanType(), getDaoVariableName()); LOG.debug("created collectionhandler for type " + getPersistentBeanType() + ": " + handler); handler.navigateHere(aEv); } /** * This is an action method that should be called by a button in the JSF * page to go to edit mode. * * A more detailed description of this action method can be found in the * class description. * * @post (getInstance() == null) * ? 'return to previous page' && * result.equals(NO_INSTANCE) * : true; * @post (getInstance() != null && !getViewMode().equals(VIEWMODE_DISPLAY)) * ? getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_DISPLAY)) * ? getViewMode().equals(VIEWMODE_EDIT) && * result.equals(null) * : true; * @mudo (jand) security * public final String edit(); */ /** * This is an action method that should be called by a button in the JSF * page to update a persistent bean in persistent storage. * * A more detailed description of this action method can be found in the * class description. * * @post (getInstance() == null) * ? 'return to previous page' && * result.equals(NO_INSTANCE) * : true; * @post (getInstance() != null && !getViewMode().equals(VIEWMODE_EDIT)) * ? getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDIT) * && 'updateValues generated messages') * ? getViewMode().equals(VIEWMODE_EDIT) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDIT) * && 'updateValues succeeded without messages' * && 'update in storage generates no semantic exceptions') * ? 'bean is updated in persistent storage' && * getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDIT) * && 'updateValues succeeded without messages' * && 'update in storage generates semantic exceptions') * ? getViewMode().equals(VIEWMODE_EDIT) && * result.equals(null) * : true; * @throws FatalFacesException * When a TechnicalException is thrown by: * {@link AsyncCrudDao#startTransaction()} * {@link AsyncCrudDao#updatePersistentBean(be.peopleware.persistence_II.PersistentBean)} * {@link AsyncCrudDao#commitTransaction(be.peopleware.persistence_II.PersistentBean)} * {@link AsyncCrudDao#cancelTransaction()} * public String update() throws FatalFacesException; */ /** * The actual update in persistent storage. No need to handle transaction: * it is open. * * @todo (jand) for now, this method should start and commit the transaction; * one the commitTransaction method no longer needs the stupid * PB argument, this can be moved out. */ protected PersistentBean actualUpdate(AsyncCrudDao dao) throws CompoundPropertyException, TechnicalException, FatalFacesException { dao.updatePersistentBean(getInstance()); // TechnicalException, CompoundPropertyException return getInstance(); // TODO (jand) stupid return stuff } /** * This method should be called from within another handler to pass * a newly created persistent bean of type {@link #getPersistentBeanType()} and show this * bean in editNew mode. To do this, the handler should be properly * initialised. * * A more detailed description of this action method can be found in the * class description. * * To initialise the handler properly, the following two steps are taken: * 1. The given {@link PersistentBean} is stored in {@link #getInstance()}. * If the given bean is not effective, has an effective id (i.e. is not * newly created), or is not of type {@link #getPersistentBeanType()}, this is signalled * to the user by throwing an InvalidBeanException. * 2. We go to editNew mode. * * @param instance * The {@link PersistentBean} that should be displayed. * @post new.getInstance() == instance; * @post new.getViewMode().equals(VIEWMODE_EDITNEW); * @throws InvalidBeanException * instance == null || * instance.getId() != null || * !getType().isInstance(instance); */ public final void editNew(PersistentBean instance) throws InvalidBeanException { LOG.debug("InstanceHandler.editNew called; a new instance is stored in the handler"); if (instance == null || instance.getId() != null || !getPersistentBeanType().isInstance(instance)) { throw new InvalidBeanException(instance, getPersistentBeanType()); } $instance = instance; assert getInstance() != null; assert getInstance().getId() == null; assert getPersistentBeanType().isInstance(instance); setViewMode(VIEWMODE_EDITNEW); LOG.debug("Stored new persistent bean successfully"); } public class InvalidBeanException extends Exception { public InvalidBeanException(PersistentBean persistentBean, Class type) { $persistentBean = persistentBean; $type = type; } public PersistentBean getPersistentBean() { return $persistentBean; } public Class getType() { return $type; } private PersistentBean $persistentBean; private Class $type; } /** * This is an action method that should be called by a button in the JSF * page to add a newly created persistent bean to persistent storage. * * A more detailed description of this action method can be found in the * class description. * * @post (getInstance() == null) * ? 'return to previous page' && * result.equals(NO_INSTANCE) * : true; * @post (getInstance() != null && !getViewMode().equals(VIEWMODE_EDITNEW)) * ? 'return to previous page' && * result.equals(INCORRECT_VIEWMODE) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDITNEW) * && 'updateValues generated messages') * ? getViewMode().equals(VIEWMODE_EDITNEW) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDITNEW) * && 'updateValues succeeded without messages' * && 'update in storage generates no semantic exceptions') * ? 'bean is created in persistent storage' && * new.getId() == new.getInstance().getId() * getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDITNEW) * && 'updateValues succeeded without messages' * && 'update in storage generates semantic exceptions') * ? getViewMode().equals(VIEWMODE_EDITNEW) && * result.equals(null) * : true; * @throws FatalFacesException * When a TechnicalException is thrown by: * {@link AsyncCrudDao#startTransaction()} * {@link AsyncCrudDao#createPersistentBean(be.peopleware.persistence_II.PersistentBean)} * {@link AsyncCrudDao#commitTransaction(be.peopleware.persistence_II.PersistentBean)} * {@link AsyncCrudDao#cancelTransaction()} */ public final String create() throws FatalFacesException { LOG.debug("InstanceHandler.create called; a new bean is created and is "+ "already partially updated"); LOG.debug("persistentBean: " + getInstance()); try { AsyncCrudDao dao = getAsyncCrudDao(); try { if (getInstance() == null) { return goBack(NO_INSTANCE); } if (!getViewMode().equals(VIEWMODE_EDITNEW)) { return goBack(INCORRECT_VIEWMODE); } updateValues(); LOG.debug("The bean is now fully updated"); LOG.debug("persistentBean: " + getInstance()); if (RobustCurrent.hasMessages()) { // updateValues can create FacesMessages that signal semantic errors return null; } else { dao.startTransaction(); // TechnicalException dao.createPersistentBean(getInstance()); // TechnicalException, CompoundPropertyException dao.commitTransaction(getInstance()); // TechnicalException, CompoundPropertyException assert getInstance().getId() != null; setId(getInstance().getId()); setViewMode(VIEWMODE_DISPLAY); return null; } } catch(CompoundPropertyException cpExc) { LOG.debug("create action failed; cancelling ...", cpExc); dao.cancelTransaction(); // TechnicalException LOG.debug("create action cancelled; using exception as faces message"); RobustCurrent.showCompoundPropertyException(cpExc); setViewMode(VIEWMODE_EDITNEW); return null; } } catch(TechnicalException exc) { RobustCurrent.fatalProblem("Could not create " + getInstance(), exc, LOG); return null; } } public static final String NO_INSTANCE = "NO_INSTANCE"; public static final String INCORRECT_VIEWMODE = "INCORRECT_VIEWMODE"; public static final String CANCEL_EDITNEW = "CANCEL_EDITNEW"; /** * This is an action method that should be called by a button in the JSF * page to delete a persistent bean from persistent storage. * * A more detailed description of this action method can be found in the * class description. * * @post (getInstance() == null) * ? 'return to previous page' && * result.equals(NO_INSTANCE) * : true; * @post (getInstance() != null && !getViewMode().equals(VIEWMODE_DISPLAY)) * ? getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_DISPLAY) * && 'delete in storage generates no semantic exceptions') * ? 'bean is deleted from persistent storage' && * getViewMode().equals(VIEWMODE_DELETED) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_DISPLAY) * && 'delete in storage generates semantic exceptions') * ? getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @throws FatalFacesException * When a TechnicalException is thrown by: * {@link AsyncCrudDao#startTransaction()} * {@link AsyncCrudDao#deletePersistentBean(be.peopleware.persistence_II.PersistentBean)} * {@link AsyncCrudDao#commitTransaction(be.peopleware.persistence_II.PersistentBean)} * {@link AsyncCrudDao#cancelTransaction()} */ public final String delete() throws FatalFacesException { LOG.debug("InstanceHandler.delete() called"); LOG.debug("persistentBean: " + getInstance()); AsyncCrudDao dao = getAsyncCrudDao(); try { try { checkConditions(VIEWMODE_DISPLAY); // ConditionException dao.startTransaction(); // TechnicalException dao.deletePersistentBean(getInstance()); // TechnicalException dao.commitTransaction(getInstance());// TechnicalException, CompoundPropertyException assert getInstance().getId() == null; setId(null); setViewMode(VIEWMODE_DELETED); return getNavigationString(); } catch(ConditionException exc) { return exc.getNavigationString(); } catch (CompoundPropertyException cpExc) { LOG.debug("delete action failed; cancelling ...", cpExc); dao.cancelTransaction(); // TechnicalException LOG.debug("delete action cancelled; using exception as faces message"); RobustCurrent.showCompoundPropertyException(cpExc); setViewMode(VIEWMODE_DISPLAY); return null; } } catch(TechnicalException exc) { RobustCurrent.fatalProblem("Could not delete " + getInstance(), exc, LOG); return null; } } /** * Helper method used in action methods to check whether the persistent bean * is effective and whether the current view mode corresponds to the * view mode in which the action method should be called. * If one of these conditions is not met, appropriate actions are taken. * * When {@link #getInstance()} is <code>null</code>, we return to a previous * page. * When the {@link #getInstance()} is effective, but the current view mode * does not correspond to the given expected view mode, we go to display mode. * In both cases, a ConditionException is thrown that contains the * navigation string. * * @param expectedViewMode * The view mode that should be checked. * @pre isViewMode(expectedViewMode); * @post true * @throws ConditionException exc * getInstance() == null * && exc.getOutcome().equals(NO_INSTANCE); * As a side effect, we return to a previous page. * @throws ConditionException exc * getInstance() != null && !getViewMode().equals(expectedViewMode) * && exc.getOutcome().equals(display()); * As a side effect, we go to display mode. */ protected void checkConditions(String expectedViewMode) throws ConditionException { super.checkConditions(expectedViewMode); if (getInstance() == null) { goBack(NO_INSTANCE); throw new ConditionException(NO_INSTANCE); } } /** * Method to be called after Render Response phase, to clear * semantic data from the session. * * @post getInstance() == null; */ void release() { releaseInstance(); // mudo (jand) more code or remove? } /** * This method returns to the page that was visited before this page. * It is possible that this previous page cannot be displayed anymore * (e.g. because the corresponding {@link PersistentBean} does not exist in * persistent storage anymore), so this process is recursive, until the first * page after login is reached. * The method returns the navigation string needed to navigate to the * previous page * * @param message * A message signalling why we are going back to a previous page. * @mudo */ public String goBack(String message) { // MUDO return message; } public String goBack() { LOG.debug("goBack method called"); return null; } /** * This is an action method that should be called by a button in the JSF * page to cancel the update of an existing persistent bean * (i.e. a persistent bean that was loaded from persistent storage, * meaning that {@link #getInstance()} <code>!=null</code> and * {@link #getInstance()}.{@link #getId()} <code>!=null</code>). * * A more detailed description of this action method can be found in the * class description. * * @post (getInstance() == null) * ? 'return to previous page' && * result.equals(NO_INSTANCE) * : true; * @post (getInstance() != null && !getViewMode().equals(VIEWMODE_EDIT)) * ? getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDIT)) * ? 'reset the UI components' && * getViewMode().equals(VIEWMODE_DISPLAY) && * result.equals(null) * : true; * public final String cancelEdit(); */ /** * This is an action method that should be called by a button in the JSF * page to cancel the creation of a new persistent bean * (i.e. a persistent bean that was created in memory but not saved in * persistent storage yet). * * A more detailed description of this action method can be found in the * class description. * * @post 'return to previous page' * @post (getInstance() == null) * ? result.equals(NO_INSTANCE) * : true; * @post (getInstance() != null && !getViewMode().equals(VIEWMODE_EDITNEW)) * ? result.equals(INCORRECT_VIEWMODE) * : true; * @post (getInstance() != null && getViewMode().equals(VIEWMODE_EDITNEW)) * ? result.equals(CANCEL_EDITNEW) * : true; */ public final String cancelEditNew() { LOG.debug("InstanceHandler.cancelEditNew called; returning to previous page"); LOG.debug("persistentBean: " + getInstance()); if (getInstance() == null) { return goBack(NO_INSTANCE); } if (!getViewMode().equals(VIEWMODE_EDITNEW)) { return goBack(INCORRECT_VIEWMODE); } return goBack(CANCEL_EDITNEW); } /*<section name="Association Handlers">*/ /** * <p>{@link PersistentBean} instances are often related to other {@link PersistentBean} * instances, according to the same pattern (a bidirectional one-to-many * association). These relations need to be navigatable and editable.</p> * <p>For the to-many associations, there is a property in the {@link PersistentBean instance} * that returns a {@link Collection} of other {@link PersistentBean PersistentBeans}. * We often want to show this collection in some way, and interact with it, via * the web interface. This is handled by a {@link CollectionHandler}. * In the handler that wraps around the original instance (an object of this class), * we need a way to create and access such a * {@link CollectionHandler list handler}. Below you will find code * to do this via reflection, automatically. Different * {@link CollectionHandler list handlers} can be accessed through * a (fake) {@link Map}, where the key is the property name of the JavaBean * property that returns the collection of associated {@link PersistentBean PersistentBeans} * from the instance this handler works for.</p> */ public final Map getAssociationHandlers() { return $associationHandlers; } /** * The association handlers that are actually created already, * because we got a request for them through {@link #getAssociationHandlers()}. * * @return $associationHandlers.getInitializedAssociationHandlers(); */ public final Map getUsedAssociationHandlers() { return $associationHandlers.getInitializedAssociationHandlers(); } public final void removeUsedAssociationHandlerFor(String propertyName) { $associationHandlers.removeInitializedAssociationHandlerFor(propertyName); } /** * Alias for {@link #getAssociationHandlers()} with a shorter name. */ public final Map getAssocH() { return getAssociationHandlers(); } private final class AutomaticAssociationHandlersMap extends AbstractUnmodifiableMap implements Removable, Skimmable { public final Set keySet() { if ($keySet == null) { initKeySet(); } return $keySet; } private void initKeySet() { $keySet = new HashSet(); $keySet.addAll(getAssociationMetaMap().keySet()); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(getPersistentBeanType()); for (int i = 0; i < descriptors.length; i++) { PropertyDescriptor pd = descriptors[i]; if (PersistentBean.class.isAssignableFrom(pd.getPropertyType())) { $keySet.add(pd.getDisplayName()); } } } private HashSet $keySet; /** * The association handlers that are actually created already, * because we got a request for them through {@link #get(Object)}. */ public final Map getInitializedAssociationHandlers() { return Collections.unmodifiableMap($backingMap); } private Map $backingMap = new HashMap(); public final void removeInitializedAssociationHandlerFor(String propertyName) { $backingMap.remove(propertyName); } public Object get(Object key) throws FatalFacesException { if (! keySet().contains(key)) { LOG.warn("request for associations handler with unknown key (property name) \"" + key + "\"; returning null"); return null; } Object result = $backingMap.get(key); if (result == null) { String propertyName = (String)key; try { Object propertyValue = PropertyUtils.getProperty(getInstance(), propertyName); if (propertyValue == null) { LOG.debug("propertyValue is null; cannot create handler, returning null"); return null; } if (propertyValue instanceof PersistentBean) { result = freshPersistentBeanInstanceHandlerFor((PersistentBean)propertyValue); } else if (propertyValue instanceof Collection) { Class associatedType = (Class)getAssociationMetaMap().get(propertyName); result = freshCollectionHandlerFor(associatedType, (Collection)propertyValue); } else { LOG.warn("Property \"" + propertyName + "\" is not a PersistentBean or a " + "Collection; returning null"); return null; } $backingMap.put(key, result); } catch (ClassCastException ccExc) { RobustCurrent.fatalProblem("could not get persistentbean for property \"" + propertyName + "\"", ccExc, LOG); } catch (IllegalArgumentException iaExc) { RobustCurrent.fatalProblem("could not get property \"" + propertyName + "\"", iaExc, LOG); } catch (IllegalAccessException iaExc) { RobustCurrent.fatalProblem("could not get property \"" + propertyName + "\"", iaExc, LOG); } catch (InvocationTargetException itExc) { RobustCurrent.fatalProblem("could not get property \"" + propertyName + "\"", itExc, LOG); } catch (NullPointerException npExc) { RobustCurrent.fatalProblem("could not get property \"" + propertyName + "\"", npExc, LOG); } catch (ExceptionInInitializerError eiiErr) { RobustCurrent.fatalProblem("could not get property \"" + propertyName + "\"", eiiErr, LOG); } catch (NoSuchMethodException nsmExc) { RobustCurrent.fatalProblem("could not get property \"" + propertyName + "\"", nsmExc, LOG); } } return result; } private InstanceHandler freshPersistentBeanInstanceHandlerFor(PersistentBean pb) throws FatalFacesException, IllegalArgumentException { InstanceHandler pbch = (InstanceHandler)RESOLVER.freshHandlerFor(pb.getClass(), getDaoVariableName()); pbch.setInstance(pb); return pbch; } private CollectionHandler freshCollectionHandlerFor(Class associatedType, Collection c) throws FatalFacesException { CollectionHandler ch = (CollectionHandler)CollectionHandler.RESOLVER.freshHandlerFor(associatedType, getDaoVariableName()); ch.setInstances(c); return ch; } /** * All cached association handlers are to be removed. */ public boolean isToBeRemoved() { Iterator iter = $backingMap.values().iterator(); while (iter.hasNext()) { PersistentBeanHandler pbH = (PersistentBeanHandler)iter.next(); if (! pbH.isToBeRemoved()) { LOG.debug("cached association handler " + pbH + " is not to be removed"); return false; } } LOG.debug("all cached association handlers are to be removed"); return true; } public void skim() { $keySet = null; List $cachedEntries = new LinkedList($backingMap.entrySet()); Iterator iter = $cachedEntries.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); PersistentBeanHandler pbH = (PersistentBeanHandler)entry.getValue(); if (pbH.isToBeRemoved()) { LOG.debug(" cached association handler " + pbH + " is to be removed"); $backingMap.remove(entry.getKey()); } else { LOG.debug(" cached assocation handler " + pbH + " will be skimmed"); pbH.skim(); } } } } private final AutomaticAssociationHandlersMap $associationHandlers = new AutomaticAssociationHandlersMap(); /** * <p>The automated {@link #getAssociationHandlers() association handlers map} requires * some meta information about the relations that instances of {@link #getPersistentBeanType()} * are involved in. This map should list entries with the property name * that represents the association as key, and the type of the related elements * as value.</p> * <p>Since this is meta information, the implementation should probably use a * class variable instead of an instance variable. The implementation could look * like this:</p> * <pre> * public final static Map ASSOCIATIONS_META_MAP = new HashMap(); * * static { * ASSOCIATIONS_META_MAP.put("groups", Group.class); * ASSOCIATIONS_META_MAP.put("friends", Person.class); * ASSOCIATIONS_META_MAP.put("hobbies", Things.class); * } * * protected Map getAssociationMetaMap() { * return ASSOCIATIONS_META_MAP; * } * </pre> * <p>This default implementation returns an empty map. This method should never * return <code>null</code>.</p> * * @result result != null; * @todo (jand) more contract * * @idea with 1.5 we will probably no longer need this meta information * @todo (jand) map should be made unmodifiable in example */ protected Map getAssociationMetaMap() { return Collections.EMPTY_MAP; } /*</section>*/ /** * @invar RESOLVER.getHandlerDefaultClass() == InstanceHandler.class; * @invar RESOLVER.getHandlerVarNameSuffix().equals(EMPTY); */ public final static PersistentBeanHandlerResolver RESOLVER = new PersistentBeanHandlerResolver(InstanceHandler.class, ""); /*<section name="skimmable">*/ /** * Sets the {@link #getStoredInstance() stored instance} to <code>null</code> * if the {@link #getId() id} is not <code>null</code>. * The {@link #getAssociationHandlers() associations handlers} are checked. * If they are {@link Removable}, and they {@link Removable#isToBeRemoved() * want to be removed}, they are removed from the backing cache of * association handlers. If they are not removed, and are {@link Skimmable}, * they are {@link Skimmable#skim() skimmed}. */ public void skim() { super.skim(); if (getId() != null) { LOG.debug("skimming instance"); releaseInstance(); } LOG.debug("skimming cached association handlers"); $associationHandlers.skim(); } /*</section>*/ /*<section name="removable">*/ /** * @return (getViewMode().equals(VIEWMODE_DISPLAY) || * getViewMode().equals(VIEWMODE_DELETED)) && * getAssociationHandler().isToBeRemoved(); */ public boolean isToBeRemoved() { boolean result = (getViewMode().equals(VIEWMODE_DISPLAY) || getViewMode().equals(VIEWMODE_DELETED)) && $associationHandlers.isToBeRemoved(); LOG.debug(this.toString() + ".isToBeRemoved() = " + result); return result; } /*</section>*/ /*<section name="navigationInstance">*/ /** * @result (ni == null) ? (result == null); * @result (result != null) ? (result == this); * @return ((getClass() == ni.getClass()) * && (getPersistentBeanType() == ((InstanceHandler)ni).getPersistentBeanType()) * && (equalsWithNull(getId(), ((InstanceHandler)ni).getId()) * || ((getId() == null) && (((InstanceHandler)ni).getId() != null))) * ? this * : null; * The last part of the condition takes care of creating a new instance: this previous * NavigationInstance was the page with no id, and after succesful creation, we do have * an id, but it is the same page. * @result (result != null) ? getTime().equals(NOW); */ public NavigationInstance absorb(NavigationInstance ni) { LOG.debug("request to absorb " + ni + " by " + this); if (ni == null) { return null; } else if ((getClass() == ni.getClass()) && (getPersistentBeanType() == ((InstanceHandler)ni).getPersistentBeanType()) && (equalsWithNull(getId(), ((InstanceHandler)ni).getId()) || ((getId() == null) && (((InstanceHandler)ni).getId() != null)) || ((getId() != null) && (((InstanceHandler)ni).getId() == null)))) { LOG.debug("absorbing"); resetLastRenderedTime(); if ((getId() == null) && (((InstanceHandler)ni).getId() != null)|| ((getId() != null) && (((InstanceHandler)ni).getId() == null))) { // we have just created a new instance; copy the id setId(((InstanceHandler)ni).getId()); } return this; } else { LOG.debug("not absorbing"); return null; } } /** * Is one value {@link Object#equals(java.lang.Object) equal} * to another, if <code>null</code> is also allowed as value * for a property. * * @return (one == null) * ? (other == null) * : one.equals(other); * * @idea (jand) move to ppw-util or toryt */ private static boolean equalsWithNull(final Object one, final Object other) { return (one == null) ? (other == null) : one.equals(other); } /*</section>*/ }
package mindpop.learnpop; import android.app.ProgressDialog; import android.os.Bundle; import android.os.AsyncTask; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; public class Share extends Fragment { private ProgressDialog pDialog; private TextView name; private TextView resUrl; private Spinner spinnerGrades; private Spinner spinnerSubjects; private Spinner spinnerType; private Button btnSend; private String request_url = "http://austinartmap.com/CreativeTeach/PHP/insertResource_v3.php"; private JSONParser jsonParser = new JSONParser(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_share, container, false); setSpinnerContent(rootView); name = (TextView)rootView.findViewById(R.id.resName); resUrl = (TextView)rootView.findViewById(R.id.editURL); btnSend = (Button)rootView.findViewById(R.id.btnSend); btnSend.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ new CreateNewResource().execute(); } }); return rootView; } private void setSpinnerContent(View view){ spinnerGrades = (Spinner) view.findViewById(R.id.spinner_Grades); ArrayAdapter <CharSequence> adapterG = ArrayAdapter.createFromResource(getActivity(), R.array.grades_array, android.R.layout.simple_spinner_item); spinnerGrades.setAdapter(adapterG); adapterG.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerGrades.setPromptId(R.string.grade_prompt); spinnerSubjects = (Spinner) view.findViewById(R.id.spinner_Subjects); ArrayAdapter <CharSequence> adapterS = ArrayAdapter.createFromResource(getActivity(), R.array.subjects_array, android.R.layout.simple_spinner_item); spinnerSubjects.setAdapter(adapterS); adapterS.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerSubjects.setPromptId(R.string.subject_prompt); spinnerType = (Spinner) view.findViewById(R.id.spinner_Type); ArrayAdapter <CharSequence> adapterT = ArrayAdapter.createFromResource(getActivity(), R.array.type_array, android.R.layout.simple_spinner_item); spinnerType.setAdapter(adapterT); adapterT.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerType.setPromptId(R.string.type_prompt); } class CreateNewResource extends AsyncTask<String, String, String>{ @Override protected void onPreExecute(){ super.onPreExecute(); pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Uploading Resource..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } private String getGradeParamName(String completeGrade){ String param = ""; switch (completeGrade){ case "Early Childhood": param = "Childhood"; break; case "Lower Elementary": param = "LowerElem"; break; case "Upper Elementary": param = "UpperElem"; break; case "Middle School": param = "Middle"; break; case "High School": param ="High"; break; } return param; } protected String doInBackground(String... args){ String resName = name.getText().toString(); String url = resUrl.getText().toString(); String type = spinnerType.getSelectedItem().toString(); String subject = spinnerSubjects.getSelectedItem().toString(); String grade = spinnerGrades.getSelectedItem().toString(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ResName", resName)); params.add(new BasicNameValuePair("ResURL", url)); params.add(new BasicNameValuePair("ResType", type)); params.add(new BasicNameValuePair("Subject[]", subject)); params.add(new BasicNameValuePair("GradeLevel[]", getGradeParamName(grade))); JSONObject json = jsonParser.makeHttpRequest(request_url, "POST", params); Log.d("Create resource response", json.toString()); return null; } protected void onPostExecute(String file_url) { pDialog.dismiss(); //if success name.setText(""); resUrl.setText(""); Toast.makeText(getActivity(), "Resource uploaded!", Toast.LENGTH_SHORT).show(); } } }
package com.mapswithme.maps; import java.io.Serializable; import java.util.Locale; import java.util.Stack; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Typeface; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.DrawerLayout.DrawerListener; import android.telephony.TelephonyManager; import android.text.style.StyleSpan; import android.util.Log; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.mapswithme.country.DownloadUI; import com.mapswithme.maps.Framework.OnBalloonListener; import com.mapswithme.maps.LocationButtonImageSetter.ButtonState; import com.mapswithme.maps.MapStorage.Index; import com.mapswithme.maps.api.ParsedMmwRequest; import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity; import com.mapswithme.maps.location.LocationService; import com.mapswithme.maps.promo.ActivationSettings; import com.mapswithme.maps.promo.PromocodeActivationDialog; import com.mapswithme.maps.settings.SettingsActivity; import com.mapswithme.maps.settings.UnitLocale; import com.mapswithme.maps.state.SuppotedState; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.ShareAction; import com.mapswithme.util.StringUtils; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.Yota; import com.mapswithme.util.statistics.Statistics; import com.nvidia.devtech.NvEventQueueActivity; public class MWMActivity extends NvEventQueueActivity implements LocationService.Listener, OnBalloonListener, DrawerListener { private final static String TAG = "MWMActivity"; public static final String EXTRA_TASK = "map_task"; private static final int PRO_VERSION_DIALOG = 110001; private static final String PRO_VERSION_DIALOG_MSG = "pro_version_dialog_msg"; private static final int PROMO_DIALOG = 110002; private MWMApplication mApplication = null; private BroadcastReceiver m_externalStorageReceiver = null; private AlertDialog m_storageDisconnectedDialog = null; private ImageButton mLocationButton; private SurfaceView mMapSurface; private View mYopItButton; // for API private View mTitleBar; private ImageView mAppIcon; private TextView mAppTitle; // Map tasks that we run AFTER rendering initialized private final Stack<MapTask> mTasks = new Stack<MWMActivity.MapTask>(); // Drawer components private DrawerLayout mDrawerLayout; private View mMainDrawer; private String mProDialogMessage; public native void deactivatePopup(); private LocationService getLocationService() { return mApplication.getLocationService(); } private MapStorage getMapStorage() { return mApplication.getMapStorage(); } private LocationState getLocationState() { return mApplication.getLocationState(); } private void startLocation() { getLocationState().onStartLocation(); resumeLocation(); } private void stopLocation() { getLocationState().onStopLocation(); pauseLocation(); } private void pauseLocation() { getLocationService().stopUpdate(this); // Enable automatic turning screen off while app is idle Utils.automaticIdleScreen(true, getWindow()); } private void resumeLocation() { getLocationService().startUpdate(this); // Do not turn off the screen while displaying position Utils.automaticIdleScreen(false, getWindow()); } public void checkShouldResumeLocationService() { final LocationState state = getLocationState(); final boolean hasPosition = state.hasPosition(); final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW); if (hasPosition || state.isFirstPosition()) { if (hasPosition && isFollowMode) { state.startCompassFollowing(); LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton); } else { LocationButtonImageSetter.setButtonViewFromState( hasPosition ? ButtonState.HAS_LOCATION : ButtonState.WAITING_LOCATION, mLocationButton); } resumeLocation(); } else { LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton); } } public void OnDownloadCountryClicked() { runOnUiThread(new Runnable() { @Override public void run() { nativeDownloadCountry(); } }); } @Override public void OnRenderingInitialized() { mRenderingInitialized = true; runOnUiThread(new Runnable() { @Override public void run() { // Run all checks in main thread after rendering is initialized. checkMeasurementSystem(); checkUpdateMaps(); checkFacebookDialog(); checkBuyProDialog(); } }); runTasks(); } private void runTasks() { // Task are not UI-thread bounded, // if any task need UI-thread it should implicitly // use Activity.runOnUiThread(). while (!mTasks.isEmpty()) mTasks.pop().run(this); } private Activity getActivity() { return this; } @Override public void ReportUnsupported() { runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setMessage(getString(R.string.unsupported_phone)) .setCancelable(false) .setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { getActivity().moveTaskToBack(true); dlg.dismiss(); } }) .create() .show(); } }); } private void checkMeasurementSystem() { UnitLocale.initializeCurrentUnits(); } private native void nativeScale(double k); public void onPlusClicked(View v) { nativeScale(3.0 / 2); } public void onMinusClicked(View v) { nativeScale(2.0 / 3); } public void onBookmarksClicked() { if (!mApplication.hasBookmarks()) showProVersionBanner(getString(R.string.bookmarks_in_pro_version)); else startActivity(new Intent(this, BookmarkCategoriesActivity.class)); } public void onMyPositionClicked(View v) { final LocationState state = mApplication.getLocationState(); if (state.hasPosition()) { if (state.isCentered()) { if (mApplication.isProVersion() && state.hasCompass()) { final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW); if (isFollowMode) { state.stopCompassFollowingAndRotateMap(); } else { state.startCompassFollowing(); LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton); return; } } } else { state.animateToPositionAndEnqueueLocationProcessMode(LocationState.LOCATION_CENTER_ONLY); mLocationButton.setSelected(true); return; } } else { if (!state.isFirstPosition()) { LocationButtonImageSetter.setButtonViewFromState(ButtonState.WAITING_LOCATION, mLocationButton); startLocation(); return; } } // Stop location observing first ... stopLocation(); LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton); } private boolean m_needCheckUpdate = true; private boolean mRenderingInitialized = false; private void checkUpdateMaps() { // do it only once if (m_needCheckUpdate) { m_needCheckUpdate = false; getMapStorage().updateMaps(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor() { @Override public void doUpdate() { runDownloadActivity(); } @Override public void doCancel() { } }); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); alignControls(); } private void showDialogImpl(final int dlgID, int resMsg, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setCancelable(false) .setMessage(getString(resMsg)) .setPositiveButton(getString(R.string.ok), okListener) .setNeutralButton(getString(R.string.never), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); mApplication.submitDialogResult(dlgID, MWMApplication.NEVER); } }) .setNegativeButton(getString(R.string.later), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); mApplication.submitDialogResult(dlgID, MWMApplication.LATER); } }) .create() .show(); } private void showFacebookPage() { try { // Trying to find package with installed Facebook application. // Exception is thrown if we don't have one. getPackageManager().getPackageInfo("com.facebook.katana", 0); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/111923085594432"))); } catch (final Exception e) { // Show Facebook page in browser. startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http: } } private boolean isChinaISO(String iso) { final String arr[] = { "CN", "CHN", "HK", "HKG", "MO", "MAC" }; for (final String s : arr) if (iso.equalsIgnoreCase(s)) return true; return false; } private boolean isChinaRegion() { final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { final String iso = tm.getNetworkCountryIso(); Log.i(TAG, "TelephonyManager country ISO = " + iso); if (isChinaISO(iso)) return true; } else { final Location l = mApplication.getLocationService().getLastKnown(); if (l != null && nativeIsInChina(l.getLatitude(), l.getLongitude())) return true; else { final String code = Locale.getDefault().getCountry(); Log.i(TAG, "Locale country ISO = " + code); if (isChinaISO(code)) return true; } } return false; } private void checkFacebookDialog() { if ((ConnectionState.getState(this) != ConnectionState.NOT_CONNECTED) && mApplication.shouldShowDialog(MWMApplication.FACEBOOK) && !isChinaRegion()) { showDialogImpl(MWMApplication.FACEBOOK, R.string.share_on_facebook_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { mApplication.submitDialogResult(MWMApplication.FACEBOOK, MWMApplication.OK); dlg.dismiss(); showFacebookPage(); } }); } } private void showProVersionBanner(final String message) { mProDialogMessage = message; runOnUiThread(new Runnable() { @SuppressWarnings("deprecation") @Override public void run() { showDialog(PRO_VERSION_DIALOG); } }); } private void runProVersionMarketActivity() { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mApplication.getProVersionURL()))); } catch (final Exception e1) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mApplication.getDefaultProVersionURL()))); } catch (final Exception e2) { /// @todo Probably we should show some alert toast here? Log.w(TAG, "Can't run activity" + e2); } } } private void checkBuyProDialog() { if (!mApplication.isProVersion() && (ConnectionState.getState(this) != ConnectionState.NOT_CONNECTED) && mApplication.shouldShowDialog(MWMApplication.BUYPRO)) { showDialogImpl(MWMApplication.BUYPRO, R.string.pro_version_available, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { mApplication.submitDialogResult(MWMApplication.BUYPRO, MWMApplication.OK); dlg.dismiss(); runProVersionMarketActivity(); } }); } } private void runSearchActivity() { startActivity(new Intent(this, SearchActivity.class)); } public void onSearchClicked() { if (!(mApplication.isProVersion() || ActivationSettings.isSearchActivated(this))) { showProVersionBanner(getString(R.string.search_available_in_pro_version)); } else { if (!getMapStorage().updateMaps(R.string.search_update_maps, this, new MapStorage.UpdateFunctor() { @Override public void doUpdate() { runDownloadActivity(); } @Override public void doCancel() { runSearchActivity(); } })) { runSearchActivity(); } } } @Override public boolean onSearchRequested() { onSearchClicked(); return false; } private void runDownloadActivity() { startActivity(new Intent(this, DownloadUI.class)); } public void onDownloadClicked() { runDownloadActivity(); } @Override public void onCreate(Bundle savedInstanceState) { // Use full-screen on Kindle Fire only if (Utils.isAmazonDevice()) { getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } setContentView(R.layout.activity_map); super.onCreate(savedInstanceState); mApplication = (MWMApplication)getApplication(); // Do not turn off the screen while benchmarking if (mApplication.nativeIsBenchmarking()) getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); nativeConnectDownloadButton(); //set up view mLocationButton = (ImageButton) findViewById(R.id.map_button_myposition); mTitleBar = findViewById(R.id.title_bar); mAppIcon = (ImageView) findViewById(R.id.app_icon); mAppTitle = (TextView) findViewById(R.id.app_title); mMapSurface = (SurfaceView) findViewById(R.id.map_surfaceview); setUpDrawer(); yotaSetup(); alignControls(); Framework.connectBalloonListeners(this); final Intent intent = getIntent(); // We need check for tasks both in onCreate and onNewIntent addTask(intent); } private void setUpDrawer() { final boolean isPro = mApplication.isProVersion(); final OnClickListener drawerItemsClickListener = new OnClickListener() { @Override public void onClick(View v) { final int id = v.getId(); if (R.id.menuitem_settings_activity == id) ContextMenu.onItemSelected(R.id.menuitem_settings_activity, MWMActivity.this); else if (R.id.map_container_bookmarks == id) { if (isPro) onBookmarksClicked(); else runProVersionMarketActivity(); } else if (R.id.map_container_download == id) onDownloadClicked(); else if (R.id.map_container_search == id) { if (isPro) onSearchClicked(); else runProVersionMarketActivity(); } else if (R.id.buy_pro == id) runProVersionMarketActivity(); else if (R.id.map_button_share_myposition == id) { final Location loc = MWMApplication.get().getLocationService().getLastKnown(); if (loc != null) { final String geoUrl = Framework.getGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl); // we use shortest message we can have here ShareAction.getAnyShare().shareWithText(getActivity(), body,""); } else { new AlertDialog.Builder(MWMActivity.this) .setMessage(R.string.unknown_current_position) .setCancelable(true) .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); }}) .create().show(); } } toggleDrawer(); } }; mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerLayout.setDrawerListener(this); mMainDrawer = findViewById(R.id.left_drawer); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mMapSurface.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return MWMActivity.this.onTouchEvent(event); } }); final SimpleOnGestureListener gestureListener = new SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (mDrawerLayout.isDrawerOpen(mMainDrawer)) return false; final float dX = e2.getX() - e1.getX(); if (dX < 0) // scroll is left { final float dY = e2.getY() - e1.getY(); if (Math.abs(dX) > Math.abs(dY)) // is closer to horizontal { mDrawerLayout.openDrawer(mMainDrawer); return true; } } return false; } }; final GestureDetectorCompat detector = new GestureDetectorCompat(this, gestureListener); final View toggleDrawer = findViewById(R.id.map_button_toggle_drawer); toggleDrawer.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return detector.onTouchEvent(event); } }); findViewById(R.id.map_container_bookmarks).setOnClickListener(drawerItemsClickListener); findViewById(R.id.map_container_search).setOnClickListener(drawerItemsClickListener); findViewById(R.id.map_container_download).setOnClickListener(drawerItemsClickListener); toggleDrawer.setOnClickListener(drawerItemsClickListener); findViewById(R.id.menuitem_settings_activity).setOnClickListener(drawerItemsClickListener); findViewById(R.id.map_button_share_myposition).setOnClickListener(drawerItemsClickListener); findViewById(R.id.buy_pro).setOnClickListener(drawerItemsClickListener); final TextView searchView = (TextView) findViewById(R.id.map_button_search); final TextView bookmarksView = (TextView) findViewById(R.id.map_button_bookmarks); final Resources res = getResources(); searchView.setCompoundDrawablesWithIntrinsicBounds(res.getDrawable(R.drawable.ic_search_selector), null, isPro ? null : res.getDrawable(R.drawable.ic_probadge), null); bookmarksView.setCompoundDrawablesWithIntrinsicBounds(res.getDrawable(R.drawable.ic_bookmarks_selector), null, isPro ? null : res.getDrawable(R.drawable.ic_probadge), null); final Button buyProButton = (Button)findViewById(R.id.buy_pro); if (isPro) UiUtils.hide(buyProButton); } private void yotaSetup() { // yota setup mYopItButton = findViewById(R.id.yop_it); if (!Yota.isYota()) mYopItButton.setVisibility(View.INVISIBLE); else { mYopItButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final double[] latLon = Framework.getScreenRectCenter(); final double zoom = Framework.getDrawScale(); final LocationState locState = mApplication.getLocationState(); if (locState.hasPosition() && locState.isCentered()) Yota.showLocation(getApplicationContext(), zoom); else Yota.showMap(getApplicationContext(), latLon[0], latLon[1], zoom, null, locState.hasPosition()); Statistics.INSTANCE.trackBackscreenCall(getApplication(), "Map"); } }); } } @Override public void onDestroy() { Framework.clearBalloonListeners(); super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); addTask(intent); } private final static String EXTRA_CONSUMED = "mwm.extra.intent.processed"; private void addTask(Intent intent) { if (intent != null && !intent.getBooleanExtra(EXTRA_CONSUMED, false) && intent.hasExtra(EXTRA_TASK) && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)) { final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK); mTasks.add(mapTask); intent.removeExtra(EXTRA_TASK); if (mRenderingInitialized) runTasks(); // mark intent as consumed intent.putExtra(EXTRA_CONSUMED, true); } } @Override protected void onStop() { deactivatePopup(); super.onStop(); mRenderingInitialized = false; } private void alignControls() { final View zoomPlusButton = findViewById(R.id.map_button_plus); final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) zoomPlusButton.getLayoutParams(); final int margin = (int) getResources().getDimension(R.dimen.zoom_margin); final int marginTop = (int) getResources().getDimension(R.dimen.zoom_plus_top_margin); lp.setMargins(margin, marginTop, margin, margin); findViewById(R.id.scroll_up).setPadding(0, (int) getResources().getDimension(R.dimen.drawer_top_padding), 0, 0); } /// @name From Location interface @Override public void onLocationError(int errorCode) { nativeOnLocationError(errorCode); // Notify user about turned off location services if (errorCode == LocationService.ERROR_DENIED) { getLocationState().turnOff(); // Do not show this dialog on Kindle Fire - it doesn't have location services // and even wifi settings can't be opened programmatically if (!Utils.isAmazonDevice()) { new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text) .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } catch (final Exception e1) { // On older Android devices location settings are merged with security try { startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS)); } catch (final Exception e2) { Log.w(TAG, "Can't run activity" + e2); } } dialog.dismiss(); } }) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } } else if (errorCode == LocationService.ERROR_GPS_OFF) { Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show(); } } public void onCompassStatusChanged(int newStatus) { if (newStatus == 1) LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton); else if (getLocationState().hasPosition()) LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton); else LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton); } public void OnCompassStatusChanged(int newStatus) { final int val = newStatus; runOnUiThread(new Runnable() { @Override public void run() { onCompassStatusChanged(val); } }); } @Override public void onLocationUpdated(final Location l) { if (getLocationState().isFirstPosition()) LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton); nativeLocationUpdated(l.getTime(), l.getLatitude(), l.getLongitude(), l.getAccuracy(), l.getAltitude(), l.getSpeed(), l.getBearing()); } @Override public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { final double angles[] = { magneticNorth, trueNorth }; getLocationService().correctCompassAngles(getWindowManager().getDefaultDisplay(), angles); nativeCompassUpdated(time, angles[0], angles[1], accuracy); } private int m_compassStatusListenerID = -1; private void startWatchingCompassStatusUpdate() { m_compassStatusListenerID = mApplication.getLocationState().addCompassStatusListener(this); } private void stopWatchingCompassStatusUpdate() { mApplication.getLocationState().removeCompassStatusListener(m_compassStatusListenerID); } @Override protected void onPause() { pauseLocation(); stopWatchingExternalStorage(); stopWatchingCompassStatusUpdate(); super.onPause(); } @Override protected void onResume() { super.onResume(); checkShouldResumeLocationService(); startWatchingCompassStatusUpdate(); startWatchingExternalStorage(); if (SettingsActivity.isZoomButtonsEnabled(mApplication)) UiUtils.show(findViewById(R.id.map_button_plus), findViewById(R.id.map_button_minus)); else UiUtils.hide(findViewById(R.id.map_button_plus), findViewById(R.id.map_button_minus)); } @Override public void setViewFromState(SuppotedState state) { if (state == SuppotedState.API_REQUEST && ParsedMmwRequest.hasRequest()) { // show title mTitleBar.findViewById(R.id.up_block).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); final ParsedMmwRequest request = ParsedMmwRequest.getCurrentRequest(); if (request.hasTitle()) mAppTitle.setText(request.getTitle()); else mAppTitle.setText(request.getCallerName(this)); mAppIcon.setImageDrawable(request.getIcon(this)); mTitleBar.setVisibility(View.VISIBLE); } else { // hide title mTitleBar.setVisibility(View.GONE); } } @Override public void onBackPressed() { if (getState() == SuppotedState.API_REQUEST) getMwmApplication() .getAppStateManager() .transitionTo(SuppotedState.DEFAULT_MAP); super.onBackPressed(); } // Initialized to invalid combination to force update on the first check private boolean m_storageAvailable = false; private boolean m_storageWriteable = true; private void updateExternalStorageState() { boolean available, writeable; final String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { available = writeable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { available = true; writeable = false; } else available = writeable = false; if (m_storageAvailable != available || m_storageWriteable != writeable) { m_storageAvailable = available; m_storageWriteable = writeable; handleExternalStorageState(available, writeable); } } private void handleExternalStorageState(boolean available, boolean writeable) { if (available && writeable) { // Add local maps to the model nativeStorageConnected(); // enable downloader button and dismiss blocking popup findViewById(R.id.map_button_download).setVisibility(View.VISIBLE); if (m_storageDisconnectedDialog != null) m_storageDisconnectedDialog.dismiss(); } else if (available) { // Add local maps to the model nativeStorageConnected(); // disable downloader button and dismiss blocking popup findViewById(R.id.map_button_download).setVisibility(View.INVISIBLE); if (m_storageDisconnectedDialog != null) m_storageDisconnectedDialog.dismiss(); } else { // Remove local maps from the model nativeStorageDisconnected(); // enable downloader button and show blocking popup findViewById(R.id.map_button_download).setVisibility(View.VISIBLE); if (m_storageDisconnectedDialog == null) { m_storageDisconnectedDialog = new AlertDialog.Builder(this) .setTitle(R.string.external_storage_is_not_available) .setMessage(getString(R.string.disconnect_usb_cable)) .setCancelable(false) .create(); } m_storageDisconnectedDialog.show(); } } private boolean isActivityPaused() { // This receiver is null only when activity is paused (see onPause, onResume). return (m_externalStorageReceiver == null); } private void startWatchingExternalStorage() { m_externalStorageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateExternalStorageState(); } }; final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_REMOVED); filter.addAction(Intent.ACTION_MEDIA_EJECT); filter.addAction(Intent.ACTION_MEDIA_SHARED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE); filter.addAction(Intent.ACTION_MEDIA_CHECKING); filter.addAction(Intent.ACTION_MEDIA_NOFS); filter.addDataScheme("file"); registerReceiver(m_externalStorageReceiver, filter); updateExternalStorageState(); } @Override @Deprecated protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { if (id == PRO_VERSION_DIALOG) { ((AlertDialog)dialog).setMessage(mProDialogMessage); } else { super.onPrepareDialog(id, dialog, args); } } @Override @Deprecated protected Dialog onCreateDialog(int id) { if (id == PRO_VERSION_DIALOG) { return new AlertDialog.Builder(getActivity()) .setMessage("") .setPositiveButton(getString(R.string.get_it_now), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); runProVersionMarketActivity(); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }) .setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { if (ActivationSettings.isSearchActivated(getApplicationContext())) return false; showDialog(PROMO_DIALOG); dismissDialog(PRO_VERSION_DIALOG); return true; } return false; } }) .create(); } else if (id == PROMO_DIALOG) return new PromocodeActivationDialog(this); else return super.onCreateDialog(id); } private void stopWatchingExternalStorage() { if (m_externalStorageReceiver != null) { unregisterReceiver(m_externalStorageReceiver); m_externalStorageReceiver = null; } } private void toggleDrawer() { if (mDrawerLayout.isDrawerOpen(mMainDrawer)) mDrawerLayout.closeDrawer(mMainDrawer); else mDrawerLayout.openDrawer(mMainDrawer); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (KeyEvent.KEYCODE_MENU == keyCode) { toggleDrawer(); return true; } return super.onKeyUp(keyCode, event); } // Map TASKS public interface MapTask extends Serializable { public boolean run(MWMActivity target); } public static class OpenUrlTask implements MapTask { private static final long serialVersionUID = 1L; private final String mUrl; public OpenUrlTask(String url) { Utils.checkNotNull(url); mUrl = url; } @Override public boolean run(MWMActivity target) { return target.showMapForUrl(mUrl); } } public static class ShowCountryTask implements MapTask { private static final long serialVersionUID = 1L; private final Index mIndex; public ShowCountryTask(Index index) { mIndex = index; } @Override public boolean run(MWMActivity target) { target.getMapStorage().showCountry(mIndex); return true; } } // NATIVE callbacks and methods @Override public void onApiPointActivated(final double lat, final double lon, final String name, final String id) { if (ParsedMmwRequest.hasRequest()) { final ParsedMmwRequest request = ParsedMmwRequest.getCurrentRequest(); request.setPointData(lat, lon, name, id); if (request.doReturnOnBalloonClick()) { request.sendResponseAndFinish(this, true); // we dont show MapObject in this case return; } } runOnUiThread(new Runnable() { @Override public void run() { MapObjectActivity.startWithApiPoint(getActivity(), name, null, null, lat, lon); } }); } @Override public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon) { runOnUiThread(new Runnable() { @Override public void run() { MapObjectActivity.startWithPoi(getActivity(), name, type, address, lat, lon); } }); } @Override public void onBookmarkActivated(final int category, final int bookmarkIndex) { runOnUiThread(new Runnable() { @Override public void run() { MapObjectActivity.startWithBookmark(getActivity(), category, bookmarkIndex); } }); } @Override public void onMyPositionActivated(final double lat, final double lon) { runOnUiThread(new Runnable() { @Override public void run() { MapObjectActivity.startWithMyPosition(getActivity(), lat, lon); } }); } public static Intent createShowMapIntent(Context context, Index index) { return new Intent(context, DownloadResourcesActivity.class) .putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index); } private native void nativeStorageConnected(); private native void nativeStorageDisconnected(); private native void nativeConnectDownloadButton(); private native void nativeDownloadCountry(); private native void nativeDestroy(); private native void nativeOnLocationError(int errorCode); private native void nativeLocationUpdated(long time, double lat, double lon, float accuracy, double altitude, float speed, float bearing); private native void nativeCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy); private native boolean nativeIsInChina(double lat, double lon); public native boolean showMapForUrl(String url); @Override public void onDrawerClosed(View arg0) { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override public void onDrawerOpened(View arg0) { mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); } @Override public void onDrawerSlide(View arg0, float arg1) { } @Override public void onDrawerStateChanged(int arg0) { } }
import static org.junit.Assert.*; import java.io.File; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestFileOperationUtilities { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testSaveFile() throws Exception { File fileToSave = new File("fileToSave.txt"); assertTrue(FileOperationUtilities.saveAs(fileToSave, "drinne")); } }
package com.yahoo.vespa.athenz.api; import java.util.Objects; /** * Represents an Athenz Access Token * * @author bjorncs */ public class AthenzAccessToken { public static final String HTTP_HEADER_NAME = "Authorization"; private static final String BEARER_TOKEN_PREFIX = "Bearer "; private final String value; public AthenzAccessToken(String value) { this.value = stripBearerTokenPrefix(value); } private static String stripBearerTokenPrefix(String rawValue) { String stripped = rawValue.strip(); String prefixRemoved = stripped.startsWith(BEARER_TOKEN_PREFIX) ? stripped.substring(BEARER_TOKEN_PREFIX.length()).strip() : stripped; if (prefixRemoved.isBlank()) { throw new IllegalArgumentException(String.format("Access token is blank: '%s'", prefixRemoved)); } return prefixRemoved; } public String value() { return value; } @Override public String toString() { return "AthenzAccessToken{value='" + value + "'}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AthenzAccessToken that = (AthenzAccessToken) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(value); } }
package org.openhab.habdroid.util; import android.app.Activity; import android.content.Context; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.util.Log; import com.crittercism.app.Crittercism; import com.crittercism.app.CrittercismConfig; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.openhab.habdroid.R; import org.openhab.habdroid.model.OpenHAB1Sitemap; import org.openhab.habdroid.model.OpenHAB2Sitemap; import org.openhab.habdroid.model.OpenHABSitemap; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Util { private final static String TAG = Util.class.getSimpleName(); public static void overridePendingTransition(Activity activity, boolean reverse) { if (PreferenceManager.getDefaultSharedPreferences(activity).getString(Constants.PREFERENCE_ANIMATION, "android").equals("android")) { } else if (PreferenceManager.getDefaultSharedPreferences(activity).getString(Constants.PREFERENCE_ANIMATION, "android").equals("ios")) { if (reverse) { activity.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } else { activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } } else { activity.overridePendingTransition(0, 0); } } public static String normalizeUrl(String sourceUrl) { String normalizedUrl = ""; try { URL url = new URL(sourceUrl); normalizedUrl = url.toString(); normalizedUrl = normalizedUrl.replace("\n", ""); normalizedUrl = normalizedUrl.replace(" ", ""); if (!normalizedUrl.endsWith("/")) normalizedUrl = normalizedUrl + "/"; } catch (MalformedURLException e) { Log.e(TAG, "normalizeUrl: invalid URL"); } return normalizedUrl; } public static void initCrittercism(Context ctx, String appKey) { // Initialize crittercism reporting CrittercismConfig crittercismConfig = new CrittercismConfig(); crittercismConfig.setLogcatReportingEnabled(true); Crittercism.initialize(ctx, appKey, crittercismConfig); } public static List<OpenHABSitemap> parseSitemapList(Document document) { List<OpenHABSitemap> sitemapList = new ArrayList<OpenHABSitemap>(); NodeList sitemapNodes = document.getElementsByTagName("sitemap"); if (sitemapNodes.getLength() > 0) { for (int i = 0; i < sitemapNodes.getLength(); i++) { Node sitemapNode = sitemapNodes.item(i); OpenHABSitemap openhabSitemap = new OpenHAB1Sitemap(sitemapNode); sitemapList.add(openhabSitemap); } } // Sort by sitename label Collections.sort(sitemapList, new Comparator<OpenHABSitemap>() { @Override public int compare(OpenHABSitemap sitemap1, OpenHABSitemap sitemap2) { if (sitemap1.getLabel() == null) { return sitemap2.getLabel() == null ? 0 : -1; } if (sitemap2.getLabel() == null) { return 1; } return sitemap1.getLabel().compareTo(sitemap2.getLabel()); } }); return sitemapList; } public static List<OpenHABSitemap> parseSitemapList(JSONArray jsonArray) { List<OpenHABSitemap> sitemapList = new ArrayList<OpenHABSitemap>(); for (int i = 0; i < jsonArray.length(); i++) { try { JSONObject sitemapJson = jsonArray.getJSONObject(i); OpenHABSitemap openHABSitemap = new OpenHAB2Sitemap(sitemapJson); sitemapList.add(openHABSitemap); } catch (JSONException e) { e.printStackTrace(); } } return sitemapList; } public static boolean sitemapExists(List<OpenHABSitemap> sitemapList, String sitemapName) { for (int i = 0; i < sitemapList.size(); i++) { if (sitemapList.get(i).getName().equals(sitemapName)) return true; } return false; } public static OpenHABSitemap getSitemapByName(List<OpenHABSitemap> sitemapList, String sitemapName) { for (int i = 0; i < sitemapList.size(); i++) { if (sitemapList.get(i).getName().equals(sitemapName)) return sitemapList.get(i); } return null; } public static void setActivityTheme(@NonNull final Activity activity) { final String theme = PreferenceManager.getDefaultSharedPreferences(activity).getString(Constants.PREFERENCE_THEME, activity.getString(R.string.theme_value_dark)); int themeRes; if (theme.equals(activity.getString(R.string.theme_value_light))) { themeRes = R.style.HABDroid_Light; } else if (theme.equals(activity.getString(R.string.theme_value_black))) { themeRes = R.style.HABDroid_Black; } else { themeRes = R.style.HABDroid_Dark; } activity.setTheme(themeRes); } }
package org.openmrs.web.servlet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.annotation.Resource; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.openmrs.Concept; import org.openmrs.api.ConceptService; import org.openmrs.api.db.ConceptDAO; import org.openmrs.web.test.BaseWebContextSensitiveTest; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; /** * Tests the {@link DownloadDictionaryServlet}. Since the test dataset for concepts is rather large, * this test uses the ConceptDAO to load specific examples to test the formatting. ConceptDAO is * used to load the concepts rather than the ConceptService because the ConceptService needs to be * mocked to return only the concepts under test. */ public class DownloadDictionaryServletTest extends BaseWebContextSensitiveTest { private static final String EXPECTED_HEADER = "Concept Id,Name,Description,Synonyms,Answers,Set Members,Class,Datatype,Changed By,Creator\n"; @Mock private ConceptService conceptService; @Resource(name = "conceptDAO") private ConceptDAO conceptDAO; @Test public void shouldPrintHeaderAndFormattedConceptLines() throws Exception { String actualContent = runServletWithConcepts(conceptDAO.getConcept(3), conceptDAO.getConcept(5), conceptDAO .getConcept(6)); String expectedContent = EXPECTED_HEADER + "3,\"COUGH SYRUP\",\"This is used for coughs\",\"COUGH SYRUP\",\"\",\"\",\"Drug\",\"N/A\",\"\",\"Super User\"\n" + "5,\"SINGLE\",\"\",\"SINGLE\",\"\",\"\",\"Misc\",\"N/A\",\"\",\"Super User\"\n" + "6,\"MARRIED\",\"\",\"MARRIED\",\"\",\"\",\"Misc\",\"N/A\",\"\",\"Super User\"\n"; Assert.assertEquals(expectedContent, actualContent); } @Test public void shouldFormatMultipleAnswersWithLineBreaks() throws Exception { String actualContent = runServletWithConcepts(conceptDAO.getConcept(4)); String expectedStart = EXPECTED_HEADER + "4,\"CIVIL STATUS\",\"What is the person's marital state\",\"CIVIL STATUS\","; String expectedEnd = ",\"\",\"ConvSet\",\"Coded\",\"Super User\",\"Super User\"\n"; String[] expectedLineBreakSections = { "SINGLE", "MARRIED" }; assertContent(expectedStart, expectedEnd, expectedLineBreakSections, actualContent); } @Test public void shouldFormatMultipleSynonymsWithLineBreaks() throws Exception { String actualContent = runServletWithConcepts(conceptDAO.getConcept(792)); String expectedStart = EXPECTED_HEADER + "792,\"STAVUDINE LAMIVUDINE AND NEVIRAPINE\",\"Combination antiretroviral drug.\","; String expectedEnd = ",\"\",\"\",\"Drug\",\"N/A\",\"Super User\",\"Super User\"\n"; String[] expectedLineBreakSections = { "STAVUDINE LAMIVUDINE AND NEVIRAPINE", "D4T+3TC+NVP", "TRIOMUNE-30", "D4T+3TC+NVP" }; assertContent(expectedStart, expectedEnd, expectedLineBreakSections, actualContent); } @Test public void shouldFormatMultipleSetMembersWithLineBreaks() throws Exception { String actualContent = runServletWithConcepts(conceptDAO.getConcept(23)); String expectedStart = EXPECTED_HEADER + "23,\"FOOD CONSTRUCT\",\"Holder for all things edible\",\"FOOD CONSTRUCT\",\"\","; String expectedEnd = ",\"ConvSet\",\"N/A\",\"\",\"Super User\"\n"; String[] expectedLineBreakSections = { "FOOD ASSISTANCE", "DATE OF FOOD ASSISTANCE", "FAVORITE FOOD, NON-CODED" }; assertContent(expectedStart, expectedEnd, expectedLineBreakSections, actualContent); } @Test public void shouldPrintColumnsWithEmptyQuotesForNullFields() throws Exception { String actualContent = runServletWithConcepts(new Concept(1)); String expectedContent = EXPECTED_HEADER + "1,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n"; Assert.assertEquals(expectedContent, actualContent); } private String runServletWithConcepts(Concept... concepts) throws Exception { DownloadDictionaryServlet downloadServlet = new DownloadDictionaryServlet(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/downloadDictionary.csv"); request.setContextPath("/somecontextpath"); MockHttpServletResponse response = new MockHttpServletResponse(); List<Concept> conceptList = Arrays.asList(concepts); Mockito.when(conceptService.conceptIterator()).thenReturn(conceptList.iterator()); downloadServlet.service(request, response); return response.getContentAsString(); } private void assertContent(String expectedStart, String expectedEnd, String[] expectedLineSections, String actualContent) { Assert.assertTrue(actualContent.startsWith(expectedStart)); Assert.assertTrue(actualContent.endsWith(expectedEnd)); // The content with line breaks can come in any order so test for the content flexibly String lineBreakContent = actualContent.substring(expectedStart.length(), actualContent.length() - expectedEnd.length()); // Should start and end with " Assert.assertTrue(lineBreakContent.startsWith("\"")); Assert.assertTrue(lineBreakContent.endsWith("\"")); lineBreakContent = lineBreakContent.replace("\"", ""); List<String> actualLineBreakSections = Arrays.asList(lineBreakContent.split("\n")); Assert.assertEquals(expectedLineSections.length, actualLineBreakSections.size()); for (String expectedSection : expectedLineSections) { Assert.assertTrue(actualLineBreakSections.contains(expectedSection)); } } }
package io.resourcepool.hvsz.controllers; import io.resourcepool.hvsz.persistance.dao.DaoMapDb; import io.resourcepool.hvsz.persistance.models.Game; import io.resourcepool.hvsz.persistance.models.GameConfig; import io.resourcepool.hvsz.persistance.models.GameStatus; import io.resourcepool.hvsz.persistance.models.GenericBuilder; import io.resourcepool.hvsz.persistance.models.Life; import io.resourcepool.hvsz.persistance.models.SafeZone; import io.resourcepool.hvsz.persistance.models.SupplyZone; import io.resourcepool.hvsz.persistance.models.Zone; import io.resourcepool.hvsz.service.ConfigurationService; import io.resourcepool.hvsz.service.HumanService; import io.resourcepool.hvsz.service.ResourceService; import io.resourcepool.hvsz.service.StatusService; import io.resourcepool.hvsz.service.ZombieService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.util.ArrayList; import java.util.List; @RestController public class RestApiController { @Autowired private DaoMapDb dao; @Autowired private ConfigurationService confService; @Autowired private ZombieService zService; @Autowired private HumanService humanService; @Autowired private ResourceService resourceService; @Autowired private StatusService statusService; private static final Logger LOGGER = LoggerFactory.getLogger(DaoMapDb.class); /** * Get all games. * * @return List all games */ @RequestMapping(value = "/api/game", method = RequestMethod.GET) @ResponseBody public List<Game> getAllGames() { return dao.getAll(); } /** * Init a new game with default config and start it. * * @return List all games */ @RequestMapping(value = "/api/init", method = RequestMethod.GET) @ResponseBody public List<Game> init() { newGame("1"); setGameConfig(1L, "30", "0", "30", "10", "2", "40", "2", "180"); GameConfig conf = confService.get(1L); GameStatus status = GenericBuilder.of(GameStatus::new) .with(GameStatus::setHumanPlayers, conf.getNbHuman()) .with(GameStatus::setZombiePlayers, conf.getNbZombie()) .with(GameStatus::setNbHumanAlive, 0) .with(GameStatus::setTimeLeft, conf.getGameDuration()) .with(GameStatus::setNbLifeLeft, conf.getNbSafezoneLifes()) .with(GameStatus::setStarted, true) .build(); statusService.add(status, 1L); ArrayList<SupplyZone> supplyZones = new ArrayList<>(); int nbSupplyZones = conf.getNbSupplyZone(); int nbSupplyResources = conf.getNbSupplyResources(); for (int i = 0; i < conf.getNbSupplyZone(); i++) { supplyZones.add(new SupplyZone(i, nbSupplyResources / nbSupplyZones)); } resourceService.setSupplyZones(supplyZones); ArrayList<SafeZone> safeZones = new ArrayList<>(); int nbSafeZones = conf.getNbSafezone(); for (int i = 0; i < conf.getNbSafezone(); i++) { safeZones.add(new SafeZone(i, 25, 100)); } resourceService.setSafeZones(safeZones); return dao.getAll(); } /** * Create a new game. * * @param key String * @return Game */ @RequestMapping(value = "/api/game", method = RequestMethod.POST) @ResponseBody public Game newGame(@RequestParam(value = "key", defaultValue = "1") String key) { Long newKey = Long.parseLong(key); dao.set(newKey, new Game(newKey)); //use index, not id return dao.get(newKey); } /** * Get a game by id. * * @param id Long * @return Game */ @RequestMapping(value = "/api/game/{id}", method = RequestMethod.GET) @ResponseBody public Game getGame(@PathVariable(value = "id") Long id) { return dao.get(id); //use index, not id } /** * Get a game by id. * * @param id Long * @return Game */ @RequestMapping(value = "/api/game/{id}/start", method = RequestMethod.POST) @ResponseBody public Game startGame(@PathVariable(value = "id") Long id) { LOGGER.debug("Starting game " + id); GameConfig conf = confService.get(id); GameStatus status = GenericBuilder.of(GameStatus::new) .with(GameStatus::setHumanPlayers, conf.getNbHuman()) .with(GameStatus::setZombiePlayers, conf.getNbZombie()) .with(GameStatus::setNbHumanAlive, 0) .with(GameStatus::setTimeLeft, conf.getGameDuration()) .with(GameStatus::setNbLifeLeft, conf.getNbSafezoneLifes()) .with(GameStatus::setStarted, true) .build(); statusService.add(status, id); ArrayList<SupplyZone> supplyZones = new ArrayList<>(); int nbSupplyZones = conf.getNbSupplyZone(); int nbSupplyResources = conf.getNbSupplyResources(); for (int i = 0; i < conf.getNbSupplyZone(); i++) { supplyZones.add(new SupplyZone(i, nbSupplyResources / nbSupplyZones)); } resourceService.setSupplyZones(supplyZones); ArrayList<SafeZone> safeZones = new ArrayList<>(); int nbSafeZones = conf.getNbSafezone(); for (int i = 0; i < conf.getNbSafezone(); i++) { safeZones.add(new SafeZone(i, 25, 100)); } resourceService.setSafeZones(safeZones); return dao.get(id); } /** * Kill life by token. * * @param id game id. * @param token life token. * @return bool succes? */ @RequestMapping(value = "/api/game/{id}/kill/{token}", method = RequestMethod.POST) @ResponseBody public Boolean killHuman(@PathVariable("id") Long id, @PathVariable(value = "token") String token) { return zService.kill(token); //use index, not id } /** * Get a new life, return token. * * @param id game id. * @return life token */ @RequestMapping(value = "/api/game/{id}/newLife", method = RequestMethod.GET) @ResponseBody public Life newLife(@PathVariable("id") Long id) { return humanService.newLife(); //use index, not id } /** * Set a game config by game id. * * @param id Long * @param gameDuration String * @param difficulty String * @param nbHuman String * @param nbZombie String * @param nbSafezone String * @param nbSafezoneLifes String * @param nbSupplyZone String * @param nbSupplyResources String * @return GameConfig */ @PostMapping("/api/game/{id}/config") @ResponseBody public GameConfig setGameConfig(@PathVariable(value = "id") Long id, @RequestParam(value = "gameDuration", defaultValue = "30") String gameDuration, @RequestParam(value = "difficulty", defaultValue = "0") String difficulty, @RequestParam(value = "nbHuman", defaultValue = "30") String nbHuman, @RequestParam(value = "nbZombie", defaultValue = "10") String nbZombie, @RequestParam(value = "nbSafezone", defaultValue = "2") String nbSafezone, @RequestParam(value = "nbSafezoneLifes", defaultValue = "40") String nbSafezoneLifes, @RequestParam(value = "nbSupplyZone", defaultValue = "2") String nbSupplyZone, @RequestParam(value = "nbSupplyResources", defaultValue = "180") String nbSupplyResources) { GameConfig conf = GenericBuilder.of(GameConfig::new) .with(GameConfig::setGameDuration, Integer.parseInt(gameDuration)) .with(GameConfig::setDifficulty, Integer.parseInt(difficulty)) .with(GameConfig::setNbHuman, Integer.parseInt(nbHuman)) .with(GameConfig::setNbZombie, Integer.parseInt(nbZombie)) .with(GameConfig::setNbSafezone, Integer.parseInt(nbSafezone)) .with(GameConfig::setNbSafezoneLifes, Integer.parseInt(nbSafezoneLifes)) .with(GameConfig::setNbSupplyZone, Integer.parseInt(nbSupplyZone)) .with(GameConfig::setNbSupplyResources, Integer.parseInt(nbSupplyResources)) .build(); confService.add(conf, id); return conf; } /** * Get resource from zone. */ @RequestMapping(value = "/api/game/{id}/zone/{zoneId}/get", method = RequestMethod.POST) @ResponseBody public Integer getResource(@PathVariable(value = "id") Long id, @PathVariable(value = "zoneId") Integer zoneId, @RequestParam(value = "lifeId") Integer lifeId, @RequestParam(value = "qte") Integer qte) { Integer gotRes = humanService.getResources(zoneId, qte, lifeId); return gotRes; } /** * Drop resource in zone. */ @RequestMapping(value = "/api/game/{id}/zone/{zoneId}/drop", method = RequestMethod.POST) @ResponseBody public Integer dropResource(@PathVariable(value = "id") Long id, @PathVariable(value = "zoneId") Integer zoneId, @RequestParam(value = "lifeId") Integer lifeId, @RequestParam(value = "qte") Integer qte) { Integer droppedRes = resourceService.dropById(zoneId, qte, lifeId); return droppedRes; } /** * Get zone from id. * * @return */ @RequestMapping(value = "/api/game/{id}/zone/{zoneId}", method = RequestMethod.GET) @ResponseBody public Zone getZone(@PathVariable(value = "id") Long id, @PathVariable(value = "zoneId") Long zoneId) { //Game g = dao.get(id); //TODO Use zoneservice throw new NotImplementedException(); //return g.getSafeZones().get(1); } }
package org.spine3.server; import com.google.protobuf.Message; import com.google.protobuf.Timestamp; import org.spine3.server.reflect.Classes; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import static com.google.api.client.util.Throwables.propagate; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.newHashMap; import static com.google.protobuf.util.TimeUtil.getCurrentTime; import static org.spine3.server.EntityId.checkType; /** * A server-side wrapper for objects with an identity. * * <p>See {@link EntityId} for supported ID types. * * @param <I> the type of the entity ID * @param <M> the type of the entity state * @author Alexander Yevsyikov * @see EntityId */ public abstract class Entity<I, M extends Message> { /** * The index of the declaration of the generic type {@code M} in this class. */ private static final int STATE_CLASS_GENERIC_INDEX = 1; private final I id; private M state; private Timestamp whenModified; private int version; public Entity(I id) { // We make the constructor public in the abstract class to avoid having protected constructors in derived // classes. We require that entity constructors be public as they are called by repositories. checkType(id); this.id = id; } /** * Obtains the default entity state. * * @return an empty instance of the state class */ @CheckReturnValue protected M getDefaultState() { final Class<? extends Entity> entityClass = getClass(); final DefaultStateRegistry registry = DefaultStateRegistry.getInstance(); if (!registry.contains(entityClass)) { final M state = retrieveDefaultState(); registry.put(entityClass, state); } @SuppressWarnings("unchecked") // cast is safe because this type of messages is saved to the map final M defaultState = (M) registry.get(entityClass); return defaultState; } private M retrieveDefaultState() { final Class<M> stateClass = Classes.getGenericParameterType(getClass(), STATE_CLASS_GENERIC_INDEX); try { final Constructor<M> constructor = stateClass.getDeclaredConstructor(); constructor.setAccessible(true); final M state = constructor.newInstance(); return state; } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw propagate(e); } } /** * Obtains the entity state. * * @return the current state object or the value produced by {@link #getDefaultState()} if the state wasn't set */ @CheckReturnValue public M getState() { final M result = (state == null) ? getDefaultState() : state; return result; } @SuppressWarnings({"NoopMethodInAbstractClass", "UnusedParameters"}) // Have this no-op method to prevent enforcing implementation in all sub-classes. protected void validate(M state) throws IllegalStateException { // Do nothing by default. } /** * Validates and sets the state. * * @param state the state object to set * @param version the entity version to set * @param whenLastModified the time of the last modification to set * @see #validate(M) */ protected void setState(M state, int version, Timestamp whenLastModified) { validate(state); this.state = checkNotNull(state, "state"); this.version = version; this.whenModified = checkNotNull(whenLastModified, "whenLastModified"); } /** * Updates the state incrementing the version number and recording time of the modification. * * @param newState a new state to set */ protected void incrementState(M newState) { setState(newState, incrementVersion(), getCurrentTime()); } /** * Sets the object into the default state. * * <p>Results of this method call are: * <ul> * <li>The state object is set to the value produced by {@link #getDefaultState()}.</li> * <li>The version number is set to zero.</li> * <li>The {@link #whenModified} field is set to the system time of the call.</li> * </ul> * <p>The timestamp is set to current system time. */ protected void setDefault() { setState(getDefaultState(), 0, getCurrentTime()); } /** * @return current version number */ public int getVersion() { return version; } /** * Advances the current version by one and records the time of the modification. * * @return new version number */ protected int incrementVersion() { ++version; whenModified = getCurrentTime(); return version; } @CheckReturnValue public I getId() { return id; } /** * Obtains the timestamp of the last modification. * * @return the timestamp instance or the value produced by {@link Timestamp#getDefaultInstance()} if the state wasn't set * @see #setState(Message, int, Timestamp) */ @CheckReturnValue @Nonnull public Timestamp whenModified() { return (whenModified == null) ? Timestamp.getDefaultInstance() : whenModified; } /** * A wrapper for the map from entity classes to entity default states. */ private static class DefaultStateRegistry { private final Map<Class<? extends Entity>, Message> defaultStates = newHashMap(); /** * Specifies if the entity state of this class is already registered. * * @param entityClass the class to check * @return {@code true} if there is a state for the passed class, {@code false} otherwise */ @CheckReturnValue public boolean contains(Class<? extends Entity> entityClass) { final boolean result = defaultStates.containsKey(entityClass); return result; } public void put(Class<? extends Entity> entityClass, Message state) { if (contains(entityClass)) { throw new IllegalArgumentException("This class is registered already: " + entityClass.getName()); } defaultStates.put(entityClass, state); } /** * Obtains a state for the passed class.. * * @param entityClass an entity class */ @CheckReturnValue public Message get(Class<? extends Entity> entityClass) { final Message state = defaultStates.get(entityClass); return state; } public static DefaultStateRegistry getInstance() { return Singleton.INSTANCE.value; } private enum Singleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final DefaultStateRegistry value = new DefaultStateRegistry(); } } }
package edu.umd.cs.findbugs; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; import javax.annotation.Nonnull; import javax.annotation.Nullable; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.SourceFinder; import edu.umd.cs.findbugs.ba.URLClassPath; import edu.umd.cs.findbugs.charsets.UTF8; import edu.umd.cs.findbugs.cloud.Cloud; import edu.umd.cs.findbugs.cloud.CloudFactory; import edu.umd.cs.findbugs.cloud.CloudPlugin; import edu.umd.cs.findbugs.config.UserPreferences; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLOutputUtil; import edu.umd.cs.findbugs.xml.XMLWriteable; import org.dom4j.DocumentException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import static edu.umd.cs.findbugs.xml.XMLOutputUtil.writeElementList; /** * A project in the GUI. This consists of some number of Jar files to analyze * for bugs, and optionally * <p/> * <ul> * <li>some number of source directories, for locating the program's source code * <li>some number of auxiliary classpath entries, for locating classes * referenced by the program which the user doesn't want to analyze * <li>some number of boolean options * </ul> * * @author David Hovemeyer */ public class Project implements XMLWriteable { private static final boolean DEBUG = SystemProperties.getBoolean("findbugs.project.debug"); private final List<File> currentWorkingDirectoryList; private String projectName; /** * List of jars/directories to analyze */ private List<String> analysisTargets; /** * The list of source directories. */ private List<String> srcDirList; /** * The list of auxiliary classpath entries. */ private List<String> auxClasspathEntryList; /** * Flag to indicate that this Project has been modified. */ private boolean isModified; private String cloudId; private UserPreferences configuration; /** key is plugin id */ private final Map<String,Boolean> enabledPlugins; public boolean getPluginStatus(Plugin plugin) { Boolean b = enabledPlugins.get(plugin.getPluginId()); if (b != null) { return b; } return plugin.isGloballyEnabled(); } public void setPluginStatus(String pluginId, boolean enabled) { enabledPlugins.put(pluginId, enabled); Plugin plugin = Plugin.getByPluginId(pluginId); if(plugin == null) { return; } if (isDefaultInitialPluginState(plugin, enabled)) { enabledPlugins.remove(plugin.getPluginId()); } } public UserPreferences getConfiguration() { return configuration; } /** * @param configuration The configuration to set, non null */ public void setConfiguration(@Nonnull UserPreferences configuration) { if (configuration == null) throw new NullPointerException(); this.configuration = configuration; } /** * @return Returns the cloudId. */ public @CheckForNull String getCloudId() { return cloudId; } /** * @param cloudId * The cloudId to set. */ public void setCloudId(@Nullable String cloudId) { if (cloudId != null && cloudId.indexOf('.') == -1) { Map<String, CloudPlugin> registeredClouds = DetectorFactoryCollection.instance().getRegisteredClouds(); String check = "." + cloudId; int count = 0; String result = cloudId; for(String name : registeredClouds.keySet()) if (name.endsWith(check)) { count++; result = name; } if (count == 1) cloudId = result; } this.cloudId = cloudId; } private Properties cloudProperties = new Properties(); /** * @return Returns the cloudProperties. */ public Properties getCloudProperties() { return cloudProperties; } /** * @param cloudProperties * The cloudProperties to set. */ public void setCloudProperties(Properties cloudProperties) { this.cloudProperties = cloudProperties; } /** * Constant used to name anonymous projects. */ public static final String UNNAMED_PROJECT = "<<unnamed project>>"; private long timestampForAnalyzedClasses = 0L; private IGuiCallback guiCallback; @NonNull private Filter suppressionFilter = new Filter(); private SourceFinder sourceFinder; /** * Create an anonymous project. */ public Project() { enabledPlugins = new HashMap<String,Boolean>(); configuration = UserPreferences.createDefaultUserPreferences(); analysisTargets = new LinkedList<String>(); srcDirList = new LinkedList<String>(); auxClasspathEntryList = new LinkedList<String>(); isModified = false; currentWorkingDirectoryList = new ArrayList<File>(); } /** * Return an exact copy of this Project. */ public Project duplicate() { Project dup = new Project(); dup.currentWorkingDirectoryList.addAll(this.currentWorkingDirectoryList); dup.projectName = this.projectName; dup.analysisTargets.addAll(this.analysisTargets); dup.srcDirList.addAll(this.srcDirList); dup.auxClasspathEntryList.addAll(this.auxClasspathEntryList); dup.timestampForAnalyzedClasses = timestampForAnalyzedClasses; dup.guiCallback = guiCallback; dup.cloudId = cloudId; dup.cloudProperties.putAll(cloudProperties); return dup; } public SourceFinder getSourceFinder() { if (sourceFinder == null) { sourceFinder = new SourceFinder(this); } return sourceFinder; } public boolean isGuiAvaliable() { return guiCallback != null; } /** * add information from project2 to this project */ public void add(Project project2) { analysisTargets = appendWithoutDuplicates(analysisTargets, project2.analysisTargets); srcDirList = appendWithoutDuplicates(srcDirList, project2.srcDirList); auxClasspathEntryList = appendWithoutDuplicates(auxClasspathEntryList, project2.auxClasspathEntryList); } public static <T> List<T> appendWithoutDuplicates(List<T> lst1, List<T> lst2) { LinkedHashSet<T> joined = new LinkedHashSet<T>(lst1); joined.addAll(lst2); return new ArrayList<T>(joined); } public void setCurrentWorkingDirectory(File f) { if (f != null) addWorkingDir(f.toString()); } /** * Return whether or not this Project has unsaved modifications. */ public boolean isModified() { return isModified; } /** * Set whether or not this Project has unsaved modifications. */ public void setModified(boolean isModified) { this.isModified = isModified; } /** * Add a file to the project. * * @param fileName * the file to add * @return true if the file was added, or false if the file was already * present */ public boolean addFile(String fileName) { return addToListInternal(analysisTargets, makeAbsoluteCWD(fileName)); } /** * Add a source directory to the project. * * @param dirName * the directory to add * @return true if the source directory was added, or false if the source * directory was already present */ public boolean addSourceDir(String dirName) { boolean isNew = false; for (String dir : makeAbsoluteCwdCandidates(dirName)) { isNew = addToListInternal(srcDirList, dir) || isNew; } sourceFinder = new SourceFinder(this); return isNew; } /** * Add a working directory to the project. * * @param dirName * the directory to add * @return true if the working directory was added, or false if the working * directory was already present */ public boolean addWorkingDir(String dirName) { if (dirName == null) throw new NullPointerException(); return addToListInternal(currentWorkingDirectoryList, new File(dirName)); } /** * Get the number of files in the project. * * @return the number of files in the project */ public int getFileCount() { return analysisTargets.size(); } /** * Get the given file in the list of project files. * * @param num * the number of the file in the list of project files * @return the name of the file */ public String getFile(int num) { return analysisTargets.get(num); } /** * Remove file at the given index in the list of project files * * @param num * index of the file to remove in the list of project files */ public void removeFile(int num) { analysisTargets.remove(num); isModified = true; } /** * Get the list of files, directories, and zip files in the project. */ public List<String> getFileList() { return analysisTargets; } /** * Get the number of source directories in the project. * * @return the number of source directories in the project */ public int getNumSourceDirs() { return srcDirList.size(); } /** * Get the given source directory. * * @param num * the number of the source directory * @return the source directory */ public String getSourceDir(int num) { return srcDirList.get(num); } /** * Remove source directory at given index. * * @param num * index of the source directory to remove */ public void removeSourceDir(int num) { srcDirList.remove(num); sourceFinder = new SourceFinder(this); isModified = true; } /** * Get project files as an array of Strings. */ public String[] getFileArray() { return analysisTargets.toArray(new String[analysisTargets.size()]); } /** * Get source dirs as an array of Strings. */ public String[] getSourceDirArray() { return srcDirList.toArray(new String[srcDirList.size()]); } /** * Get the source dir list. */ public List<String> getSourceDirList() { return srcDirList; } /** * Add an auxiliary classpath entry * * @param auxClasspathEntry * the entry * @return true if the entry was added successfully, or false if the given * entry is already in the list */ public boolean addAuxClasspathEntry(String auxClasspathEntry) { return addToListInternal(auxClasspathEntryList, makeAbsoluteCWD(auxClasspathEntry)); } /** * Get the number of auxiliary classpath entries. */ public int getNumAuxClasspathEntries() { return auxClasspathEntryList.size(); } /** * Get the n'th auxiliary classpath entry. */ public String getAuxClasspathEntry(int n) { return auxClasspathEntryList.get(n); } /** * Remove the n'th auxiliary classpath entry. */ public void removeAuxClasspathEntry(int n) { auxClasspathEntryList.remove(n); isModified = true; } /** * Return the list of aux classpath entries. */ public List<String> getAuxClasspathEntryList() { return auxClasspathEntryList; } /** * Worklist item for finding implicit classpath entries. */ private static class WorkListItem { private final URL url; /** * Constructor. * * @param url * the URL of the Jar or Zip file */ public WorkListItem(URL url) { this.url = url; } /** * Get URL of Jar/Zip file. */ public URL getURL() { return this.url; } } /** * Worklist for finding implicit classpath entries. */ private static class WorkList { private final LinkedList<WorkListItem> itemList; private final HashSet<String> addedSet; /** * Constructor. Creates an empty worklist. */ public WorkList() { this.itemList = new LinkedList<WorkListItem>(); this.addedSet = new HashSet<String>(); } /** * Create a URL from a filename specified in the project file. */ public URL createURL(String fileName) throws MalformedURLException { String protocol = URLClassPath.getURLProtocol(fileName); if (protocol == null) { fileName = "file:" + fileName; } return new URL(fileName); } /** * Create a URL of a file relative to another URL. */ public URL createRelativeURL(URL base, String fileName) throws MalformedURLException { return new URL(base, fileName); } /** * Add a worklist item. * * @param item * the WorkListItem representing a zip/jar file to be * examined * @return true if the item was added, false if not (because it was * examined already) */ public boolean add(WorkListItem item) { if (DEBUG) { System.out.println("Adding " + item.getURL().toString()); } if (!addedSet.add(item.getURL().toString())) { if (DEBUG) { System.out.println("\t==> Already processed"); } return false; } itemList.add(item); return true; } /** * Return whether or not the worklist is empty. */ public boolean isEmpty() { return itemList.isEmpty(); } /** * Get the next item in the worklist. */ public WorkListItem getNextItem() { return itemList.removeFirst(); } } /** * Return the list of implicit classpath entries. The implicit classpath is * computed from the closure of the set of jar files that are referenced by * the <code>"Class-Path"</code> attribute of the manifest of the any jar * file that is part of this project or by the <code>"Class-Path"</code> * attribute of any directly or indirectly referenced jar. The referenced * jar files that exist are the list of implicit classpath entries. * * @deprecated FindBugs2 and ClassPathBuilder take care of this * automatically */ @Deprecated public List<String> getImplicitClasspathEntryList() { final LinkedList<String> implicitClasspath = new LinkedList<String>(); WorkList workList = new WorkList(); // Prime the worklist by adding the zip/jar files // in the project. for (String fileName : analysisTargets) { try { URL url = workList.createURL(fileName); WorkListItem item = new WorkListItem(url); workList.add(item); } catch (MalformedURLException ignore) { // Ignore } } // Scan recursively. while (!workList.isEmpty()) { WorkListItem item = workList.getNextItem(); processComponentJar(item.getURL(), workList, implicitClasspath); } return implicitClasspath; } /** * Examine the manifest of a single zip/jar file for implicit classapth * entries. * * @param jarFileURL * URL of the zip/jar file * @param workList * worklist of zip/jar files to examine * @param implicitClasspath * list of implicit classpath entries found */ private void processComponentJar(URL jarFileURL, WorkList workList, List<String> implicitClasspath) { if (DEBUG) { System.out.println("Processing " + jarFileURL.toString()); } if (!jarFileURL.toString().endsWith(".zip") && !jarFileURL.toString().endsWith(".jar")) { return; } try { URL manifestURL = new URL("jar:" + jarFileURL.toString() + "!/META-INF/MANIFEST.MF"); InputStream in = null; try { in = manifestURL.openStream(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] fileList = classPath.split("\\s+"); for (String jarFile : fileList) { URL referencedURL = workList.createRelativeURL(jarFileURL, jarFile); if (workList.add(new WorkListItem(referencedURL))) { implicitClasspath.add(referencedURL.toString()); if (DEBUG) { System.out.println("Implicit jar: " + referencedURL.toString()); } } } } } finally { if (in != null) { in.close(); } } } catch (IOException ignore) { // Ignore } } private static final String OPTIONS_KEY = "[Options]"; private static final String JAR_FILES_KEY = "[Jar files]"; private static final String SRC_DIRS_KEY = "[Source dirs]"; private static final String AUX_CLASSPATH_ENTRIES_KEY = "[Aux classpath entries]"; // Option keys public static final String RELATIVE_PATHS = "relative_paths"; /** * Save the project to an output file. * * @param outputFile * name of output file * @param useRelativePaths * true if the project should be written using only relative * paths * @param relativeBase * if useRelativePaths is true, this file is taken as the base * directory in terms of which all files should be made relative * @throws IOException * if an error occurs while writing */ @Deprecated public void write(String outputFile, boolean useRelativePaths, String relativeBase) throws IOException { PrintWriter writer = UTF8.printWriter(outputFile); try { writer.println(JAR_FILES_KEY); for (String jarFile : analysisTargets) { if (useRelativePaths) { jarFile = convertToRelative(jarFile, relativeBase); } writer.println(jarFile); } writer.println(SRC_DIRS_KEY); for (String srcDir : srcDirList) { if (useRelativePaths) { srcDir = convertToRelative(srcDir, relativeBase); } writer.println(srcDir); } writer.println(AUX_CLASSPATH_ENTRIES_KEY); for (String auxClasspathEntry : auxClasspathEntryList) { if (useRelativePaths) { auxClasspathEntry = convertToRelative(auxClasspathEntry, relativeBase); } writer.println(auxClasspathEntry); } if (useRelativePaths) { writer.println(OPTIONS_KEY); writer.println(RELATIVE_PATHS + "=true"); } } finally { writer.close(); } // Project successfully saved isModified = false; } public static Project readXML(File f) throws IOException, DocumentException, SAXException { InputStream in = new BufferedInputStream(new FileInputStream(f)); Project project = new Project(); try { String tag = Util.getXMLType(in); SAXBugCollectionHandler handler; if (tag.equals("Project")) { handler = new SAXBugCollectionHandler(project, f); } else if (tag.equals("BugCollection")) { SortedBugCollection bugs = new SortedBugCollection(project); handler = new SAXBugCollectionHandler(bugs, f); } else { throw new IOException("Can't load a project from a " + tag + " file"); } XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(handler); xr.setErrorHandler(handler); Reader reader = Util.getReader(in); xr.parse(new InputSource(reader)); } finally { in.close(); } // Presumably, project is now up-to-date project.setModified(false); return project; } public void writeXML(File f, @CheckForNull BugCollection bugCollection) throws IOException { OutputStream out = new FileOutputStream(f); XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { writeXML(xmlOutput, f, bugCollection); } finally { xmlOutput.finish(); } } /** * Read Project from named file. * * @param argument * command line argument containing project file name * @return the Project * @throws IOException */ public static Project readProject(String argument) throws IOException { String projectFileName = argument; File projectFile = new File(projectFileName); if (projectFileName.endsWith(".xml") || projectFileName.endsWith(".fbp")) { try { return Project.readXML(projectFile); } catch (DocumentException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } catch (SAXException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } } throw new IllegalArgumentException("Can't read project from " + argument); } /** * Read a line from a BufferedReader, ignoring blank lines and comments. */ private static String getLine(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith(" break; } } return line; } /** * Convert to a string in a nice (displayable) format. */ @Override public String toString() { if (projectName != null) { return projectName; } return UNNAMED_PROJECT; } /** * Transform a user-entered filename into a proper filename, by adding the * ".fb" file extension if it isn't already present. */ public static String transformFilename(String fileName) { if (!fileName.endsWith(".fb")) { fileName = fileName + ".fb"; } return fileName; } static final String JAR_ELEMENT_NAME = "Jar"; static final String AUX_CLASSPATH_ENTRY_ELEMENT_NAME = "AuxClasspathEntry"; static final String SRC_DIR_ELEMENT_NAME = "SrcDir"; static final String WRK_DIR_ELEMENT_NAME = "WrkDir"; static final String FILENAME_ATTRIBUTE_NAME = "filename"; static final String PROJECTNAME_ATTRIBUTE_NAME = "projectName"; static final String CLOUD_ELEMENT_NAME = "Cloud"; static final String CLOUD_ID_ATTRIBUTE_NAME = "id"; static final String CLOUD_PROPERTY_ELEMENT_NAME = "Property"; static final String PLUGIN_ELEMENT_NAME = "Plugin"; static final String PLUGIN_ID_ATTRIBUTE_NAME = "id"; static final String PLUGIN_STATUS_ELEMENT_NAME = "enabled"; public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, null, null); } public void writeXML(XMLOutput xmlOutput, @CheckForNull File destination, @CheckForNull BugCollection bugCollection) throws IOException { { XMLAttributeList attributeList = new XMLAttributeList(); if (getProjectName() != null) { attributeList = attributeList.addAttribute(PROJECTNAME_ATTRIBUTE_NAME, getProjectName()); } xmlOutput.openTag(BugCollection.PROJECT_ELEMENT_NAME, attributeList); } if (destination != null) { String base = destination.getParent(); writeElementList(xmlOutput, JAR_ELEMENT_NAME, convertToRelative(analysisTargets, base)); writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, convertToRelative(auxClasspathEntryList, base)); writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, convertToRelative(srcDirList, base)); List<String> cwdStrings = new ArrayList<String>(); for (File file : currentWorkingDirectoryList) cwdStrings.add(file.getPath()); XMLOutputUtil.writeElementList(xmlOutput, WRK_DIR_ELEMENT_NAME, convertToRelative(cwdStrings, base)); } else { // TODO to allow relative paths: refactor the code which uses null // file arguments writeElementList(xmlOutput, JAR_ELEMENT_NAME, analysisTargets); writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, auxClasspathEntryList); writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, srcDirList); XMLOutputUtil.writeFileList(xmlOutput, WRK_DIR_ELEMENT_NAME, currentWorkingDirectoryList); } if (suppressionFilter != null && !suppressionFilter.isEmpty()) { xmlOutput.openTag("SuppressionFilter"); suppressionFilter.writeBodyAsXML(xmlOutput); xmlOutput.closeTag("SuppressionFilter"); } for(Map.Entry<String, Boolean> e : enabledPlugins.entrySet()) { String pluginId = e.getKey(); Boolean enabled = e.getValue(); Plugin plugin = Plugin.getByPluginId(pluginId); if (plugin == null || isDefaultInitialPluginState(plugin, enabled)) { continue; } XMLAttributeList pluginAttributeList = new XMLAttributeList(); pluginAttributeList.addAttribute(PLUGIN_ID_ATTRIBUTE_NAME, plugin.getPluginId()); pluginAttributeList.addAttribute(PLUGIN_STATUS_ELEMENT_NAME, enabled.toString()); xmlOutput.openCloseTag(PLUGIN_ELEMENT_NAME, pluginAttributeList); } CloudPlugin cloudPlugin = CloudFactory.getCloudPlugin(bugCollection); if (cloudPlugin != null) { String id = cloudPlugin.getId(); if (id == null) id = cloudId; xmlOutput.startTag(CLOUD_ELEMENT_NAME); xmlOutput.addAttribute(CLOUD_ID_ATTRIBUTE_NAME, id); boolean onlineCloud = cloudPlugin.isOnline(); xmlOutput.addAttribute("online", Boolean.toString(onlineCloud)); String url = cloudPlugin.getProperties().getProperty("cloud.detailsUrl"); if (url != null) xmlOutput.addAttribute("detailsUrl", url); xmlOutput.stopTag(false); for (Map.Entry e : cloudProperties.entrySet()) { xmlOutput.startTag(CLOUD_PROPERTY_ELEMENT_NAME); xmlOutput.addAttribute("key", e.getKey().toString()); xmlOutput.stopTag(false); Object value = e.getValue(); xmlOutput.writeText(value.toString()); xmlOutput.closeTag(CLOUD_PROPERTY_ELEMENT_NAME); } xmlOutput.closeTag(CLOUD_ELEMENT_NAME); } xmlOutput.closeTag(BugCollection.PROJECT_ELEMENT_NAME); } private boolean isDefaultInitialPluginState(Plugin plugin, Boolean enabled) { return plugin.isInitialPlugin() && enabled == plugin.isGloballyEnabled() && plugin.isEnabledByDefault() == plugin.isGloballyEnabled(); } /** * Hack for whether files are case insensitive. For now, we'll assume that * Windows is the only case insensitive OS. (OpenVMS users, feel free to * submit a patch :-) */ private static final boolean FILE_IGNORE_CASE = SystemProperties.getProperty("os.name", "unknown").startsWith("Windows"); private Iterable<String> convertToRelative(List<String> paths, String base) { List<String> newList = new ArrayList<String>(paths.size()); for (String path : paths) { newList.add(convertToRelative(path, base)); } return newList; } /** * Converts a full path to a relative path if possible * * @param srcFile * path to convert * @return the converted filename */ private String convertToRelative(String srcFile, String base) { String slash = SystemProperties.getProperty("file.separator"); if (FILE_IGNORE_CASE) { srcFile = srcFile.toLowerCase(); base = base.toLowerCase(); } if (base.equals(srcFile)) { return "."; } if (!base.endsWith(slash)) { base = base + slash; } if (base.length() <= srcFile.length()) { String root = srcFile.substring(0, base.length()); if (root.equals(base)) { // Strip off the base directory, make relative return "." + SystemProperties.getProperty("file.separator") + srcFile.substring(base.length()); } } // See if we can build a relative path above the base using .. notation int slashPos = srcFile.indexOf(slash); int branchPoint; if (slashPos >= 0) { String subPath = srcFile.substring(0, slashPos); if ((subPath.length() == 0) || base.startsWith(subPath)) { branchPoint = slashPos + 1; slashPos = srcFile.indexOf(slash, branchPoint); while (slashPos >= 0) { subPath = srcFile.substring(0, slashPos); if (base.startsWith(subPath)) { branchPoint = slashPos + 1; } else { break; } slashPos = srcFile.indexOf(slash, branchPoint); } int slashCount = 0; slashPos = base.indexOf(slash, branchPoint); while (slashPos >= 0) { slashCount++; slashPos = base.indexOf(slash, slashPos + 1); } StringBuilder path = new StringBuilder(); String upDir = ".." + slash; for (int i = 0; i < slashCount; i++) { path.append(upDir); } path.append(srcFile.substring(branchPoint)); return path.toString(); } } return srcFile; } /** * Converts a relative path to an absolute path if possible. * * @param fileName * path to convert * @return the converted filename */ private String convertToAbsolute(String fileName) throws IOException { // At present relative paths are only calculated if the fileName is // below the project file. This need not be the case, and we could use // syntax to move up the tree. (To Be Added) File file = new File(fileName); if (!file.isAbsolute()) { for (File cwd : currentWorkingDirectoryList) { File test = new File(cwd, fileName); if (test.canRead()) return test.getAbsolutePath(); } return file.getAbsolutePath(); } return fileName; } /** * Make the given filename absolute relative to the current working * directory. */ private String makeAbsoluteCWD(String fileName) { List<String> candidates = makeAbsoluteCwdCandidates(fileName); return candidates.get(0); } /** * Make the given filename absolute relative to the current working * directory candidates. * * If the given filename exists in more than one of the working directories, * a list of these existing absolute paths is returned. * * The returned list is guaranteed to be non-empty. The returned paths might * exist or not exist and might be relative or absolute. * * @return A list of at least one candidate path for the given filename. */ private List<String> makeAbsoluteCwdCandidates(String fileName) { List<String> candidates = new ArrayList<String>(); boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) { candidates.add(fileName); return candidates; } if (new File(fileName).isAbsolute()) { candidates.add(fileName); return candidates; } for (File currentWorkingDirectory : currentWorkingDirectoryList) { File relativeToCurrent = new File(currentWorkingDirectory, fileName); if (relativeToCurrent.exists()) { candidates.add(relativeToCurrent.toString()); } } if (candidates.isEmpty()) { candidates.add(fileName); } return candidates; } /** * Add a value to given list, making the Project modified if the value is * not already present in the list. * * @param list * the list * @param value * the value to be added * @return true if the value was not already present in the list, false * otherwise */ private <T> boolean addToListInternal(Collection<T> list, T value) { if (!list.contains(value)) { list.add(value); isModified = true; return true; } else { return false; } } /** * Make the given list of pathnames absolute relative to the absolute path * of the project file. */ private void makeListAbsoluteProject(List<String> list) throws IOException { List<String> replace = new LinkedList<String>(); for (String fileName : list) { fileName = convertToAbsolute(fileName); replace.add(fileName); } list.clear(); list.addAll(replace); } /** * @param timestamp * The timestamp to set. */ public void setTimestamp(long timestamp) { this.timestampForAnalyzedClasses = timestamp; } public void addTimestamp(long timestamp) { if (this.timestampForAnalyzedClasses < timestamp && FindBugs.validTimestamp(timestamp)) { this.timestampForAnalyzedClasses = timestamp; } } /** * @return Returns the timestamp. */ public long getTimestamp() { return timestampForAnalyzedClasses; } /** * @param projectName * The projectName to set. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return Returns the projectName. */ public String getProjectName() { return projectName; } /** * @param suppressionFilter * The suppressionFilter to set. */ public void setSuppressionFilter(Filter suppressionFilter) { this.suppressionFilter = suppressionFilter; } /** * @return Returns the suppressionFilter. */ public Filter getSuppressionFilter() { if (suppressionFilter == null) { suppressionFilter = new Filter(); } return suppressionFilter; } public void setGuiCallback(IGuiCallback guiCallback) { this.guiCallback = guiCallback; } public IGuiCallback getGuiCallback() { if (guiCallback == null) guiCallback = new CommandLineUiCallback(); return guiCallback; } /** * @return */ public Iterable<String> getResolvedSourcePaths() { List<String> result = new ArrayList<String>(); for (String s : srcDirList) { boolean hasProtocol = (URLClassPath.getURLProtocol(s) != null); if (hasProtocol) { result.add(s); continue; } File f = new File(s); if (f.isAbsolute() || currentWorkingDirectoryList.isEmpty()) { if (f.canRead()) result.add(s); continue; } for (File d : currentWorkingDirectoryList) if (d.canRead() && d.isDirectory()) { File a = new File(d, s); if (a.canRead()) result.add(a.getAbsolutePath()); } } return result; } } // vim:ts=4
package com.game.pts3; import com.badlogic.gdx.*; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.maps.Map; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.game.classes.Character; public class ScreenGame implements Screen, InputProcessor { Stage stage; private Skin skin; private Game game; private Texture texture; private TiledMap tiledMap; private com.game.classes.Game gameState; private OrthographicCamera camera; private TiledMapRenderer renderer; private SpriteBatch batch; private Sprite sprite; private ShapeRenderer shapeRenderer; private float selectedTileX = 0; private float selectedTileY = 0; public ScreenGame(Game game, TiledMap map, com.game.classes.Game gameState){ stage = new Stage(); float width = Gdx.graphics.getWidth(); float height = Gdx.graphics.getHeight(); camera = new OrthographicCamera(); camera.setToOrtho(false, width, height); camera.update(); tiledMap = map; this.gameState = gameState; renderer = new OrthogonalTiledMapRenderer(tiledMap); this.game = game; skin = new Skin(Gdx.files.internal("data/uiskin.json")); shapeRenderer = new ShapeRenderer(); batch = new SpriteBatch(); Label lblGame = new Label("Game start", skin); lblGame.setPosition(10,10); lblGame.setSize(100,100); stage.addActor(lblGame); Gdx.input.setInputProcessor(this); } @Override public void show() { //Gdx.input.setInputProcessor(stage); } @Override public void render(float delta) { Gdx.gl.glClearColor( 0, 0, 0, 1 ); Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT ); camera.update(); /** * Tilemap */ renderer.setView(camera); //batch.setProjectionMatrix(camera.combined); //batch.end(); renderer.render(); shapeRenderer.begin(ShapeRenderer.ShapeType.Line); shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.setColor(0,0,0,1); for (int i = 0; i < gameState.getMap().getSizeX(); i++){ for (int j = 0; j < gameState.getMap().getSizeY(); j++){ shapeRenderer.rect(gameState.getMap().getTileWidth() * i, gameState.getMap().getTileHeight() * j, gameState.getMap().getTileWidth(), gameState.getMap().getTileHeight()); } } shapeRenderer.end(); //batch.begin(); //batch.draw(sprite, 200,200,64,64); /** * Selection Rectangle */ //shapeRenderer.begin(ShapeRenderer.ShapeType.Line); //shapeRenderer.setColor(1, 1, 1, 1); //shapeRenderer.rect(selectedTileX, selectedTileY, 15, 15); //x,y of specific tile //batch.end(); stage.act(); stage.draw(); } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { stage.dispose(); } @Override public boolean keyDown(int keycode) { if(keycode == Input.Keys.LEFT) camera.translate(-32,0); if(keycode == Input.Keys.RIGHT) camera.translate(32,0); if(keycode == Input.Keys.UP) camera.translate(0,32); if(keycode == Input.Keys.DOWN) camera.translate(0,-32); if(keycode == Input.Keys.NUM_1) tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible()); if(keycode == Input.Keys.NUM_2) tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible()); return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { selectedTileX = screenX; selectedTileY = 480 - screenY; // screen height - y System.out.println("Clickered." + screenX + ":" + screenY); return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } }
package ro.isdc.wro.maven.plugin; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.Date; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.plexus.build.incremental.BuildContext; import ro.isdc.wro.config.Context; import ro.isdc.wro.extensions.manager.standalone.ExtensionsStandaloneManagerFactory; import ro.isdc.wro.manager.WroManager.Builder; import ro.isdc.wro.manager.factory.WroManagerFactory; import ro.isdc.wro.manager.factory.WroManagerFactoryDecorator; import ro.isdc.wro.manager.factory.standalone.DefaultStandaloneContextAwareManagerFactory; import ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory; import ro.isdc.wro.model.WroModel; import ro.isdc.wro.model.group.Group; import ro.isdc.wro.model.resource.Resource; import ro.isdc.wro.model.resource.locator.UriLocator; import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory; import ro.isdc.wro.model.resource.processor.ResourcePostProcessor; import ro.isdc.wro.model.resource.processor.factory.ConfigurableProcessorsFactory; import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory; import ro.isdc.wro.model.resource.processor.factory.SimpleProcessorsFactory; import ro.isdc.wro.model.resource.processor.impl.css.CssUrlRewritingProcessor; import ro.isdc.wro.model.resource.support.hash.HashStrategy; import ro.isdc.wro.model.resource.support.naming.ConfigurableNamingStrategy; import ro.isdc.wro.model.resource.support.naming.DefaultHashEncoderNamingStrategy; import ro.isdc.wro.model.resource.support.naming.FolderHashEncoderNamingStrategy; import ro.isdc.wro.model.resource.support.naming.NamingStrategy; import ro.isdc.wro.util.WroTestUtils; import ro.isdc.wro.util.WroUtil; import ro.isdc.wro.util.concurrent.TaskExecutor; /** * Test class for {@link Wro4jMojo} * * @author Alex Objelean */ public class TestWro4jMojo { private static final Logger LOG = LoggerFactory.getLogger(TestWro4jMojo.class); @Mock private BuildContext mockBuildContext; @Mock private HashStrategy mockHashStrategy; private UriLocatorFactory mockLocatorFactory; @Mock private UriLocator mockLocator; private File cssDestinationFolder; private File jsDestinationFolder; private File destinationFolder; private File extraConfigFile; private Wro4jMojo victim; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mockLocatorFactory = new UriLocatorFactory() { public InputStream locate(final String uri) throws IOException { return mockLocator.locate(uri); } public UriLocator getInstance(final String uri) { return mockLocator; } }; Context.set(Context.standaloneContext()); victim = new Wro4jMojo(); setUpMojo(victim); } /** * Perform basic initialization with valid values of the provided mojo. */ private void setUpMojo(final Wro4jMojo mojo) throws Exception { mojo.setIgnoreMissingResources(false); mojo.setParallelProcessing(false); mojo.setMinimize(true); setWroWithValidResources(); destinationFolder = new File(FileUtils.getTempDirectory(), "wroTemp-" + new Date().getTime()); destinationFolder.mkdir(); cssDestinationFolder = new File(FileUtils.getTempDirectory(), "wroTemp-css-" + new Date().getTime()); destinationFolder.mkdir(); jsDestinationFolder = new File(FileUtils.getTempDirectory(), "wroTemp-js-" + new Date().getTime()); destinationFolder.mkdir(); extraConfigFile = new File(FileUtils.getTempDirectory(), "extraConfig-" + new Date().getTime()); extraConfigFile.createNewFile(); mojo.setBuildDirectory(destinationFolder); mojo.setExtraConfigFile(extraConfigFile); mojo.setDestinationFolder(destinationFolder); final MavenProject mockMavenProject = Mockito.mock(MavenProject.class); final Model mockMavenModel = Mockito.mock(Model.class); final Build mockBuild = Mockito.mock(Build.class); Mockito.when(mockMavenProject.getModel()).thenReturn(mockMavenModel); Mockito.when(mockMavenModel.getBuild()).thenReturn(mockBuild); Mockito.when(mockBuild.getDirectory()).thenReturn(FileUtils.getTempDirectoryPath()); mojo.setMavenProject(mockMavenProject); mojo.setBuildContext(mockBuildContext); } private void setWroFile(final String classpathResourceName) throws URISyntaxException { final URL url = getClass().getClassLoader().getResource(classpathResourceName); final File wroFile = new File(url.toURI()); victim.setWroFile(wroFile); victim.setContextFolder(wroFile.getParentFile().getPath()); } private void setWroWithValidResources() throws Exception { setWroFile("wro.xml"); } private void setWroWithInvalidResources() throws Exception { setWroFile("wroWithInvalidResources.xml"); } @Test public void testMojoWithPropertiesSetAndOneTargetGroup() throws Exception { victim.setTargetGroups("g1"); victim.setIgnoreMissingResources(true); victim.execute(); } @Test(expected = MojoExecutionException.class) public void shouldFailWhenInvalidResourcesAreUsed() throws Exception { victim.setIgnoreMissingResources(false); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testNoDestinationFolderSet() throws Exception { victim.setDestinationFolder(null); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testOnlyCssDestinationFolderSet() throws Exception { victim.setCssDestinationFolder(cssDestinationFolder); victim.setDestinationFolder(null); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testOnlyJsDestinationFolderSet() throws Exception { victim.setJsDestinationFolder(jsDestinationFolder); victim.setDestinationFolder(null); victim.execute(); } @Test public void testJsAndCssDestinationFolderSet() throws Exception { victim.setIgnoreMissingResources(true); victim.setJsDestinationFolder(jsDestinationFolder); victim.setCssDestinationFolder(cssDestinationFolder); victim.execute(); } @Test(expected = MojoExecutionException.class) public void cannotExecuteWhenInvalidResourcesPresentAndDoNotIgnoreMissingResources() throws Exception { setWroWithInvalidResources(); victim.setIgnoreMissingResources(false); victim.execute(); } @Test public void testWroXmlWithInvalidResourcesAndIgnoreMissingResourcesTrue() throws Exception { setWroWithInvalidResources(); victim.setIgnoreMissingResources(true); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testMojoWithWroManagerFactorySet() throws Exception { victim.setWroManagerFactory(ExceptionThrowingWroManagerFactory.class.getName()); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testInvalidMojoWithWroManagerFactorySet() throws Exception { victim.setWroManagerFactory("INVALID_CLASS_NAME"); victim.execute(); } @Test public void executeWithNullTargetGroupsProperty() throws Exception { victim.setIgnoreMissingResources(true); victim.setTargetGroups(null); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testMojoWithCustomManagerFactoryWithInvalidResourceAndNotIgnoreMissingResources() throws Exception { setWroWithInvalidResources(); victim.setIgnoreMissingResources(false); victim.setWroManagerFactory(CustomManagerFactory.class.getName()); victim.execute(); } @Test public void testMojoWithCustomManagerFactoryWithInvalidResourceAndIgnoreMissingResources() throws Exception { setWroWithInvalidResources(); victim.setIgnoreMissingResources(true); victim.setWroManagerFactory(CustomManagerFactory.class.getName()); victim.execute(); } @Test(expected = MojoExecutionException.class) public void testMojoWithConfigurableWroManagerFactory() throws Exception { setWroWithValidResources(); victim.setIgnoreMissingResources(true); // by default a valid file is used, set null explicitly victim.setExtraConfigFile(null); victim.setWroManagerFactory(ConfigurableWroManagerFactory.class.getName()); victim.execute(); } @Test public void testMojoWithConfigurableWroManagerFactoryWithValidAndEmptyConfigFileSet() throws Exception { setWroWithValidResources(); victim.setIgnoreMissingResources(true); victim.setWroManagerFactory(ConfigurableWroManagerFactory.class.getName()); victim.execute(); } @Test public void testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet() throws Exception { setWroWithValidResources(); final String preProcessors = ConfigurableProcessorsFactory.PARAM_PRE_PROCESSORS + "=cssMin"; FileUtils.write(extraConfigFile, preProcessors); victim.setIgnoreMissingResources(true); victim.setWroManagerFactory(ConfigurableWroManagerFactory.class.getName()); victim.execute(); } /** * Ignoring this test, since it is not reliable. */ @Ignore @Test public void shouldBeFasterWhenRunningProcessingInParallel() throws Exception { //warmup testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet(); //start actual test final long begin = System.currentTimeMillis(); victim.setParallelProcessing(false); testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet(); final long endSerial = System.currentTimeMillis(); victim.setParallelProcessing(true); testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet(); final long endParallel = System.currentTimeMillis(); final long serial = endSerial - begin; final long parallel = endParallel - endSerial; LOG.info("serial took: {}ms", serial); LOG.info("parallel took: {}ms", parallel); assertTrue(String.format("Serial (%s) > Parallel (%s)", serial, parallel), serial > parallel); } @Test public void shouldUseTaskExecutorWhenRunningInParallel() throws Exception { final AtomicBoolean invoked = new AtomicBoolean(); final TaskExecutor<Void> taskExecutor = new TaskExecutor<Void>() { @Override public void submit(final Collection<Callable<Void>> callables) throws Exception { invoked.set(true); super.submit(callables); } }; victim.setTaskExecutor(taskExecutor); victim.setIgnoreMissingResources(true); victim.setParallelProcessing(false); victim.execute(); assertFalse(invoked.get()); victim.setParallelProcessing(true); victim.execute(); assertTrue(invoked.get()); } @Test public void shouldComputedAggregatedFolderWhenContextPathIsSet() throws Exception { setWroWithValidResources(); victim.setWroManagerFactory(CssUrlRewriterWroManagerFactory.class.getName()); victim.setIgnoreMissingResources(true); final File cssDestinationFolder = new File(this.destinationFolder, "subfolder"); cssDestinationFolder.mkdir(); victim.setCssDestinationFolder(cssDestinationFolder); victim.execute(); assertEquals("/subfolder", WroUtil.normalize(Context.get().getAggregatedFolderPath())); victim.setContextPath("app"); victim.execute(); assertEquals("/app", Context.get().getRequest().getContextPath()); victim.setContextPath("/app/"); victim.execute(); assertEquals("/app", Context.get().getRequest().getContextPath()); victim.setContextPath("/"); victim.execute(); assertEquals("/", Context.get().getRequest().getContextPath()); } @Test(expected = MojoExecutionException.class) public void testMojoWithConfigurableWroManagerFactoryWithInvalidPreProcessor() throws Exception { setWroWithValidResources(); final String preProcessors = ConfigurableProcessorsFactory.PARAM_PRE_PROCESSORS + "=INVALID"; FileUtils.write(extraConfigFile, preProcessors); victim.setIgnoreMissingResources(true); victim.setWroManagerFactory(ConfigurableWroManagerFactory.class.getName()); victim.execute(); } @Test public void shouldGenerateGroupMappingUsingNoOpNamingStrategy() throws Exception { setWroWithValidResources(); final File groupNameMappingFile = new File(FileUtils.getTempDirectory(), "groupMapping-" + new Date().getTime()); victim.setGroupNameMappingFile(groupNameMappingFile); victim.setIgnoreMissingResources(true); victim.execute(); // verify final Properties groupNames = new Properties(); groupNames.load(new FileInputStream(groupNameMappingFile)); LOG.debug("groupNames: {}", groupNames); assertEquals("g1.js", groupNames.get("g1.js")); FileUtils.deleteQuietly(groupNameMappingFile); } @Test public void shouldGenerateGroupMappingUsingCustomNamingStrategy() throws Exception { setWroWithValidResources(); final File groupNameMappingFile = new File(FileUtils.getTempDirectory(), "groupMapping-" + new Date().getTime()); victim.setWroManagerFactory(CustomNamingStrategyWroManagerFactory.class.getName()); victim.setGroupNameMappingFile(groupNameMappingFile); victim.setIgnoreMissingResources(true); victim.execute(); // verify final Properties groupNames = new Properties(); groupNames.load(new FileInputStream(groupNameMappingFile)); LOG.debug("groupNames: {}", groupNames); Assert.assertEquals(CustomNamingStrategyWroManagerFactory.PREFIX + "g1.js", groupNames.get("g1.js")); FileUtils.deleteQuietly(groupNameMappingFile); } /** * Uses a not existing folder to store groupNameMappingFile and proves that it is getting created instead of failing. */ @Test public void shouldCreateMissingFolderForGroupNameMappingFile() throws Exception { final File parentFolder = new File(FileUtils.getTempDirectory(), "wro4j-" + UUID.randomUUID()); try { setWroWithValidResources(); final File groupNameMappingFile = new File(parentFolder, "groupMapping-" + new Date().getTime()); victim.setWroManagerFactory(CustomNamingStrategyWroManagerFactory.class.getName()); victim.setGroupNameMappingFile(groupNameMappingFile); victim.setIgnoreMissingResources(true); victim.execute(); } finally { FileUtils.deleteQuietly(parentFolder); } } @Test public void shouldSkipSecondProcessingWhenIncrementalBuildEnabled() throws Exception { victim.setBuildContext(null); victim.setIncrementalBuildEnabled(true); testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet(); testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet(); } @Test public void shouldUseConfiguredNamingStrategy() throws Exception { setWroWithValidResources(); final File extraConfigFile = new File(FileUtils.getTempDirectory(), "groupMapping-" + new Date().getTime()); final Properties props = new Properties(); // TODO create a properties builder props.setProperty(ConfigurableNamingStrategy.KEY, FolderHashEncoderNamingStrategy.ALIAS); props.list(new PrintStream(extraConfigFile)); victim.setWroManagerFactory(ConfigurableWroManagerFactory.class.getName()); victim.setExtraConfigFile(extraConfigFile); victim.setIgnoreMissingResources(true); victim.execute(); FileUtils.deleteQuietly(extraConfigFile); } public static final class ExceptionThrowingWroManagerFactory extends DefaultStandaloneContextAwareManagerFactory { @Override protected ProcessorsFactory newProcessorsFactory() { final SimpleProcessorsFactory factory = new SimpleProcessorsFactory(); final ResourcePostProcessor postProcessor = Mockito.mock(ResourcePostProcessor.class); try { Mockito.doThrow(new RuntimeException()).when(postProcessor).process(Mockito.any(Reader.class), Mockito.any(Writer.class)); } catch (final IOException e) { Assert.fail("never happen"); } factory.addPostProcessor(postProcessor); return factory; } } public static class CustomManagerFactory extends DefaultStandaloneContextAwareManagerFactory { } public static final class CustomNamingStrategyWroManagerFactory extends DefaultStandaloneContextAwareManagerFactory { public static final String PREFIX = "renamed"; { setNamingStrategy(new NamingStrategy() { public String rename(final String originalName, final InputStream inputStream) throws IOException { return PREFIX + originalName; } }); } } public static final class CssUrlRewriterWroManagerFactory extends DefaultStandaloneContextAwareManagerFactory { @Override protected ProcessorsFactory newProcessorsFactory() { final SimpleProcessorsFactory factory = new SimpleProcessorsFactory(); factory.addPreProcessor(new CssUrlRewritingProcessor()); return factory; } } @Test public void shouldDetectIncrementalChange() throws Exception { victim = new Wro4jMojo() { @Override protected WroManagerFactory newWroManagerFactory() throws MojoExecutionException { return new WroManagerFactoryDecorator(new ExtensionsStandaloneManagerFactory()) { @Override protected void onBeforeBuild(final Builder builder) { builder.setHashStrategy(mockHashStrategy); } }; } }; setUpMojo(victim); final String hashValue = "SomeHashValue"; when(mockHashStrategy.getHash(Mockito.any(InputStream.class))).thenReturn(hashValue); when(mockBuildContext.isIncremental()).thenReturn(true); when(mockBuildContext.getValue(Mockito.anyString())).thenReturn(hashValue); victim.setIgnoreMissingResources(true); // incremental build detects no change assertTrue(victim.getTargetGroupsAsList().isEmpty()); // incremental change detects change for all resources when(mockHashStrategy.getHash(Mockito.any(InputStream.class))).thenReturn("TotallyDifferentValue"); assertFalse(victim.getTargetGroupsAsList().isEmpty()); } @Test public void shouldDetectIncrementalChangeOfImportedCss() throws Exception { final String importResource = "imported.css"; configureMojoForModelWithImportedCssResource(importResource); // incremental build detects no change assertTrue(victim.getTargetGroupsAsList().isEmpty()); when(mockLocator.locate(Mockito.eq(importResource))).thenAnswer(answerWithContent("Changed")); assertFalse(victim.getTargetGroupsAsList().isEmpty()); } private void configureMojoForModelWithImportedCssResource(final String importResource) throws Exception { final String parentResource = "parent.css"; final WroModel model = new WroModel(); model.addGroup(new Group("g1").addResource(Resource.create(parentResource))); when(mockLocator.locate(Mockito.anyString())).thenAnswer(answerWithContent("")); final String parentContent = String.format("@import url(%s)", importResource); when(mockLocator.locate(Mockito.eq(parentResource))).thenAnswer(answerWithContent(parentContent)); victim = new Wro4jMojo() { @Override protected WroManagerFactory newWroManagerFactory() throws MojoExecutionException { final DefaultStandaloneContextAwareManagerFactory managerFactory = new DefaultStandaloneContextAwareManagerFactory(); managerFactory.setUriLocatorFactory(mockLocatorFactory); managerFactory.setModelFactory(WroTestUtils.simpleModelFactory(model)); return managerFactory; } }; final HashStrategy hashStrategy = victim.getManagerFactory().create().getHashStrategy(); setUpMojo(victim); final String importedInitialContent = "initial"; when(mockLocator.locate(Mockito.eq(importResource))).thenAnswer(answerWithContent(importedInitialContent)); when(mockBuildContext.isIncremental()).thenReturn(true); when(mockBuildContext.getValue(Mockito.eq(parentResource))).thenReturn( hashStrategy.getHash(new ByteArrayInputStream(parentContent.getBytes()))); when(mockBuildContext.getValue(Mockito.eq(importResource))).thenReturn( hashStrategy.getHash(new ByteArrayInputStream(importedInitialContent.getBytes()))); victim.setIgnoreMissingResources(true); } @Test public void shouldIgnoreChangesOfGroupsWhichAreNotPartOfTargetGroups() throws Exception { final String importResource = "imported.css"; configureMojoForModelWithImportedCssResource(importResource); victim.setTargetGroups("g2"); // incremental build detects no change assertTrue(victim.getTargetGroupsAsList().isEmpty()); when(mockLocator.locate(Mockito.eq(importResource))).thenAnswer(answerWithContent("Changed")); assertTrue(victim.getTargetGroupsAsList().isEmpty()); } @Test public void shouldReuseGroupNameMappingFileWithIncrementalBuild() throws Exception { final File groupNameMappingFile = WroUtil.createTempFile(); final Resource g1Resource = spy(Resource.create("1.js")); try { final WroModel model = new WroModel(); model.addGroup(new Group("g1").addResource(g1Resource)); model.addGroup(new Group("g2").addResource(Resource.create("2.js"))); victim = new Wro4jMojo() { @Override protected WroManagerFactory newWroManagerFactory() throws MojoExecutionException { final DefaultStandaloneContextAwareManagerFactory managerFactory = new DefaultStandaloneContextAwareManagerFactory(); managerFactory.setUriLocatorFactory(WroTestUtils.createResourceMockingLocatorFactory()); managerFactory.setModelFactory(WroTestUtils.simpleModelFactory(model)); managerFactory.setNamingStrategy(new DefaultHashEncoderNamingStrategy()); return managerFactory; } }; setUpMojo(victim); victim.setGroupNameMappingFile(groupNameMappingFile); assertEquals(2, victim.getTargetGroupsAsList().size()); victim.execute(); // Now mark it as incremental when(mockBuildContext.isIncremental()).thenReturn(true); final Properties groupNames = new Properties(); groupNames.load(new FileInputStream(groupNameMappingFile)); assertEquals(4, groupNames.entrySet().size()); // change the uri of the resource from group a (equivalent to changing its content). when(g1Resource.getUri()).thenReturn("1a.js"); assertEquals(1, victim.getTargetGroupsAsList().size()); victim.execute(); groupNames.load(new FileInputStream(groupNameMappingFile)); // The number of persisted groupNames should still be unchanged, even though only a single group has been changed // after incremental build. assertEquals(4, groupNames.entrySet().size()); } finally { FileUtils.deleteQuietly(groupNameMappingFile); } } /** * Test for the following scenario: when incremental build is performed, only changed resources are processed. Given * that there are two target groups, and a resource from only one group is changed incremental build should process * only that one group. However, if the targetFolder does not exist, all target groups must be processed. */ @Test public void shouldProcessTargetGroupsWhenDestinationFolderDoesNotExist() throws Exception { victim = new Wro4jMojo() { @Override protected WroManagerFactory newWroManagerFactory() throws MojoExecutionException { return new WroManagerFactoryDecorator(new ExtensionsStandaloneManagerFactory()) { @Override protected void onBeforeBuild(final Builder builder) { builder.setHashStrategy(mockHashStrategy); } }; } }; final String constantHash = "hash"; when(mockHashStrategy.getHash(Mockito.any(InputStream.class))).thenReturn(constantHash); setUpMojo(victim); victim.setIgnoreMissingResources(true); final int totalGroups = 10; assertEquals(totalGroups, victim.getTargetGroupsAsList().size()); when(mockBuildContext.isIncremental()).thenReturn(true); when(mockBuildContext.getValue(Mockito.anyString())).thenReturn(constantHash); assertEquals(0, victim.getTargetGroupsAsList().size()); // delete target folder destinationFolder.delete(); assertEquals(totalGroups, victim.getTargetGroupsAsList().size()); victim.doExecute(); } private Answer<InputStream> answerWithContent(final String content) { return new Answer<InputStream>() { public InputStream answer(final InvocationOnMock invocation) throws Throwable { return new ByteArrayInputStream(content.getBytes()); } }; } /** * Verify that the plugin execution does not fail when one of the context folder is invalid. */ @Test public void shouldUseMultipleContextFolders() throws Exception { final String defaultContextFolder = victim.getContextFoldersAsCSV(); victim.setTargetGroups("contextRelative"); victim.setContextFolder("invalid, " + defaultContextFolder); victim.doExecute(); // reversed order should work the same victim.setContextFolder(defaultContextFolder + ", invalid"); victim.doExecute(); } @Test public void shouldSkipExecutionWhenSkipIsEnabled() throws Exception { victim.setSkip(false); try { victim.execute(); fail("should have failed"); } catch (final MojoExecutionException e) { } victim.setSkip(true); victim.execute(); } @Test public void shouldRefreshParentFolderWhenBuildContextSet() throws Exception { final BuildContext buildContext = Mockito.mock(BuildContext.class); victim.setBuildContext(buildContext); testMojoWithConfigurableWroManagerFactoryWithValidConfigFileSet(); verify(buildContext, Mockito.atLeastOnce()).refresh(Mockito.eq(destinationFolder)); } @After public void tearDown() throws Exception { victim.clean(); FileUtils.deleteDirectory(destinationFolder); FileUtils.deleteDirectory(cssDestinationFolder); FileUtils.deleteDirectory(jsDestinationFolder); FileUtils.deleteQuietly(extraConfigFile); } }
package org.knowm.xchange.bittrex.v1; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.exceptions.ExchangeException; /** * A central place for shared Bittrex properties */ public final class BittrexUtils { private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"; private static final String DATE_FORMAT_NO_MILLIS = "yyyy-MM-dd'T'HH:mm:ss"; private static final SimpleDateFormat DATE_PARSER = new SimpleDateFormat(DATE_FORMAT); private static final SimpleDateFormat DATE_PARSER_NO_MILLIS = new SimpleDateFormat(DATE_FORMAT_NO_MILLIS); private static final TimeZone TIME_ZONE = TimeZone.getTimeZone("UTC"); static { DATE_PARSER.setTimeZone(TIME_ZONE); DATE_PARSER_NO_MILLIS.setTimeZone(TIME_ZONE); } /** * private Constructor */ private BittrexUtils() { } public static String toPairString(CurrencyPair currencyPair) { return currencyPair.counter.getCurrencyCode().toUpperCase() + "-" + currencyPair.base.getCurrencyCode().toUpperCase(); } public static Date toDate(String dateString) { try { return DATE_PARSER.parse(dateString); } catch (ParseException e) { try { return DATE_PARSER_NO_MILLIS.parse(dateString); } catch (ParseException e1) { throw new ExchangeException("Illegal date/time format", e1); } } } }
package org.knowm.xchange.coinmate; import org.knowm.xchange.currency.CurrencyPair; /** * Conversion between XChange CurrencyPair and Coinmate API * * @author Martin Stachon */ public class CoinmateUtils { public static String getPair(CurrencyPair currencyPair) { if (currencyPair == null) { return null; } return currencyPair.base.getCurrencyCode().toUpperCase() + "_" + currencyPair.counter.getCurrencyCode().toUpperCase(); } public static CurrencyPair getPair(String currencyPair) { return new CurrencyPair(currencyPair.replace("_","/")); } }
package com.thoughtworks.acceptance.objects; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class SampleDynamicProxy implements InvocationHandler { private String aField = "hello"; public static interface InterfaceOne { String doSomething(); } public static interface InterfaceTwo { String doSomething(); } public static Object newInstance() { return Proxy.newProxyInstance(InterfaceOne.class.getClassLoader(), new Class[]{InterfaceOne.class, InterfaceTwo.class}, new SampleDynamicProxy()); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("equals")) { return equals(args[0]) ? Boolean.TRUE : Boolean.FALSE; } else if (method.getName().equals("hashCode")) { return new Integer(System.identityHashCode(proxy)); } else { return aField; } } public boolean equals(Object obj) { return equalsInterfaceOne(obj) && equalsInterfaceTwo(obj); } private boolean equalsInterfaceOne(Object o) { if (o instanceof InterfaceOne) { InterfaceOne interfaceOne = (InterfaceOne) o; return aField.equals(interfaceOne.doSomething()); } else { return false; } } private boolean equalsInterfaceTwo(Object o) { if (o instanceof InterfaceTwo) { InterfaceTwo interfaceTwo = (InterfaceTwo) o; return aField.equals(interfaceTwo.doSomething()); } else { return false; } } }
package com.journeyapps.barcodescanner; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import android.view.ViewGroup; import android.view.WindowManager; import com.google.zxing.client.android.R; import com.journeyapps.barcodescanner.camera.CameraInstance; import com.journeyapps.barcodescanner.camera.CameraSettings; import com.journeyapps.barcodescanner.camera.CameraSurface; import com.journeyapps.barcodescanner.camera.CenterCropStrategy; import com.journeyapps.barcodescanner.camera.FitCenterStrategy; import com.journeyapps.barcodescanner.camera.DisplayConfiguration; import com.journeyapps.barcodescanner.camera.FitXYStrategy; import com.journeyapps.barcodescanner.camera.PreviewScalingStrategy; import java.util.ArrayList; import java.util.List; /** * CameraPreview is a view that handles displaying of a camera preview on a SurfaceView. It is * intended to be used as a base for realtime processing of camera images, e.g. barcode decoding * or OCR, although none of this happens in CameraPreview itself. * * The camera is managed on a separate thread, using CameraInstance. * * Two methods MUST be called on CameraPreview to manage its state: * 1. resume() - initialize the camera and start the preview. Call from the Activity's onResume(). * 2. pause() - stop the preview and release any resources. Call from the Activity's onPause(). * * Startup sequence: * * 1. Create SurfaceView. * 2. open camera. * 2. layout this container, to get size * 3. set display config, according to the container size * 4. configure() * 5. wait for preview size to be ready * 6. set surface size according to preview size * 7. set surface and start preview */ public class CameraPreview extends ViewGroup { public interface StateListener { /** * Preview and frame sizes are determined. */ void previewSized(); /** * Preview has started. */ void previewStarted(); /** * Preview has stopped. */ void previewStopped(); /** * The camera has errored, and cannot display a preview. * * @param error the error */ void cameraError(Exception error); } private static final String TAG = CameraPreview.class.getSimpleName(); private CameraInstance cameraInstance; private WindowManager windowManager; private Handler stateHandler; private boolean useTextureView = false; private SurfaceView surfaceView; private TextureView textureView; private boolean previewActive = false; private RotationListener rotationListener; private int openedOrientation = -1; // Delay after rotation change is detected before we reorientate ourselves. // This is to avoid double-reinitialization when the Activity is destroyed and recreated. private static final int ROTATION_LISTENER_DELAY_MS = 250; private List<StateListener> stateListeners = new ArrayList<>(); private DisplayConfiguration displayConfiguration; private CameraSettings cameraSettings = new CameraSettings(); // Size of this container, non-null after layout is performed private Size containerSize; // Size of the preview resolution private Size previewSize; // Rect placing the preview surface private Rect surfaceRect; // Size of the current surface. non-null if the surface is ready private Size currentSurfaceSize; // Framing rectangle relative to this view private Rect framingRect = null; // Framing rectangle relative to the preview resolution private Rect previewFramingRect = null; // Size of the framing rectangle. If null, defaults to using a margin percentage. private Size framingRectSize = null; // Fraction of the width / heigth to use as a margin. This fraction is used on each size, so // must be smaller than 0.5; private double marginFraction = 0.1d; private PreviewScalingStrategy previewScalingStrategy = null; private boolean torchOn = false; @TargetApi(14) private TextureView.SurfaceTextureListener surfaceTextureListener() { // Cannot initialize automatically, since we may be API < 14 return new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { onSurfaceTextureSizeChanged(surface, width, height); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { currentSurfaceSize = new Size(width, height); startPreviewIfReady(); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; } private final SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { currentSurfaceSize = null; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceChanged() gave us a null surface!"); return; } currentSurfaceSize = new Size(width, height); startPreviewIfReady(); } }; private final Handler.Callback stateCallback = new Handler.Callback() { @Override public boolean handleMessage(Message message) { if (message.what == R.id.zxing_prewiew_size_ready) { previewSized((Size) message.obj); return true; } else if (message.what == R.id.zxing_camera_error) { Exception error = (Exception) message.obj; if (isActive()) { // This check prevents multiple errors from begin passed through. pause(); fireState.cameraError(error); } } return false; } }; private RotationCallback rotationCallback = new RotationCallback() { @Override public void onRotationChanged(int rotation) { // Make sure this is run on the main thread. stateHandler.postDelayed(new Runnable() { @Override public void run() { rotationChanged(); } }, ROTATION_LISTENER_DELAY_MS); } }; public CameraPreview(Context context) { super(context); initialize(context, null, 0, 0); } public CameraPreview(Context context, AttributeSet attrs) { super(context, attrs); initialize(context, attrs, 0, 0); } public CameraPreview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs, defStyleAttr, 0); } private void initialize(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { if (getBackground() == null) { // Default to SurfaceView colour, so that there are less changes. setBackgroundColor(Color.BLACK); } initializeAttributes(attrs); windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); stateHandler = new Handler(stateCallback); rotationListener = new RotationListener(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); setupSurfaceView(); } /** * Initialize from XML attributes. * * @param attrs the attributes */ protected void initializeAttributes(AttributeSet attrs) { TypedArray styledAttributes = getContext().obtainStyledAttributes(attrs, R.styleable.zxing_camera_preview); int framingRectWidth = (int) styledAttributes.getDimension(R.styleable.zxing_camera_preview_zxing_framing_rect_width, -1); int framingRectHeight = (int) styledAttributes.getDimension(R.styleable.zxing_camera_preview_zxing_framing_rect_height, -1); if (framingRectWidth > 0 && framingRectHeight > 0) { this.framingRectSize = new Size(framingRectWidth, framingRectHeight); } this.useTextureView = styledAttributes.getBoolean(R.styleable.zxing_camera_preview_zxing_use_texture_view, true); // See zxing_attrs.xml for the enum values int scalingStrategyNumber = styledAttributes.getInteger(R.styleable.zxing_camera_preview_zxing_preview_scaling_strategy, -1); if(scalingStrategyNumber == 1) { previewScalingStrategy = new CenterCropStrategy(); } else if(scalingStrategyNumber == 2) { previewScalingStrategy = new FitCenterStrategy(); } else if(scalingStrategyNumber == 3) { previewScalingStrategy = new FitXYStrategy(); } styledAttributes.recycle(); } private void rotationChanged() { // Confirm that it did actually change if(isActive() && getDisplayRotation() != openedOrientation) { pause(); resume(); } } @SuppressWarnings("deprecation") @SuppressLint("NewAPI") private void setupSurfaceView() { if(useTextureView && Build.VERSION.SDK_INT >= 14) { textureView = new TextureView(getContext()); textureView.setSurfaceTextureListener(surfaceTextureListener()); addView(textureView); } else { surfaceView = new SurfaceView(getContext()); if (Build.VERSION.SDK_INT < 11) { surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } surfaceView.getHolder().addCallback(surfaceCallback); addView(surfaceView); } } /** * Add a listener to be notified of changes to the preview state, as well as camera errors. * * @param listener the listener */ public void addStateListener(StateListener listener) { stateListeners.add(listener); } private final StateListener fireState = new StateListener() { @Override public void previewSized() { for (StateListener listener : stateListeners) { listener.previewSized(); } } @Override public void previewStarted() { for (StateListener listener : stateListeners) { listener.previewStarted(); } } @Override public void previewStopped() { for (StateListener listener : stateListeners) { listener.previewStopped(); } } @Override public void cameraError(Exception error) { for (StateListener listener : stateListeners) { listener.cameraError(error); } } }; private void calculateFrames() { if (containerSize == null || previewSize == null || displayConfiguration == null) { previewFramingRect = null; framingRect = null; surfaceRect = null; throw new IllegalStateException("containerSize or previewSize is not set yet"); } int previewWidth = previewSize.width; int previewHeight = previewSize.height; int width = containerSize.width; int height = containerSize.height; surfaceRect = displayConfiguration.scalePreview(previewSize); Rect container = new Rect(0, 0, width, height); framingRect = calculateFramingRect(container, surfaceRect); Rect frameInPreview = new Rect(framingRect); frameInPreview.offset(-surfaceRect.left, -surfaceRect.top); previewFramingRect = new Rect(frameInPreview.left * previewWidth / surfaceRect.width(), frameInPreview.top * previewHeight / surfaceRect.height(), frameInPreview.right * previewWidth / surfaceRect.width(), frameInPreview.bottom * previewHeight / surfaceRect.height()); if (previewFramingRect.width() <= 0 || previewFramingRect.height() <= 0) { previewFramingRect = null; framingRect = null; Log.w(TAG, "Preview frame is too small"); } else { fireState.previewSized(); } } /** * Call this on the main thread, while the preview is running. * * @param on true to turn on the torch */ public void setTorch(boolean on) { torchOn = on; if (cameraInstance != null) { cameraInstance.setTorch(on); } } private void containerSized(Size containerSize) { this.containerSize = containerSize; if (cameraInstance != null) { if (cameraInstance.getDisplayConfiguration() == null) { displayConfiguration = new DisplayConfiguration(getDisplayRotation(), containerSize); displayConfiguration.setPreviewScalingStrategy(getPreviewScalingStrategy()); cameraInstance.setDisplayConfiguration(displayConfiguration); cameraInstance.configureCamera(); if(torchOn) { cameraInstance.setTorch(torchOn); } } } } /** * Override the preview scaling strategy. * * @param previewScalingStrategy null for the default */ public void setPreviewScalingStrategy(PreviewScalingStrategy previewScalingStrategy) { this.previewScalingStrategy = previewScalingStrategy; } /** * Override this to specify a different preview scaling strategy. */ public PreviewScalingStrategy getPreviewScalingStrategy() { if(previewScalingStrategy != null) { return previewScalingStrategy; } // If we are using SurfaceTexture, it is safe to use centerCrop. // For SurfaceView, it's better to use fitCenter, otherwise the preview may overlap to // other views. if(textureView != null) { return new CenterCropStrategy(); } else { return new FitCenterStrategy(); } } private void previewSized(Size size) { this.previewSize = size; if (containerSize != null) { calculateFrames(); requestLayout(); startPreviewIfReady(); } } /** * Calculate transformation for the TextureView. * * An identity matrix would cause the preview to be scaled up/down to fill the TextureView. * * @param textureSize the size of the textureView * @param previewSize the camera preview resolution * @return the transform matrix for the TextureView */ protected Matrix calculateTextureTransform(Size textureSize, Size previewSize) { float ratioTexture = (float) textureSize.width / (float) textureSize.height; float ratioPreview = (float) previewSize.width / (float) previewSize.height; float scaleX; float scaleY; // We scale so that either width or height fits exactly in the TextureView, and the other // is bigger (cropped). if (ratioTexture < ratioPreview) { scaleX = ratioPreview / ratioTexture; scaleY = 1; } else { scaleX = 1; scaleY = ratioTexture / ratioPreview; } Matrix matrix = new Matrix(); matrix.setScale(scaleX, scaleY); // Center the preview float scaledWidth = textureSize.width * scaleX; float scaledHeight = textureSize.height * scaleY; float dx = (textureSize.width - scaledWidth) / 2; float dy = (textureSize.height - scaledHeight) / 2; // Perform the translation on the scaled preview matrix.postTranslate(dx, dy); return matrix; } private void startPreviewIfReady() { if (currentSurfaceSize != null && previewSize != null && surfaceRect != null) { if (surfaceView != null && currentSurfaceSize.equals(new Size(surfaceRect.width(), surfaceRect.height()))) { startCameraPreview(new CameraSurface(surfaceView.getHolder())); } else if(textureView != null && Build.VERSION.SDK_INT >= 14 && textureView.getSurfaceTexture() != null) { if(previewSize != null) { Matrix transform = calculateTextureTransform(new Size(textureView.getWidth(), textureView.getHeight()), previewSize); textureView.setTransform(transform); } startCameraPreview(new CameraSurface(textureView.getSurfaceTexture())); } else { // Surface is not the correct size yet } } } @SuppressLint("DrawAllocation") @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { containerSized(new Size(r - l, b - t)); if(surfaceView != null) { if (surfaceRect == null) { // Match the container, to reduce the risk of issues. The preview should never be drawn // while the surface has this size. surfaceView.layout(0, 0, getWidth(), getHeight()); } else { surfaceView.layout(surfaceRect.left, surfaceRect.top, surfaceRect.right, surfaceRect.bottom); } } else if(textureView != null && Build.VERSION.SDK_INT >= 14) { textureView.layout(0, 0, getWidth(), getHeight()); } } /** * The framing rectangle, relative to this view. Use to draw the rectangle. * * Will never be null while the preview is active. * * @return the framing rect, or null * @see #isPreviewActive() */ public Rect getFramingRect() { return framingRect; } /** * The framing rect, relative to the camera preview resolution. * * Will never be null while the preview is active. * * @return the preview rect, or null * @see #isPreviewActive() */ public Rect getPreviewFramingRect() { return previewFramingRect; } /** * @return the CameraSettings currently in use */ public CameraSettings getCameraSettings() { return cameraSettings; } /** * Set the CameraSettings. Use this to select a different camera, change exposure and torch * settings, and some other options. * * This has no effect if the camera is already open. * * @param cameraSettings the new settings */ public void setCameraSettings(CameraSettings cameraSettings) { this.cameraSettings = cameraSettings; } /** * Start the camera preview and decoding. Typically this should be called from the Activity's * onResume() method. * * Call from UI thread only. */ public void resume() { // This must be safe to call multiple times Util.validateMainThread(); Log.d(TAG, "resume()"); // initCamera() does nothing if called twice, but does log a warning initCamera(); if (currentSurfaceSize != null) { // The activity was paused but not stopped, so the surface still exists. Therefore // surfaceCreated() won't be called, so init the camera here. startPreviewIfReady(); } else if(surfaceView != null) { // Install the callback and wait for surfaceCreated() to init the camera. surfaceView.getHolder().addCallback(surfaceCallback); } else if(textureView != null && Build.VERSION.SDK_INT >= 14) { textureView.setSurfaceTextureListener(surfaceTextureListener()); } // To trigger surfaceSized again requestLayout(); rotationListener.listen(getContext(), rotationCallback); } /** * Pause scanning and the camera preview. Typically this should be called from the Activity's * onPause() method. * * Call from UI thread only. */ public void pause() { // This must be safe to call multiple times. Util.validateMainThread(); Log.d(TAG, "pause()"); openedOrientation = -1; if (cameraInstance != null) { cameraInstance.close(); cameraInstance = null; previewActive = false; } if (currentSurfaceSize == null && surfaceView != null) { SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.removeCallback(surfaceCallback); } if(currentSurfaceSize == null && textureView != null && Build.VERSION.SDK_INT >= 14) { textureView.setSurfaceTextureListener(null); } this.containerSize = null; this.previewSize = null; this.previewFramingRect = null; rotationListener.stop(); fireState.previewStopped(); } public Size getFramingRectSize() { return framingRectSize; } /** * Set an exact size for the framing rectangle. It will be centered in the view. * * @param framingRectSize the size */ public void setFramingRectSize(Size framingRectSize) { this.framingRectSize = framingRectSize; } public double getMarginFraction() { return marginFraction; } /** * The the fraction of the width/height of view to be used as a margin for the framing rect. * This is ignored if framingRectSize is specified. * * @param marginFraction the fraction */ public void setMarginFraction(double marginFraction) { if(marginFraction >= 0.5d) { throw new IllegalArgumentException("The margin fraction must be less than 0.5"); } this.marginFraction = marginFraction; } public boolean isUseTextureView() { return useTextureView; } /** * Set to true to use TextureView instead of SurfaceView. * * Will only have an effect on API >= 14. * * @param useTextureView true to use TextureView. */ public void setUseTextureView(boolean useTextureView) { this.useTextureView = useTextureView; } /** * Considered active if between resume() and pause(). * * @return true if active */ protected boolean isActive() { return cameraInstance != null; } private int getDisplayRotation() { return windowManager.getDefaultDisplay().getRotation(); } private void initCamera() { if (cameraInstance != null) { Log.w(TAG, "initCamera called twice"); return; } cameraInstance = createCameraInstance(); cameraInstance.setReadyHandler(stateHandler); cameraInstance.open(); // Keep track of the orientation we opened at, so that we don't reopen the camera if we // don't need to. openedOrientation = getDisplayRotation(); } /** * Create a new CameraInstance. * * Override to use a custom CameraInstance. * * @return a new CameraInstance */ protected CameraInstance createCameraInstance() { CameraInstance cameraInstance = new CameraInstance(getContext()); cameraInstance.setCameraSettings(cameraSettings); return cameraInstance; } private void startCameraPreview(CameraSurface surface) { if (!previewActive && cameraInstance != null) { Log.i(TAG, "Starting preview"); cameraInstance.setSurface(surface); cameraInstance.startPreview(); previewActive = true; previewStarted(); fireState.previewStarted(); } } /** * Called when the preview is started. Override this to start decoding work. */ protected void previewStarted() { } /** * Get the current CameraInstance. This may be null, and may change when * pausing / resuming the preview. * * While the preview is active, getCameraInstance() will never be null. * * @return the current CameraInstance * @see #isPreviewActive() */ public CameraInstance getCameraInstance() { return cameraInstance; } /** * The preview typically starts being active a while after calling resume(), and stops * when calling pause(). * * @return true if the preview is active */ public boolean isPreviewActive() { return previewActive; } /** * Calculate framing rectangle, relative to the preview frame. * * Note that the SurfaceView may be larger than the container. * * Override this for more control over the framing rect calculations. * * @param container this container, with left = top = 0 * @param surface the SurfaceView, relative to this container * @return the framing rect, relative to this container */ protected Rect calculateFramingRect(Rect container, Rect surface) { // intersection is the part of the container that is used for the preview Rect intersection = new Rect(container); boolean intersects = intersection.intersect(surface); if(framingRectSize != null) { // Specific size is specified. Make sure it's not larger than the container or surface. int horizontalMargin = Math.max(0, (intersection.width() - framingRectSize.width) / 2); int verticalMargin = Math.max(0, (intersection.height() - framingRectSize.height) / 2); intersection.inset(horizontalMargin, verticalMargin); return intersection; } // margin as 10% (default) of the smaller of width, height int margin = (int)Math.min(intersection.width() * marginFraction, intersection.height() * marginFraction); intersection.inset(margin, margin); if (intersection.height() > intersection.width()) { // We don't want a frame that is taller than wide. intersection.inset(0, (intersection.height() - intersection.width()) / 2); } return intersection; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); Bundle myState = new Bundle(); myState.putParcelable("super", superState); myState.putBoolean("torch", torchOn); return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if(!(state instanceof Bundle)) { super.onRestoreInstanceState(state); return; } Bundle myState = (Bundle)state; Parcelable superState = myState.getParcelable("super"); super.onRestoreInstanceState(superState); boolean torch = myState.getBoolean("torch"); setTorch(torch); } }
package plugins; import net.xeoh.plugins.base.Plugin; import java.io.File; import java.io.IOException; /** * Interface which <b>must</b> be implemented by all Corpoplugins. * The framework uses this interface to interface to interact with Corpoplugins. * * @author Fati CHEN * @version 1.0.0 */ @Pluginspecs( name = "Plugin", version = "1.0.0", description = "Interface, every plugin should implement it", author = "Fati CHEN", dependencies = "none", extensions = "none") public interface Corpoplugins extends Plugin { File file_in = null; File file_out = null; /** * Loading the selected file in the plugin and sets the output file * (security measures) * * @param file_in File to load */ public void Load(File file_in, File file_out); /** * Process the text extraction to file_out with options if necessary. * The options must be filtered by the Corpoplugins * * @param options eventuals options of the plugin */ public void processExtraction(String[] options) throws IOException; void setFileIn(File file_in); void setFileOut(File file_out); @Override public String toString(); }
package org.approvaltests; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.approvaltests.core.ApprovalFailureReporter; import org.approvaltests.reporters.DiffReporter; import org.approvaltests.reporters.FileLauncherReporter; import org.approvaltests.reporters.ImageReporter; import org.approvaltests.reporters.MultiReporter; import org.approvaltests.reporters.QuietReporter; import org.approvaltests.reporters.UseReporter; import com.spun.util.ClassUtils; public class ReporterFactory { private static HashMap<String, Class<? extends ApprovalFailureReporter>> reporters = new HashMap<String, Class<? extends ApprovalFailureReporter>>(); public static class FileTypes { public static final String Text = "txt"; public static final String Html = "html"; public static final String Excel = "csv"; public static final String File = "file"; public static final String Image = "png"; private static final String Default = "default"; } static { setupReporters(); } public static ApprovalFailureReporter get(String string) { ApprovalFailureReporter returned = getFromAnnotation(); returned = tryFor(returned, reporters.get(string)); returned = tryFor(returned, reporters.get(FileTypes.Default)); return returned; } public static ApprovalFailureReporter getFromAnnotation() { UseReporter reporter = getAnnotationFromStackTrace(UseReporter.class); return reporter == null ? null : getReporter(reporter); } private static ApprovalFailureReporter getReporter(UseReporter reporter) { Class<? extends ApprovalFailureReporter>[] classes = reporter.value(); List<ApprovalFailureReporter> reporters = new ArrayList<ApprovalFailureReporter>(); for (Class<? extends ApprovalFailureReporter> clazz : classes) { ApprovalFailureReporter instance = ClassUtils.create(clazz); reporters.add(instance); } return reporters.size() == 1 ? reporters.get(0) : new MultiReporter(reporters); } private static <T extends Annotation> T getAnnotationFromStackTrace(Class<T> annotationClass) { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); for (StackTraceElement stack : trace) { Method method = null; Class<?> clazz = null; try { String methodName = stack.getMethodName(); clazz = Class.forName(stack.getClassName()); method = clazz.getMethod(methodName, (Class<?>[]) null); } catch (Exception e) { //ignore } T annotation = null; if (method != null) { annotation = method.getAnnotation(annotationClass); } if (annotation != null) { return annotation; } if (clazz != null) { annotation = clazz.getAnnotation(annotationClass); } if (annotation != null) { return annotation; } } return null; } private static ApprovalFailureReporter tryFor(ApprovalFailureReporter returned, Class<? extends ApprovalFailureReporter> trying) { if (returned == null && trying != null) { return ClassUtils.create(trying); } return returned; } private static void setupReporters() { reporters.put(FileTypes.Text, DiffReporter.class); reporters.put(FileTypes.Html, DiffReporter.class); reporters.put(FileTypes.Excel, FileLauncherReporter.class); reporters.put(FileTypes.File, FileLauncherReporter.class); reporters.put(FileTypes.Image, ImageReporter.class); reporters.put(FileTypes.Default, QuietReporter.class); } public static void clearAllReportersExceptDefault() { Class all = reporters.get(FileTypes.Default); reporters.clear(); reporters.put(FileTypes.Default, all); } }
package net.ldvsoft.warofviruses; import java.security.SecureRandom; public class Game { private long id; private Player crossPlayer, zeroPlayer; private OnGameFinishedListener onGameFinishedListener = null; private GameLogic gameLogic; public interface OnGameFinishedListener { void onGameFinished(); } public static Game deserializeGame(long id, Player crossPlayer, Player zeroPlayer, GameLogic gameLogic) { Game game = new Game(); game.id = id; game.crossPlayer = crossPlayer; game.zeroPlayer = zeroPlayer; game.gameLogic = gameLogic; game.crossPlayer.setGame(game); game.zeroPlayer.setGame(game); return game; } public boolean isFinished() { return gameLogic.isFinished(); } public Player getZeroPlayer() { return zeroPlayer; } public Player getCrossPlayer() { return crossPlayer; } public long getGameId() { return id; } //returns COPY of gameLogic instance to prevent corrupting it public GameLogic getGameLogic() { return new GameLogic(gameLogic); } public void startNewGame(Player cross, Player zero) { id = new SecureRandom().nextLong(); crossPlayer = cross; zeroPlayer = zero; gameLogic = new GameLogic(); gameLogic.newGame(); crossPlayer.setGame(this); zeroPlayer.setGame(this); } public Player getCurrentPlayer() { switch (gameLogic.getCurrentPlayerFigure()) { case CROSS: return crossPlayer; case ZERO: return zeroPlayer; default: return null; } } private void notifyPlayer() { Player currentPlayer = getCurrentPlayer(); if (currentPlayer != null) { currentPlayer.makeTurn(); } } public void setOnGameFinishedListener(OnGameFinishedListener onGameFinishedListener) { this.onGameFinishedListener = onGameFinishedListener; } public boolean giveUp(Player sender) { if (!sender.equals(getCurrentPlayer())) { return false; } boolean result = gameLogic.giveUp(); if (result) { crossPlayer.onGameStateChanged(gameLogic.getEventHistory().get(gameLogic.getEventHistory().size() - 1)); zeroPlayer.onGameStateChanged(gameLogic.getEventHistory().get(gameLogic.getEventHistory().size() - 1)); } return result; } public boolean skipTurn(Player sender) { if (!sender.equals(getCurrentPlayer())) { return false; } GameLogic.PlayerFigure oldPlayer = gameLogic.getCurrentPlayerFigure(); boolean result = gameLogic.skipTurn(); if (result) { GameLogic.PlayerFigure currentPlayer = gameLogic.getCurrentPlayerFigure(); if (!oldPlayer.equals(currentPlayer)) { notifyPlayer(); } crossPlayer.onGameStateChanged(gameLogic.getEventHistory().get(gameLogic.getEventHistory().size() - 1)); zeroPlayer.onGameStateChanged(gameLogic.getEventHistory().get(gameLogic.getEventHistory().size() - 1)); } return result; } public boolean doTurn(Player sender, int x, int y) { if (!sender.equals(getCurrentPlayer())) { return false; } GameLogic.PlayerFigure oldPlayer = gameLogic.getCurrentPlayerFigure(); boolean result = gameLogic.doTurn(x, y); if (result) { GameLogic.PlayerFigure currentPlayer = gameLogic.getCurrentPlayerFigure(); if (!oldPlayer.equals(currentPlayer)) { notifyPlayer(); } crossPlayer.onGameStateChanged(gameLogic.getEventHistory().get(gameLogic.getEventHistory().size() - 1)); zeroPlayer.onGameStateChanged(gameLogic.getEventHistory().get(gameLogic.getEventHistory().size() - 1)); } return result; } }
package lucee.runtime.tag; import java.util.ArrayList; import java.util.TimeZone; import lucee.commons.date.TimeZoneUtil; import lucee.commons.lang.ClassException; import lucee.commons.lang.StringUtil; import lucee.runtime.PageContext; import lucee.runtime.PageContextImpl; import lucee.runtime.PageSource; import lucee.runtime.cache.tag.CacheHandler; import lucee.runtime.cache.tag.CacheHandlerFactory; import lucee.runtime.cache.tag.CacheItem; import lucee.runtime.cache.tag.query.QueryCacheItem; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.ConfigWebImpl; import lucee.runtime.config.ConfigWebUtil; import lucee.runtime.config.Constants; import lucee.runtime.db.DataSource; import lucee.runtime.db.DatasourceConnection; import lucee.runtime.db.DatasourceManagerImpl; import lucee.runtime.db.HSQLDBHandler; import lucee.runtime.db.SQL; import lucee.runtime.db.SQLImpl; import lucee.runtime.db.SQLItem; import lucee.runtime.debug.DebuggerPro; import lucee.runtime.debug.DebuggerUtil; import lucee.runtime.exp.ApplicationException; import lucee.runtime.exp.DatabaseException; import lucee.runtime.exp.ExpressionException; import lucee.runtime.exp.PageException; import lucee.runtime.ext.tag.BodyTagTryCatchFinallyImpl; import lucee.runtime.listener.AppListenerUtil; import lucee.runtime.listener.ApplicationContextPro; import lucee.runtime.op.Caster; import lucee.runtime.op.Decision; import lucee.runtime.orm.ORMSession; import lucee.runtime.orm.ORMUtil; import lucee.runtime.tag.util.DeprecatedUtil; import lucee.runtime.tag.util.QueryParamConverter; import lucee.runtime.type.Array; import lucee.runtime.type.ArrayImpl; import lucee.runtime.type.Collection; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.QueryColumn; import lucee.runtime.type.QueryImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.dt.DateTime; import lucee.runtime.type.dt.DateTimeImpl; import lucee.runtime.type.dt.TimeSpan; import lucee.runtime.type.query.SimpleQuery; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; /** * Passes SQL statements to a data source. Not limited to queries. **/ public final class Query extends BodyTagTryCatchFinallyImpl { private static final Collection.Key SQL_PARAMETERS = KeyImpl.intern("sqlparameters"); private static final Collection.Key CFQUERY = KeyImpl.intern("cfquery"); private static final Collection.Key GENERATEDKEY = KeyImpl.intern("generatedKey"); private static final Collection.Key MAX_RESULTS = KeyImpl.intern("maxResults"); private static final Collection.Key TIMEOUT = KeyConstants._timeout; private static final int RETURN_TYPE_QUERY = 1; private static final int RETURN_TYPE_ARRAY_OF_ENTITY = 2; /** If specified, password overrides the password value specified in the data source setup. */ private String password; /** The name of the data source from which this query should retrieve data. */ private DataSource datasource=null; /** The maximum number of milliseconds for the query to execute before returning an error ** indicating that the query has timed-out. This attribute is not supported by most ODBC drivers. ** timeout is supported by the SQL Server 6.x or above driver. The minimum and maximum allowable values ** vary, depending on the driver. */ private int timeout=-1; /** This is the age of which the query data can be */ private Object cachedWithin; /** Specifies the maximum number of rows to fetch at a time from the server. The range is 1, ** default to 100. This parameter applies to ORACLE native database drivers and to ODBC drivers. ** Certain ODBC drivers may dynamically reduce the block factor at runtime. */ private int blockfactor=-1; /** The database driver type. */ private String dbtype; /** Used for debugging queries. Specifying this attribute causes the SQL statement submitted to the ** data source and the number of records returned from the query to be returned. */ private boolean debug=true; /* This is specific to JTags, and allows you to give the cache a specific name */ //private String cachename; /** Specifies the maximum number of rows to return in the record set. */ private int maxrows=-1; /** If specified, username overrides the username value specified in the data source setup. */ private String username; private DateTime cachedAfter; /** The name query. Must begin with a letter and may consist of letters, numbers, and the underscore ** character, spaces are not allowed. The query name is used later in the page to reference the query's ** record set. */ private String name; private String result=null; //private static HSQLDBHandler hsql=new HSQLDBHandler(); private boolean orgPSQ; private boolean hasChangedPSQ; ArrayList<SQLItem> items=new ArrayList<SQLItem>(); private boolean clearCache; private boolean unique; private Struct ormoptions; private int returntype=RETURN_TYPE_ARRAY_OF_ENTITY; private TimeZone timezone; private TimeZone tmpTZ; private boolean lazy; private Object params; private int nestingLevel=1; @Override public void release() { super.release(); items.clear(); password=null; datasource=null; timeout=-1; clearCache=false; cachedWithin=null; cachedAfter=null; //cachename=""; blockfactor=-1; dbtype=null; debug=true; maxrows=-1; username=null; name=""; result=null; orgPSQ=false; hasChangedPSQ=false; unique=false; ormoptions=null; returntype=RETURN_TYPE_ARRAY_OF_ENTITY; timezone=null; tmpTZ=null; lazy=false; params=null; nestingLevel=1; } public void setOrmoptions(Struct ormoptions) { this.ormoptions = ormoptions; } public void setReturntype(String strReturntype) throws ApplicationException { if(StringUtil.isEmpty(strReturntype)) return; strReturntype=strReturntype.toLowerCase().trim(); if(strReturntype.equals("query")) returntype=RETURN_TYPE_QUERY; //mail.setType(lucee.runtime.mail.Mail.TYPE_TEXT); else if(strReturntype.equals("array_of_entity") || strReturntype.equals("array-of-entity") || strReturntype.equals("array_of_entities") || strReturntype.equals("array-of-entities") || strReturntype.equals("arrayofentities") || strReturntype.equals("arrayofentities")) returntype=RETURN_TYPE_ARRAY_OF_ENTITY; //mail.setType(lucee.runtime.mail.Mail.TYPE_TEXT); else throw new ApplicationException("attribute returntype of tag query has an invalid value","valid values are [query,array-of-entity] but value is now ["+strReturntype+"]"); } public void setUnique(boolean unique) { this.unique = unique; } /** * @param result the result to set */ public void setResult(String result) { this.result = result; } /** * @param psq set preserver single quote */ public void setPsq(boolean psq) { orgPSQ=pageContext.getPsq(); if(orgPSQ!=psq){ pageContext.setPsq(psq); hasChangedPSQ=true; } } /** set the value password * If specified, password overrides the password value specified in the data source setup. * @param password value to set **/ public void setPassword(String password) { this.password=password; } /** set the value datasource * The name of the data source from which this query should retrieve data. * @param datasource value to set * @throws ClassException **/ public void setDatasource(Object datasource) throws PageException, ClassException { if (Decision.isStruct(datasource)) { this.datasource=AppListenerUtil.toDataSource("__temp__", Caster.toStruct(datasource)); } else if (Decision.isString(datasource)) { this.datasource=((PageContextImpl)pageContext).getDataSource(Caster.toString(datasource)); } else { throw new ApplicationException("attribute [datasource] must be datasource name or a datasource definition(struct)"); } } /** set the value timeout * The maximum number of milliseconds for the query to execute before returning an error * indicating that the query has timed-out. This attribute is not supported by most ODBC drivers. * timeout is supported by the SQL Server 6.x or above driver. The minimum and maximum allowable values * vary, depending on the driver. * @param timeout value to set **/ public void setTimeout(double timeout) { this.timeout=(int)timeout; } /** set the value cachedafter * This is the age of which the query data can be * @param cachedafter value to set **/ public void setCachedafter(DateTime cachedafter) { //lucee.print.ln("cachedafter:"+cachedafter); this.cachedAfter=cachedafter; } /** set the value cachename * This is specific to JTags, and allows you to give the cache a specific name * @param cachename value to set **/ public void setCachename(String cachename) { DeprecatedUtil.tagAttribute(pageContext,"query", "cachename"); //this.cachename=cachename; } /** set the value cachedwithin * * @param cachedwithin value to set **/ public void setCachedwithin(TimeSpan cachedwithin) { if(cachedwithin.getMillis()>0) this.cachedWithin=cachedwithin; else clearCache=true; } public void setCachedwithin(Object cachedwithin) throws PageException { if(cachedwithin instanceof String) { String str=((String)cachedwithin).trim(); if("request".equalsIgnoreCase(str)) { this.cachedWithin="request"; return; } } setCachedwithin(Caster.toTimespan(cachedwithin)); } public void setLazy(boolean lazy) { this.lazy=lazy; } /** set the value providerdsn * Data source name for the COM provider, OLE-DB only. * @param providerdsn value to set * @throws ApplicationException **/ public void setProviderdsn(String providerdsn) throws ApplicationException { DeprecatedUtil.tagAttribute(pageContext,"Query", "providerdsn"); } /** set the value connectstring * @param connectstring value to set * @throws ApplicationException **/ public void setConnectstring(String connectstring) throws ApplicationException { DeprecatedUtil.tagAttribute(pageContext,"Query", "connectstring"); } public void setTimezone(String timezone) throws ExpressionException { this.timezone=TimeZoneUtil.toTimeZone(timezone); } /** set the value blockfactor * Specifies the maximum number of rows to fetch at a time from the server. The range is 1, * default to 100. This parameter applies to ORACLE native database drivers and to ODBC drivers. * Certain ODBC drivers may dynamically reduce the block factor at runtime. * @param blockfactor value to set **/ public void setBlockfactor(double blockfactor) { this.blockfactor=(int) blockfactor; } /** set the value dbtype * The database driver type. * @param dbtype value to set **/ public void setDbtype(String dbtype) { this.dbtype=dbtype.toLowerCase(); } /** set the value debug * Used for debugging queries. Specifying this attribute causes the SQL statement submitted to the * data source and the number of records returned from the query to be returned. * @param debug value to set **/ public void setDebug(boolean debug) { this.debug=debug; } /** set the value dbname * The database name, Sybase System 11 driver and SQLOLEDB provider only. If specified, dbName * overrides the default database specified in the data source. * @param dbname value to set * @throws ApplicationException **/ public void setDbname(String dbname) { DeprecatedUtil.tagAttribute(pageContext,"Query", "dbname"); } /** set the value maxrows * Specifies the maximum number of rows to return in the record set. * @param maxrows value to set **/ public void setMaxrows(double maxrows) { this.maxrows=(int) maxrows; } /** set the value username * If specified, username overrides the username value specified in the data source setup. * @param username value to set **/ public void setUsername(String username) { if(!StringUtil.isEmpty(username)) this.username=username; } /** set the value provider * COM provider, OLE-DB only. * @param provider value to set * @throws ApplicationException **/ public void setProvider(String provider) { DeprecatedUtil.tagAttribute(pageContext,"Query", "provider"); } /** set the value dbserver * For native database drivers and the SQLOLEDB provider, specifies the name of the database server * computer. If specified, dbServer overrides the server specified in the data source. * @param dbserver value to set * @throws ApplicationException **/ public void setDbserver(String dbserver) { DeprecatedUtil.tagAttribute(pageContext,"Query", "dbserver"); } /** set the value name * The name query. Must begin with a letter and may consist of letters, numbers, and the underscore * character, spaces are not allowed. The query name is used later in the page to reference the query's * record set. * @param name value to set **/ public void setName(String name) { this.name=name; } public String getName() { return name==null? "query":name; } /** * @param item */ public void setParam(SQLItem item) { items.add(item); } public void setParams(Object params) { this.params=params; } public void setNestinglevel(double nestingLevel) { this.nestingLevel=(int)nestingLevel; } @Override public int doStartTag() throws PageException { // default datasource if(datasource==null && (dbtype==null || !dbtype.equals("query"))){ Object obj = ((ApplicationContextPro)pageContext.getApplicationContext()).getDefDataSource(); if(StringUtil.isEmpty(obj)) throw new ApplicationException( "attribute [datasource] is required, when attribute [dbtype] has not value [query] and no default datasource is defined", "you can define a default datasource as attribute [defaultdatasource] of the tag "+Constants.CFAPP_NAME+" or as data member of the "+Constants.APP_CFC+" (this.defaultdatasource=\"mydatasource\";)"); datasource=obj instanceof DataSource?(DataSource)obj:((PageContextImpl)pageContext).getDataSource(Caster.toString(obj)); } // timezone if(timezone!=null || (datasource!=null && (timezone=datasource.getTimeZone())!=null)) { tmpTZ=pageContext.getTimeZone(); pageContext.setTimeZone(timezone); } return EVAL_BODY_BUFFERED; } @Override public void doFinally() { if(tmpTZ!=null) { pageContext.setTimeZone(tmpTZ); } super.doFinally(); } @Override public int doEndTag() throws PageException { if(hasChangedPSQ)pageContext.setPsq(orgPSQ); String strSQL=bodyContent.getString(); // no SQL String defined if(strSQL.length()==0) throw new DatabaseException("no sql string defined, inside query tag",null,null,null); // cannot use attribute params and queryparam tag if(items.size()>0 && params!=null) throw new DatabaseException("you cannot use the attribute params and sub tags queryparam at the same time",null,null,null); // create SQL SQL sql; if(params!=null) { if(Decision.isArray(params)) sql=QueryParamConverter.convert(strSQL, Caster.toArray(params)); else if(Decision.isStruct(params)) sql=QueryParamConverter.convert(strSQL, Caster.toStruct(params)); else throw new DatabaseException("value of the attribute [params] has to be a struct or a array",null,null,null); } else sql=items.size()>0?new SQLImpl(strSQL,items.toArray(new SQLItem[items.size()])):new SQLImpl(strSQL); lucee.runtime.type.Query query=null; long exe=0; boolean hasCached=cachedWithin!=null || cachedAfter!=null; String cacheType=null; if(clearCache) { hasCached=false; String id = CacheHandlerFactory.createId(sql,datasource!=null?datasource.getName():null,username,password); CacheHandler ch = ConfigWebUtil.getCacheHandlerFactories(pageContext.getConfig()).query.getInstance(pageContext.getConfig(), CacheHandlerFactory.TYPE_TIMESPAN); ch.remove(pageContext, id); } else if(hasCached) { String id = CacheHandlerFactory.createId(sql,datasource!=null?datasource.getName():null,username,password); CacheHandler ch = ConfigWebUtil.getCacheHandlerFactories(pageContext.getConfig()).query.getInstance(pageContext.getConfig(), cachedWithin); if(ch!=null) { cacheType=ch.label(); CacheItem ci = ch.get(pageContext, id); if(ci instanceof QueryCacheItem) { QueryCacheItem ce = (QueryCacheItem) ci; if(ce.isCachedAfter(cachedAfter)) query= ce.query; } } } if(query==null) { if("query".equals(dbtype)) query=executeQoQ(sql); else if("orm".equals(dbtype) || "hql".equals(dbtype)) { long start=System.nanoTime(); Object obj = executeORM(sql,returntype,ormoptions); if(obj instanceof lucee.runtime.type.Query){ query=(lucee.runtime.type.Query) obj; } else { if(!StringUtil.isEmpty(name)) { pageContext.setVariable(name,obj); } if(result!=null){ Struct sct=new StructImpl(); sct.setEL(KeyConstants._cached, Boolean.FALSE); long time=System.nanoTime()-start; sct.setEL(KeyConstants._executionTime, Caster.toDouble(time/1000000)); sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(time)); sct.setEL(KeyConstants._SQL, sql.getSQLString()); if(Decision.isArray(obj)){ } else sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(1)); pageContext.setVariable(result, sct); } else setExecutionTime((System.nanoTime()-start)/1000000); return EVAL_PAGE; } } else query=executeDatasoure(sql,result!=null,pageContext.getTimeZone()); //query=(dbtype!=null && dbtype.equals("query"))?executeQoQ(sql):executeDatasoure(sql,result!=null); if(cachedWithin!=null) { DateTimeImpl cachedBefore = null; //if(cachedWithin!=null) String id = CacheHandlerFactory.createId(sql,datasource!=null?datasource.getName():null,username,password); CacheHandler ch = ConfigWebUtil.getCacheHandlerFactories(pageContext.getConfig()).query.getInstance(pageContext.getConfig(), cachedWithin); ch.set(pageContext, id,cachedWithin,new QueryCacheItem(query)); } exe=query.getExecutionTime(); } else { if(query instanceof QueryImpl) ((QueryImpl)query).setCacheType(cacheType); // FUTURE add method to interface else query.setCached(hasCached); } if(pageContext.getConfig().debug() && debug) { boolean logdb=((ConfigImpl)pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE); if(logdb){ boolean debugUsage=DebuggerUtil.debugQueryUsage(pageContext,query); PageSource source=null; if(nestingLevel>1) { PageContextImpl pci=(PageContextImpl) pageContext; int index=pci.getCurrentLevel()-(nestingLevel); if(index>0) source=pci.getPageSource(index); } if(source==null) source=pageContext.getCurrentPageSource(); ((DebuggerPro)pageContext.getDebugger()).addQuery(debugUsage?query:null,datasource!=null?datasource.getName():null,name,sql,query.getRecordcount(),source,exe); } } if(!query.isEmpty() && !StringUtil.isEmpty(name)) { pageContext.setVariable(name,query); } // Result if(result!=null) { Struct sct=new StructImpl(); sct.setEL(KeyConstants._cached, Caster.toBoolean(query.isCached())); if(!query.isEmpty())sct.setEL(KeyConstants._COLUMNLIST, ListUtil.arrayToList(query.getColumnNamesAsString(),",")); int rc=query.getRecordcount(); if(rc==0)rc=query.getUpdateCount(); sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(rc)); sct.setEL(KeyConstants._executionTime, Caster.toDouble(query.getExecutionTime()/1000000)); sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(query.getExecutionTime())); sct.setEL(KeyConstants._SQL, sql.getSQLString()); // GENERATED KEYS lucee.runtime.type.Query qi = Caster.toQuery(query,null); if(qi !=null){ lucee.runtime.type.Query qryKeys = qi.getGeneratedKeys(); if(qryKeys!=null){ StringBuilder generatedKey=new StringBuilder(),sb; Collection.Key[] columnNames = qryKeys.getColumnNames(); QueryColumn column; for(int c=0;c<columnNames.length;c++){ column = qryKeys.getColumn(columnNames[c]); sb=new StringBuilder(); int size=column.size(); for(int row=1;row<=size;row++) { if(row>1)sb.append(','); sb.append(Caster.toString(column.get(row,null))); } if(sb.length()>0){ sct.setEL(columnNames[c], sb.toString()); if(generatedKey.length()>0)generatedKey.append(','); generatedKey.append(sb); } } if(generatedKey.length()>0) sct.setEL(GENERATEDKEY, generatedKey.toString()); } } // sqlparameters SQLItem[] params = sql.getItems(); if(params!=null && params.length>0) { Array arr=new ArrayImpl(); sct.setEL(SQL_PARAMETERS, arr); for(int i=0;i<params.length;i++) { arr.append(params[i].getValue()); } } pageContext.setVariable(result, sct); } // cfquery.executiontime else { setExecutionTime(exe/1000000); } // listener ((ConfigWebImpl)pageContext.getConfig()).getActionMonitorCollector() .log(pageContext, "query", "Query", exe, query); return EVAL_PAGE; } private void setExecutionTime(long exe) { Struct sct=new StructImpl(); sct.setEL(KeyConstants._executionTime,new Double(exe)); pageContext.undefinedScope().setEL(CFQUERY,sct); } private Object executeORM(SQL sql, int returnType, Struct ormoptions) throws PageException { ORMSession session=ORMUtil.getSession(pageContext); String dsn = null; if (ormoptions!=null) dsn = Caster.toString(ormoptions.get(KeyConstants._datasource,null),null); if(StringUtil.isEmpty(dsn,true)) dsn=ORMUtil.getDefaultDataSource(pageContext).getName(); // params SQLItem[] _items = sql.getItems(); Array params=new ArrayImpl(); for(int i=0;i<_items.length;i++){ params.appendEL(_items[i]); } // query options if(maxrows!=-1 && !ormoptions.containsKey(MAX_RESULTS)) ormoptions.setEL(MAX_RESULTS, new Double(maxrows)); if(timeout!=-1 && !ormoptions.containsKey(TIMEOUT)) ormoptions.setEL(TIMEOUT, new Double(timeout)); /* MUST offset: Specifies the start index of the resultset from where it has to start the retrieval. cacheable: Whether the result of this query is to be cached in the secondary cache. Default is false. cachename: Name of the cache in secondary cache. */ Object res = session.executeQuery(pageContext,dsn,sql.getSQLString(),params,unique,ormoptions); if(returnType==RETURN_TYPE_ARRAY_OF_ENTITY) return res; return session.toQuery(pageContext, res, null); } public static Object _call(PageContext pc,String hql, Object params, boolean unique, Struct queryOptions) throws PageException { ORMSession session=ORMUtil.getSession(pc); String dsn = Caster.toString(queryOptions.get(KeyConstants._datasource,null),null); if(StringUtil.isEmpty(dsn,true)) dsn=ORMUtil.getDefaultDataSource(pc).getName(); if(Decision.isCastableToArray(params)) return session.executeQuery(pc,dsn,hql,Caster.toArray(params),unique,queryOptions); else if(Decision.isCastableToStruct(params)) return session.executeQuery(pc,dsn,hql,Caster.toStruct(params),unique,queryOptions); else return session.executeQuery(pc,dsn,hql,(Array)params,unique,queryOptions); } private lucee.runtime.type.Query executeQoQ(SQL sql) throws PageException { try { return new HSQLDBHandler().execute(pageContext,sql,maxrows,blockfactor,timeout); } catch (Exception e) { throw Caster.toPageException(e); } } private lucee.runtime.type.Query executeDatasoure(SQL sql,boolean createUpdateData,TimeZone tz) throws PageException { DatasourceManagerImpl manager = (DatasourceManagerImpl) pageContext.getDataSourceManager(); DatasourceConnection dc=manager.getConnection(pageContext,datasource, username, password); try { if(lazy && !createUpdateData && cachedWithin==null && cachedAfter==null && result==null) return new SimpleQuery(pageContext,dc,sql,maxrows,blockfactor,timeout,getName(),pageContext.getCurrentPageSource().getDisplayPath(),tz); return new QueryImpl(pageContext,dc,sql,maxrows,blockfactor,timeout,getName(),pageContext.getCurrentPageSource().getDisplayPath(),createUpdateData,true); } finally { manager.releaseConnection(pageContext,dc); } } @Override public void doInitBody() { } @Override public int doAfterBody() { return SKIP_BODY; } }
package org.sana.core; import java.io.File; import org.sana.api.IObservation; /** * An instance of data collected about a Subject by executing an Instruction. * * @author Sana Development * */ public class Observation extends Model implements IObservation { private String node; private Encounter encounter; private Concept concept; private String value_complex; private String valueText; private boolean isComplex = false; /** Default Constructor */ public Observation(){ super(); } /** * Instantiates a new Observation with a specified id. * * @param uuid The UUID of the instance */ public Observation(String uuid){ super(); this.uuid = uuid; } /* (non-Javadoc) * @see org.sana.core.IObservation#getId() */ @Override public String getId() { return node; } /** * @param id the id to set */ public void setId(String id) { node = id; } /* (non-Javadoc) * @see org.sana.core.IObservation#getEncounter() */ @Override public Encounter getEncounter() { return encounter; } /** * Sets the uuid of the encounter. * * @param encounterUUID the uuid to set */ public void setEncounter(String encounterUUID) { encounter = new Encounter(); encounter.setUuid(encounterUUID); } /** * Sets the encounter uuid stored in this object from the uuid of an * {@link org.sana.core.Encounter} instance; * @param encounter */ public void setEncounter(Encounter encounter) { this.encounter = encounter; } /* (non-Javadoc) * @see org.sana.core.IObservation#getConcept() */ @Override public Concept getConcept() { return concept; } /** * @param conceptName the concept to set */ public void setConcept(String conceptName) { concept = new Concept(); concept.setName(conceptName); setIsComplex(concept); } /** * Sets the value of whether this observation's stored value is complex * based on the value of {@link org.sana.core.Concept#isComplex()} and the * uuid of the concept this observation represents. * * @param concept */ public void setConcept(Concept concept){ this.concept = concept; setIsComplex(concept); } /** * Convenience wrapper which returns either a File or String depending on * this object's Concept is complex. * * @return the value */ public Object getValue() { if(getIsComplex()){ return getValue_complex(); } else { return getValue_text(); } } /** * This sets the internal value stored as either a File or String depending * on whether the result of {@link Observation#getIsComplex()} is true. <br/> * <br/> * Note: if {@link Observation#getIsComplex()} is <code>true</code> and a * String instance is passed, it will be interpreted as a path. * * @param value the value to set as either a File or String */ public void setValue(Object value) { if(getIsComplex()){ setValue_text(null); if(value instanceof String){ setValue_complex(value.toString()); } else if(value instanceof File){ setValue_complex(((File) value).getAbsolutePath()); } } else { setValue_complex(null); setValue_text(String.valueOf(value)); } } /* (non-Javadoc) * @see org.sana.core.IObservation#getValue_complex() */ @Override public String getValue_complex() { return value_complex; } /** * @param valueComplex the value_complex to set */ public void setValue_complex(String valueComplex) { this.value_complex = valueComplex; } /* (non-Javadoc) * @see org.sana.core.IObservation#getValue_text() */ @Override public String getValue_text() { return valueText; } /** * @param valueText the valueText to set */ public void setValue_text(String valueText) { this.valueText = valueText; } /** * Returns whether this instance's stored valued represents a binary or text * blob. * * @return */ public boolean getIsComplex(){ return isComplex; } public void setIsComplex(Concept concept){ isComplex = concept.isComplex(); } }
package ifc.connection; import java.io.PrintWriter; import lib.MultiMethodTest; import lib.StatusException; import com.sun.star.connection.XAcceptor; import com.sun.star.connection.XConnection; import com.sun.star.connection.XConnector; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Tests methods of <code>XAcceptor</code> interface. <p> * Required relations : * <ul> * <li> <code>'XAcceptor.connectStr'</code> : String variable. Has * the following format : * <code>'socket,host=<SOHost>,port=<UniquePort>' where <SOHost> is * the host where StarOffice is started. This string must be passed * as parameter to <code>accept()</code> method. </li> * <ul> <p> * This test <b>can not</b> be run in multiply threads. */ public class _XAcceptor extends MultiMethodTest { protected PrintWriter log_ ; /** * Calls <code>accept()</code> method in a separate thread. * Then stores exception thrown by call if it occured, or * return value. */ protected class AcceptorThread extends Thread { /** * If exception occured during method call it is * stored in this field. */ public Exception ex = null ; private XAcceptor acc = null ; /** * If method call returns some value it stores in this field. */ public XConnection acceptedCall = null ; /** * Creates object which can call <code>accept</code> method * of the Acceptor object specified. */ public AcceptorThread(XAcceptor acc) { this.acc = acc ; } /** * Call <code>accept()</code> method. */ public void run() { try { acceptedCall = acc.accept(connectString) ; } catch (com.sun.star.lang.IllegalArgumentException e) { ex = e ; } catch (com.sun.star.connection.ConnectionSetupException e) { ex = e ; } catch (com.sun.star.connection.AlreadyAcceptingException e) { ex = e ; } } } public XAcceptor oObj = null; protected String connectString = null ; /** * Retrieves object relation. */ public void before() throws StatusException { connectString = (String) tEnv.getObjRelation("XAcceptor.connectStr") ; log_ = log ; if (connectString == null) throw new StatusException("No object relation found", new NullPointerException()) ; } /** * First part : Thread with acceptor created, and it starts listening. * The main thread tries to connect to acceptor. Acception thread must * return and valid connection must be returned by Acceptor. <p> * * Second part : Trying to create second acceptor which listen on * the same port. Calling <code>accept()</code> method of the second * Acceptor must rise appropriate exception. <p> * * Has OK status if both test parts executed properly. */ public void _accept() { boolean result = true ; AcceptorThread acception = null, dupAcception = null ; XAcceptor dupAcceptor = null ; XConnector xConnector = null ; // creating services requierd try { Object oConnector = ((XMultiServiceFactory)tParam.getMSF()). createInstance("com.sun.star.connection.Connector") ; xConnector = (XConnector) UnoRuntime.queryInterface (XConnector.class, oConnector) ; XInterface acceptor = (XInterface) ((XMultiServiceFactory) tParam.getMSF()).createInstance ("com.sun.star.connection.Acceptor") ; dupAcceptor = (XAcceptor) UnoRuntime.queryInterface (XAcceptor.class, acceptor) ; } catch (com.sun.star.uno.Exception e) { e.printStackTrace(log) ; throw new StatusException("Can't create service", e) ; } // Testing connection to the acceptor try { acception = new AcceptorThread(oObj) ; acception.start() ; try { Thread.sleep(500); } catch (java.lang.InterruptedException e) {} XConnection con = xConnector.connect(connectString) ; if (con == null) log.println("Connector returned : null") ; else log.println("Connector returned : " + con.getDescription()) ; try { acception.join(5 * 1000) ; } catch(InterruptedException e) {} if (acception.isAlive()) { result = false ; log.println("Method call haven't returned") ; if (acception.acceptedCall == null) log.println("Acceptor returned : null") ; else log.println("Acceptor returned : " + acception.acceptedCall.getDescription()) ; } else { if (acception.ex != null) { log.println("Exception occured in accept() thread :") ; acception.ex.printStackTrace(log) ; } if (acception.acceptedCall == null) log.println("Method returned : null") ; else log.println("Method returned : " + acception.acceptedCall.getDescription()) ; result &= acception.acceptedCall != null ; } } catch (com.sun.star.connection.ConnectionSetupException e) { e.printStackTrace(log) ; result = false ; } catch (com.sun.star.connection.NoConnectException e) { e.printStackTrace(log) ; result = false ; } finally { oObj.stopAccepting(); if (acception.isAlive()) { acception.interrupt(); } } // duplicate acceptor test // creating the additional acceptor which listens // on the same port log.println("___ Testing for accepting on the same port ...") ; try { dupAcception = new AcceptorThread(dupAcceptor) ; dupAcception.start() ; try { dupAcception.join(1 * 1000) ; } catch(InterruptedException e) {} if (dupAcception.isAlive()) { log.println("Duplicate acceptor is listening ...") ; // now trying to accept on the same port as additional // acceptor acception = new AcceptorThread(oObj) ; acception.start() ; try { acception.join(3 * 1000) ; } catch(InterruptedException e) {} if (acception.isAlive()) { oObj.stopAccepting() ; acception.interrupt() ; log.println("Acceptor with the same port must cause"+ " an error but didn't") ; result = false ; } else { log.println("Accepted call = " + acception.acceptedCall) ; if (acception.ex == null) { //result = false ; log.println("No exception was thrown when trying"+ " to listen on the same port") ; } else { if (acception.ex instanceof com.sun.star.connection.AlreadyAcceptingException || acception.ex instanceof com.sun.star.connection.ConnectionSetupException) { log.println("Rigth exception was thrown when trying"+ " to listen on the same port") ; } else { result = false ; log.println("Wrong exception was thrown when trying"+ " to listen on the same port :") ; acception.ex.printStackTrace(log) ; } } } } } finally { dupAcceptor.stopAccepting() ; if (dupAcception.isAlive()) { dupAcception.interrupt() ; } } tRes.tested("accept()", result) ; } /** * Starts thread with Acceptor and then calls <code>stopListening</code> * method. <p> * Has OK status if <code>accept</code> method successfully returns and * rises no exceptions. */ public void _stopAccepting() { boolean result = true ; AcceptorThread acception = new AcceptorThread(oObj) ; acception.start() ; oObj.stopAccepting() ; try { acception.join(3 * 1000) ; } catch (InterruptedException e) {} if (acception.isAlive()) { acception.interrupt() ; result = false ; log.println("Method call haven't returned") ; } else { if (acception.ex != null) { log.println("Exception occured in accept() thread :") ; acception.ex.printStackTrace(log) ; result = false ; } else { result = true ; } if (acception.acceptedCall == null) log.println("accept() returned : null") ; else log.println("accept() returned : " + acception.acceptedCall.getDescription()) ; } tRes.tested("stopAccepting()", result) ; } }
package io.mangoo.core; import java.util.Map; import java.util.Objects; import io.mangoo.enums.Default; import io.mangoo.enums.Header; import io.mangoo.enums.Required; import io.undertow.util.HttpString; /** * * @author svenkubiak * */ public final class Server { private static Map<HttpString, String> headers = Map.of( Header.X_CONTENT_TYPE_OPTIONS.toHttpString(), Default.APPLICATION_HEADERS_XCONTENTTYPEOPTIONS.toString(), Header.X_FRAME_OPTIONS.toHttpString(), Default.APPLICATION_HEADERS_XFRAMEOPTIONS.toString(), Header.X_XSS_PPROTECTION.toHttpString(), Default.APPLICATION_HEADERS_XSSPROTECTION.toString(), Header.REFERER_POLICY.toHttpString(), Default.APPLICATION_HEADERS_REFERERPOLICY.toString(), Header.FEATURE_POLICY.toHttpString(), Default.APPLICATION_HEADERS_FEATUREPOLICY.toString(), Header.CONTENT_SECURITY_POLICY.toHttpString(), Default.APPLICATION_HEADERS_CONTENTSECURITYPOLICY.toString(), Header.SERVER.toHttpString(), Default.APPLICATION_HEADERS_SERVER.toString() ); private Server() { } public static Map<HttpString, String> headers() { return headers; } /** * Sets a custom header that is used globally on server responses * * @param name The name of the header * @param value The value of the header */ public static void header(Header name, String value) { Objects.requireNonNull(name, Required.NAME.toString()); headers.put(name.toHttpString(), value); } }
package comments.user; import static com.dyuproject.protostuffdb.EntityMetadata.ZERO_KEY; import static com.dyuproject.protostuffdb.SerializedValueUtil.asInt64; import static com.dyuproject.protostuffdb.SerializedValueUtil.readByteArrayOffsetWithTypeAsSize; import java.io.IOException; import java.util.Arrays; import com.dyuproject.protostuff.KeyBuilder; import com.dyuproject.protostuff.Pipe; import com.dyuproject.protostuff.RpcHeader; import com.dyuproject.protostuff.RpcResponse; import com.dyuproject.protostuffdb.Datastore; import com.dyuproject.protostuffdb.ProtostuffPipe; import com.dyuproject.protostuffdb.RangeV; import com.dyuproject.protostuffdb.WriteContext; /** * Comment ops. */ public final class CommentOps { private CommentOps() {} static byte[] append(byte[] data, int offset, int len, byte[] suffix) { byte[] buf = new byte[len+suffix.length]; System.arraycopy(data, offset, buf, 0, len); System.arraycopy(suffix, 0, buf, len, suffix.length); return buf; } static boolean validateAndProvide(Comment param, long now, Datastore store, WriteContext context, RpcResponse res) throws IOException { byte[] parentKey = param.parentKey; if (parentKey.length == 0 || Arrays.equals(parentKey, ZERO_KEY)) { param.parentKey = ZERO_KEY; param.provide(now, ZERO_KEY, 0); return true; } final byte[] parentValue = store.get(parentKey, Comment.EM, null, context); if (parentValue == null) return res.fail("Parent comment does not exist!"); if (param.postId.longValue() != asInt64(Comment.VO_POST_ID, parentValue)) return res.fail("Invalid post id."); int offset = readByteArrayOffsetWithTypeAsSize(Comment.FN_KEY_CHAIN, parentValue, context), size = context.type, depth = size / 9; if (depth > 127) return res.fail("The nested replies are too deep and have exceeded the limit."); param.provide(now, append(parentValue, offset, size, parentKey), depth); return true; } static boolean create(Comment req, Datastore store, RpcResponse res, Pipe.Schema<Comment.PList> resPipeSchema, RpcHeader header) throws IOException { final byte[] lastSeenKey = req.key, key = new byte[9]; final WriteContext context = res.context; final long now = context.ts(Comment.EM); if (!validateAndProvide(req, now, store, context, res)) return false; context.fillEntityKey(key, Comment.EM, now); store.insertWithKey(key, req, req.em(), null, context); req.key = key; if (req.parentKey != ZERO_KEY) { // user posted a reply final KeyBuilder kb = res.context.kb() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId); final byte[] keyChain = req.keyChain, startKey; if (lastSeenKey == null) { // visit starting at the first child startKey = new byte[keyChain.length + 1]; System.arraycopy(keyChain, 0, startKey, 0, keyChain.length); } else { startKey = new byte[keyChain.length + 9]; System.arraycopy(keyChain, 0, startKey, 0, keyChain.length); // visit starting the entry after the last seen one lastSeenKey[lastSeenKey.length - 1] |= 0x02; System.arraycopy(lastSeenKey, 0, startKey, keyChain.length, 9); } kb.$append(startKey).$push() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append(keyChain) .$append8(0xFF) .$push(); final ProtostuffPipe pipe = res.context.pipe.init( Comment.EM, Comment.getPipeSchema(), Comment.PList.FN_P, true); try { store.visitRange(false, -1, false, null, res.context, RangeV.RES_PV, res, kb.buf(), kb.offset(-1), kb.len(-1), kb.buf(), kb.offset(), kb.len()); } finally { pipe.clear(); } } else if (lastSeenKey != null) { // visit starting the entry after the last seen one lastSeenKey[lastSeenKey.length - 1] |= 0x02; KeyBuilder kb = res.context.kb() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append(ZERO_KEY) .$append(lastSeenKey) .$push() /*.begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$push()*/ .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append8(0xFF) .$push(); final ProtostuffPipe pipe = res.context.pipe.init( Comment.EM, Comment.getPipeSchema(), Comment.PList.FN_P, true); try { store.visitRange(false, -1, false, null/*kb.copy(-2)*/, res.context, RangeV.RES_PV, res, kb.buf(), kb.offset(-1), kb.len(-1), kb.buf(), kb.offset(), kb.len()); } finally { pipe.clear(); } } else { CommentViews.visitByPostId(req.postId, store, res.context, RangeV.Store.ENTITY_PV, RangeV.RES_PV, res); } return true; } }
package com.intellij.diagnostic; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.ErrorLogger; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Priority; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import javax.swing.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Mike */ public class DialogAppender extends AppenderSkeleton { private static final DefaultIdeaErrorLogger DEFAULT_LOGGER = new DefaultIdeaErrorLogger(); static final boolean RELEASE_BUILD = false; private Runnable myDialogRunnable = null; protected synchronized void append(final LoggingEvent event) { if (!event.level.isGreaterOrEqual(Priority.WARN)) return; SwingUtilities.invokeLater(new Runnable() { public void run() { List<ErrorLogger> loggers = new ArrayList<ErrorLogger>(); loggers.add(DEFAULT_LOGGER); Application application = ApplicationManager.getApplication(); if (application != null) { if (application.isHeadlessEnvironment() || application.isDisposed()) return; loggers.addAll(Arrays.asList(application.getComponents(ErrorLogger.class))); } appendToLoggers(event, loggers.toArray(new ErrorLogger[loggers.size()])); } }); } void appendToLoggers(final LoggingEvent event, ErrorLogger[] errorLoggers) { if (myDialogRunnable != null) { return; } ThrowableInformation throwable = event.getThrowableInformation(); if (throwable == null) { return; } final IdeaLoggingEvent ideaEvent = new IdeaLoggingEvent((String)event.getMessage(), throwable.getThrowable()); for (int i = errorLoggers.length - 1; i >= 0; i final ErrorLogger logger = errorLoggers[i]; if (logger.canHandle(ideaEvent)) { //noinspection HardCodedStringLiteral myDialogRunnable = new Runnable() { public void run() { try { logger.handle(ideaEvent); } finally { myDialogRunnable = null; } } }; ApplicationManager.getApplication().executeOnPooledThread(myDialogRunnable); break; } } } public boolean requiresLayout() { return false; } public void close() { } }
package com.exedio.cope; import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class FunctionAttribute extends Attribute implements Function { private final Class valueClass; private final String valueClassName; private final UniqueConstraint implicitUniqueConstraint; private ArrayList uniqueConstraints; protected FunctionAttribute(final Option option, final Class valueClass, final String valueClassName) { super(option); this.valueClass = valueClass; this.valueClassName = valueClassName; this.implicitUniqueConstraint = option.unique ? new UniqueConstraint((FunctionAttribute)this) : null; } final void initialize(final Type type, final String name) { super.initialize(type, name); if(implicitUniqueConstraint!=null) implicitUniqueConstraint.initialize(type, name + UniqueConstraint.SINGLE_UNIQUE_SUFFIX); } public abstract FunctionAttribute copyAsTemplate(); abstract Object get(Row row); abstract void set(Row row, Object surface); final Option getTemplateOption() { if(isReadOnly()) if(isMandatory()) return Item.READ_ONLY; else return Item.READ_ONLY_OPTIONAL; else if(isMandatory()) return Item.MANDATORY; else return Item.OPTIONAL; } /** * Checks attribute values set by * {@link Item#setAttribute(FunctionAttribute,Object)} (for <code>initial==false</code>) * and {@link Item(FunctionAttribute[])} (for <code>initial==true</code>) * and throws the exception specified there. */ final void checkValue(final Object value, final Item item) throws MandatoryViolationException, LengthViolationException { if(value == null) { if(isMandatory()) throw new MandatoryViolationException(item, this); } else { if(value.equals("") && isMandatory() && !getType().getModel().supportsEmptyStrings()) // TODO dont call supportsEmptyStrings that often throw new MandatoryViolationException(item, this); if(!(valueClass.isAssignableFrom(value.getClass()))) { throw new ClassCastException( "expected " + valueClassName + ", got " + value.getClass().getName() + " for " + getName()); } checkNotNullValue(value, item); } } /** * Further checks non-null attribute values already checked by * {@link #checkValue(boolean, Object, Item)}. * To be overidden by subclasses, * the default implementation does nothing. */ void checkNotNullValue(final Object value, final Item item) throws LengthViolationException { } private static final Entity getEntity(final Item item) { return getEntity(item, true); } private static final Entity getEntity(final Item item, final boolean present) { return item.type.getModel().getCurrentTransaction().getEntity(item, present); } public final Object getObject(final Item item) { if(!getType().isAssignableFrom(item.type)) throw new RuntimeException("attribute "+toString()+" does not belong to type "+item.type.toString()); return getEntity(item).get(this); } public final void append(final Statement bf, final Join join) { bf.append(getColumn(), join); } public final void appendParameter(final Statement bf, final Object value) { final Row dummyRow = new Row(); set(dummyRow, value); final Column column = getColumn(); bf.appendParameter(column, dummyRow.get(column)); } /** * Returns the unique constraint of this attribute, * that has been created implicitly when creating this attribute. * Does return null, if there is no such unique constraint. * @see #getUniqueConstraints() */ public UniqueConstraint getImplicitUniqueConstraint() { return implicitUniqueConstraint; } /** * Returns a list of unique constraints this attribute is part of. * This includes an * {@link #getImplicitUniqueConstraint() implicit unique constraint}, * if there is one for this attribute. */ public List getUniqueConstraints() { return uniqueConstraints!=null ? Collections.unmodifiableList(uniqueConstraints) : Collections.EMPTY_LIST; } final void registerUniqueConstraint(final UniqueConstraint constraint) { if(constraint==null) throw new NullPointerException(); if(uniqueConstraints==null) { uniqueConstraints = new ArrayList(); } else { if(uniqueConstraints.contains(constraint)) throw new RuntimeException(constraint.toString()); } uniqueConstraints.add(constraint); } /** * Finds an item by it's unique attributes. * @return null if there is no matching item. */ public final Item searchUnique(final Object value) { // TODO: search nativly for unique constraints return getType().searchUnique(new EqualCondition(this, value)); } public final EqualCondition isNull() { return new EqualCondition(this, null); } public final NotEqualCondition isNotNull() { return new NotEqualCondition(this, null); } }
package cutin.sample; import java.util.ArrayList; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.garlicg.cutinlib.CutinInfo; import com.garlicg.cutinlib.CutinItem; import com.garlicg.cutinlib.Demo; public class DirectSettingActivity extends Activity{ private static final String TAG = "DirectSettingActivity"; private final DirectSettingActivity self = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Demo demo = new Demo(this); setContentView(R.layout.activity_directsetting); View getOnGooglePlay = findViewById(R.id.get_on_google_play); getOnGooglePlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse("market://details?id=com.garlicg.cutin")); startActivity(intent); } }); // set up ListView ArrayList<CutinItem> list = new ArrayList<CutinItem>(); list.add(new CutinItem(DirectSettingCutIn.class, "GREEN" ,0)); list.add(new CutinItem(DirectSettingCutIn.class, "BLUE" ,1)); list.add(new CutinItem(DirectSettingCutIn.class, "YELLOW" ,2)); ArrayAdapter<CutinItem> adapter = new ArrayAdapter<CutinItem>(this, android.R.layout.simple_list_item_single_choice, list); final ListView listView = (ListView)findViewById(R.id.direct_setting_ListView); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listView.setAdapter(adapter); listView.setItemChecked(0, true); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { CutinItem item = (CutinItem)arg0.getItemAtPosition(arg2); demo.play(item.serviceClass,item.cutinId); } }); // set up Button View okButton = findViewById(R.id.launch_cutin_manager); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = listView.getCheckedItemPosition(); Object obj = listView.getItemAtPosition(position); if(obj != null){ // direct setting! Intent intent = CutinInfo.buildSetCutinIntent((CutinItem)obj); try{ startActivity(intent); }catch(ActivityNotFoundException e){ Toast.makeText(self, "Activity not found.", Toast.LENGTH_SHORT).show(); } } } }); } }
package org.apache.batik.gvt.text; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.Stroke; import java.awt.BasicStroke; import java.awt.Font; import java.awt.font.TextAttribute; import java.awt.font.GlyphVector; import java.awt.font.GlyphMetrics; import java.awt.font.LineMetrics; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.text.AttributedCharacterIterator; import java.text.CharacterIterator; import java.text.AttributedString; import org.apache.batik.gvt.text.TextSpanLayout; import org.apache.batik.gvt.text.GVTAttributedCharacterIterator; import org.apache.batik.gvt.text.TextHit; /** * Implementation of TextSpanLayout which uses java.awt.font.GlyphVector. * @see org.apache.batik.gvt.TextSpanLayout. * * @author <a href="bill.haneman@ireland.sun.com>Bill Haneman</a> * @version $Id$ */ public class GlyphLayout implements TextSpanLayout { private GlyphVector gv; private Font font; private LineMetrics metrics; private AttributedCharacterIterator aci; private CharacterIterator ci; private FontRenderContext frc; private AffineTransform transform; private Point2D advance; private Point2D offset; private Point2D prevCharPosition; protected Shape[] glyphLogicalBounds; protected Point2D[] glyphPositions; /** * Creates the specified text layout using the * specified AttributedCharacterIterator and rendering context. * @param aci the AttributedCharacterIterator whose text is to * be laid out * @param frc the FontRenderContext to use for generating glyphs. */ public GlyphLayout(AttributedCharacterIterator aci, Point2D offset, FontRenderContext frc) { this.aci = (AttributedCharacterIterator) aci.clone(); this.frc = frc; this.font = getFont(aci); this.metrics = font.getLineMetrics( this.aci, aci.getBeginIndex(), aci.getEndIndex(), frc); ci = new ReorderedCharacterIterator(this.aci); this.gv = font.createGlyphVector(frc, ci); this.gv.performDefaultLayout(); this.glyphPositions = new Point2D.Float[gv.getNumGlyphs()]; this.offset = offset; this.transform = null; doExplicitGlyphLayout(false); adjustTextSpacing(); computeGlyphLogicalBounds(); } /** * Paints the specified text layout using the * specified Graphics2D and rendering context. * @param g2d the Graphics2D to use * @param x the x position of the rendered layout origin. * @param y the y position of the rendered layout origin. */ public void draw(Graphics2D g2d) { AffineTransform t; if (transform != null) { t = g2d.getTransform(); g2d.transform(transform); g2d.drawGlyphVector(gv, 0f, 0f); g2d.setTransform(t); } else { g2d.drawGlyphVector(gv, 0f, 0f); } } /** * Returns the outline of the completed glyph layout, transformed * by an AffineTransform. * @param t an AffineTransform to apply to the outline before returning it. */ public Shape getOutline() { Shape s = gv.getOutline(0f, 0f); if (transform != null) { s = transform.createTransformedShape(s); } return s; } /** * Returns the current text position at the beginning * of glyph layout, before the application of explicit * glyph positioning attributes. */ public Point2D getOffset() { return offset; } /** * Sets the text position used for the implicit origin * of glyph layout. Ignored if multiple explicit glyph * positioning attributes are present in ACI * (e.g. if the aci has multiple X or Y values). */ public void setOffset(Point2D offset) { //System.out.println("Offset set to "+offset); this.offset = offset; this.gv.performDefaultLayout(); doExplicitGlyphLayout(true); adjustTextSpacing(); computeGlyphLogicalBounds(); } /** * Returns the outline of the specified decorations on the glyphs, * @param decorationType an integer indicating the type(s) of decorations * included in this shape. May be the result of "OR-ing" several * values together: * e.g. <tt>DECORATION_UNDERLINE | DECORATION_STRIKETHROUGH</tt> */ public Shape getDecorationOutline(int decorationType) { Shape g = new GeneralPath(); if ((decorationType & DECORATION_UNDERLINE) != 0) { ((GeneralPath) g).append(getUnderlineShape(), false); } if ((decorationType & DECORATION_STRIKETHROUGH) != 0) { ((GeneralPath) g).append(getStrikethroughShape(), false); } if ((decorationType & DECORATION_OVERLINE) != 0) { ((GeneralPath) g).append(getOverlineShape(), false); } if (transform != null) { g = transform.createTransformedShape(g); } return g; } /** * Returns the rectangular bounds of the completed glyph layout. */ public Rectangle2D getBounds() { Rectangle2D bounds = gv.getVisualBounds(); if (transform != null) { bounds = transform.createTransformedShape(bounds).getBounds2D(); } return bounds; } /** * Returns the rectangular bounds of the completed glyph layout, * inclusive of "decoration" (underline, overline, etc.) */ public Rectangle2D getDecoratedBounds() { return getBounds().createUnion( getDecorationOutline( DECORATION_ALL).getBounds2D()); } /** * Returns the dimension of the completed glyph layout in the * primary text advance direction (e.g. width, for RTL or LTR text). * (This is the dimension that should be used for positioning * adjacent layouts.) */ public float getAdvance() { return (float) advance.getX(); } /** * Returns the current text position at the completion * of glyph layout. * (This is the position that should be used for positioning * adjacent layouts.) */ public Point2D getAdvance2D() { return advance; } /** * Returns a Shape which encloses the currently selected glyphs * as specified by glyph indices <tt>begin/tt> and <tt>end</tt>. * @param begin the index of the first glyph in the contiguous selection. * @param end the index of the last glyph in the contiguous selection. */ public Shape getLogicalHighlightShape(int begin, int end) { Shape shape = null; begin = Math.max(0, begin); end = Math.min(end, gv.getNumGlyphs()); if (begin == 0 && end == gv.getNumGlyphs()) { shape = new GeneralPath(getBounds()); } else { for (int i=begin; i<end; ++i) { Shape gbounds = getGlyphLogicalBounds(i); Rectangle2D gbounds2d = gbounds.getBounds2D(); if (shape == null) { shape = new GeneralPath(gbounds2d); } else { ((GeneralPath) shape).append(gbounds2d, false); } } if (transform != null) { shape = transform.createTransformedShape(shape); } } return shape; } /** * Perform hit testing for coordinate at x, y. * @return a TextHit object encapsulating the character index for * successful hits and whether the hit is on the character * leading edge. * @param x the x coordinate of the point to be tested. * @param y the y coordinate of the point to be tested. */ public TextHit hitTestChar(float x, float y) { int begin = 0; int end = gv.getNumGlyphs(); TextHit textHit; GlyphMetrics gm; float maxX = (float) gv.getVisualBounds().getX(); if (transform != null) { try { Point2D p = new Point2D.Float(x, y); transform.inverseTransform(p, p); x = (float) p.getX(); y = (float) p.getY(); } catch (java.awt.geom.NoninvertibleTransformException nite) {;} } for (int i=begin; i<end; ++i) { Shape gbounds = getGlyphLogicalBounds(i); Rectangle2D gbounds2d = gbounds.getBounds2D(); if (gbounds2d.getX()+gbounds2d.getWidth() > maxX) { maxX = (float) (gbounds2d.getX()+gbounds2d.getWidth()); } if (gbounds.contains(x, y)) { boolean isRightHalf = (x > (gbounds2d.getX()+(gbounds2d.getWidth()/2d))); boolean isLeadingEdge = !isRightHalf; textHit = new TextHit(i, isLeadingEdge); return textHit; } } // fallthrough: in text bbox but not on a glyph textHit = new TextHit(-1, false); return textHit; } /** * Returns true if the advance direction of this text is vertical. */ public boolean isVertical() { // TODO: Implement this! return false; } /** * Returns the number of characters in this layout. */ public int getCharacterCount() { return gv.getNumGlyphs(); // XXX: probably wrong for CTL, work to be done here! } protected Shape getGlyphLogicalBounds(int i) { // We can't use GlyphVector.getGlyphLogicalBounds(i) // since it seems to have a nasty bug! return glyphLogicalBounds[i]; } // private private void computeGlyphLogicalBounds() { int c = gv.getNumGlyphs(); glyphLogicalBounds = new Rectangle2D.Double[c]; Rectangle2D.Double lbox = null; for (int i=0; i<c; ++i) { GlyphMetrics gm = gv.getGlyphMetrics(i); Rectangle2D gbounds2d = gm.getBounds2D(); Point2D gpos = glyphPositions[i]; lbox = new Rectangle2D.Double( gpos.getX()+gbounds2d.getX(), gpos.getY()+gbounds2d.getY(), gbounds2d.getWidth(), gbounds2d.getHeight()); glyphLogicalBounds[i] = lbox; } for (int i=0; i<c; ++i) { int begin = i; int end = begin; Point2D gpos = glyphPositions[begin]; // calculate a "run" over the same y nominal position, // over which the glyphs have positive 'x' advances. // (means that RTL "runs" are not yet supported, sorry) float y = (float) gpos.getY(); float x = (float) gpos.getX(); lbox = (Rectangle2D.Double) glyphLogicalBounds[begin]; float miny = (float) lbox.getY(); float maxy = (float) (lbox.getY() + lbox.getHeight()); float epsilon = (float) lbox.getHeight()/8f; float currY = y; float currX = x; while (end<c) { lbox = (Rectangle2D.Double) glyphLogicalBounds[end]; currY = (float) glyphPositions[end].getY(); currX = (float) glyphPositions[end].getX(); if ((currX < x) || (Math.abs(currY - y) > epsilon)) { break; } miny = Math.min((float) lbox.getY(), miny); float h = (float) (lbox.getY() + lbox.getHeight()); maxy = Math.max(h, maxy); ++end; } i = (end > begin) ? end-1 : end; Rectangle2D.Double lboxPrev = null; float prevx = 0f; for (int n=begin; n<end; ++n) { // extend the vertical bbox for this run lbox = (Rectangle2D.Double) glyphLogicalBounds[n]; x = (float) lbox.getX(); // adjust left bounds if not first in run if (lboxPrev != null) { x = (float) (x + (prevx+lboxPrev.getWidth()))/2f; glyphLogicalBounds[n-1] = new Rectangle2D.Double( (double) prevx, lboxPrev.getY(), (double) (x - prevx), lboxPrev.getHeight()); //System.out.println("Setting glb["+(n-1)+"]="+ // glyphLogicalBounds[n-1]); } lbox = new Rectangle2D.Double( (double) x, (double) miny, Math.max(0d, lbox.getWidth()+(lbox.getX() - x)), (double) (maxy - miny)); lboxPrev = lbox; prevx = x; glyphLogicalBounds[n] = lbox; } } } //inner classes protected class ReorderedCharacterIterator implements CharacterIterator { private int ndx; private int begin; private int end; private char[] c; ReorderedCharacterIterator(AttributedCharacterIterator aci) { int aciIndex = aci.getBeginIndex(); begin = 0; end = aci.getEndIndex()-aciIndex; ndx = begin; c = new char[end-begin]; // set increment and initial array index according to // run direction of this aci int inc = (aci.getAttribute(TextAttribute.RUN_DIRECTION) == TextAttribute.RUN_DIRECTION_RTL) ? -1 : 1; ndx = (inc > 0) ? begin : end-1; // reordering section char ch = aci.first(); while (ch != CharacterIterator.DONE) { // get BiDi embedding Integer embed = (Integer) aci.getAttribute( TextAttribute.BIDI_EMBEDDING); //System.out.println("BiDi embedding level : "+embed); // get BiDi span int runLimit = aci.getRunLimit(TextAttribute.BIDI_EMBEDDING); boolean isReversed = false; int runEndNdx = ndx; if (embed != null) { isReversed = (Math.abs(Math.IEEEremainder( (double)embed.intValue(), 2d)) < 0.1) ? false : true; if (isReversed) { runEndNdx = ndx + inc*(runLimit-aciIndex); inc = -inc; ndx = runEndNdx + inc; } } for (;aciIndex < runLimit; ch=aci.next(),++aciIndex) { c[ndx] = ch; //System.out.println("Setting c["+ndx+"] to "+ch); ndx += inc; } if (isReversed) { // undo the reversal, run is done ndx = runEndNdx; inc = -inc; } } aci.first(); ndx = begin; } public Object clone() { return new ReorderedCharacterIterator( (AttributedCharacterIterator) aci.clone()); } public char current() { return c[ndx]; } public char first() { ndx=begin; return c[ndx]; } public int getBeginIndex() { return begin; } public int getEndIndex() { return end; } public int getIndex() { return ndx; } public char last() { ndx = end-1; return c[end-1]; } public char next() { ++ndx; if (ndx >= end) { ndx = end; return CharacterIterator.DONE; } else return c[ndx]; } public char previous() { --ndx; if (ndx < begin) { ndx = begin; return c[ndx]; } else return c[ndx]; } public char setIndex(int position) { if (position < begin || position > end) { throw new IllegalArgumentException(); } ndx = position; return c[ndx]; } } //protected /** * Returns a shape describing the overline decoration for a given ACI. */ protected Shape getOverlineShape() { double y = metrics.getBaselineOffsets()[java.awt.Font.ROMAN_BASELINE] - metrics.getAscent(); Stroke overlineStroke = new BasicStroke(metrics.getUnderlineThickness()); return overlineStroke.createStrokedShape( new java.awt.geom.Line2D.Double( 0f, y, getAdvance(), y)); } /** * Returns a shape describing the strikethrough line for a given ACI. */ protected Shape getUnderlineShape() { double y = metrics.getUnderlineOffset(); Stroke underlineStroke = new BasicStroke(metrics.getUnderlineThickness()); return underlineStroke.createStrokedShape( new java.awt.geom.Line2D.Double( 0f, y, getAdvance(), y)); } /** * Returns a shape describing the strikethrough line for a given ACI. */ protected Shape getStrikethroughShape() { double y = metrics.getStrikethroughOffset(); Stroke strikethroughStroke = new BasicStroke(metrics.getStrikethroughThickness()); return strikethroughStroke.createStrokedShape( new java.awt.geom.Line2D.Double( 0f, y, getAdvance(), y)); } protected Font getFont(AttributedCharacterIterator aci) { aci.first(); return new Font(aci.getAttributes()); } protected void adjustTextSpacing() { aci.first(); Boolean customSpacing = (Boolean) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.CUSTOM_SPACING); Float length = (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.BBOX_WIDTH); Integer lengthAdjust = (Integer) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.LENGTH_ADJUST); if ((customSpacing != null) && customSpacing.booleanValue()) { applySpacingParams(length, lengthAdjust, (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.KERNING), (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.LETTER_SPACING), (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.WORD_SPACING)); } if (lengthAdjust == GVTAttributedCharacterIterator.TextAttribute.ADJUST_ALL) { transform = computeStretchTransform(length); } } protected AffineTransform computeStretchTransform(Float length) { AffineTransform t = null; if (length!= null && !length.isNaN()) { double xscale = 1d; double yscale = 1d; if (isVertical()) { yscale = length.floatValue()/gv.getVisualBounds().getHeight(); } else { xscale = length.floatValue()/gv.getVisualBounds().getWidth(); } try { Point2D startPos = gv.getGlyphPosition(0); AffineTransform translation = AffineTransform.getTranslateInstance( startPos.getX(), startPos.getY()); AffineTransform inverse = translation.createInverse(); t = translation; t.concatenate( AffineTransform.getScaleInstance(xscale, yscale)); t.concatenate(inverse); } catch (java.awt.geom.NoninvertibleTransformException e) {;} } return t; } protected void applySpacingParams(Float length, Integer lengthAdjust, Float kern, Float letterSpacing, Float wordSpacing) { /** * Two passes required when textLength is specified: * First, apply spacing properties, * then adjust spacing with new advances based on ratio * of expected length to actual advance. */ advance = doSpacing(kern, letterSpacing, wordSpacing); if ((lengthAdjust == GVTAttributedCharacterIterator.TextAttribute.ADJUST_SPACING) && length!= null && !length.isNaN()) { // adjust if necessary float xscale = 1f; float yscale = 1f; if (!isVertical()) { xscale = length.floatValue()/(float) gv.getVisualBounds().getWidth(); } else { yscale = length.floatValue()/(float) gv.getVisualBounds().getHeight(); } rescaleSpacing(xscale, yscale); } } protected Point2D doSpacing(Float kern, Float letterSpacing, Float wordSpacing) { boolean autoKern = true; boolean doWordSpacing = false; boolean doLetterSpacing = false; float kernVal = 0f; float letterSpacingVal = 0f; float wordSpacingVal = 0f; if ((kern instanceof Float) && (!kern.isNaN())) { kernVal = kern.floatValue(); autoKern = false; //System.out.println("KERNING: "+kernVal); } if ((letterSpacing instanceof Float) && (!letterSpacing.isNaN())) { letterSpacingVal = letterSpacing.floatValue(); doLetterSpacing = true; //System.out.println("LETTER-SPACING: "+letterSpacingVal); } if ((wordSpacing instanceof Float) && (!wordSpacing.isNaN())) { wordSpacingVal = wordSpacing.floatValue(); doWordSpacing = true; //System.out.println("WORD_SPACING: "+wordSpacingVal); } int numGlyphs = gv.getNumGlyphs(); float dx = 0f; float dy = 0f; Point2D newPositions[] = new Point2D[numGlyphs]; Point2D prevPos = glyphPositions[0]; float x = (float) prevPos.getX(); float y = (float) prevPos.getY(); try { if ((numGlyphs > 1) && (doWordSpacing || doLetterSpacing || !autoKern)) { for (int i=1; i<numGlyphs; ++i) { Point2D gpos = glyphPositions[i]; dx = (float)gpos.getX()-(float)prevPos.getX(); dy = (float)gpos.getY()-(float)prevPos.getY(); boolean inWS = false; // while this is whitespace, increment int beginWS = i; int endWS = i; GlyphMetrics gm = gv.getGlyphMetrics(i); // BUG: gm.isWhitespace() fails for latin SPACE glyph! while ((gm.getBounds2D().getWidth()<0.01d) || gm.isWhitespace()) { ++i; ++endWS; if (!inWS) inWS = true; if (i>=numGlyphs) { inWS = false; break; } gpos = glyphPositions[i]; gm = gv.getGlyphMetrics(i); } // then apply wordSpacing if ( inWS ) { if (doWordSpacing) { int nWS = endWS-beginWS; float px = (float) prevPos.getX(); float py = (float) prevPos.getY(); dx = (float) (gpos.getX() - px)/(nWS+1); dy = (float) (gpos.getY() - py)/(nWS+1); if (isVertical()) { dy += (float) wordSpacing.floatValue()/(nWS+1); } else { dx += (float) wordSpacing.floatValue()/(nWS+1); } for (int j=beginWS; j<=endWS; ++j) { x += dx; y += dy; newPositions[j] = new Point2D.Float(x, y); } } } else { dx = (float) (gpos.getX()-prevPos.getX()); dy = (float) (gpos.getY()-prevPos.getY()); if (autoKern) { if (isVertical()) dy += letterSpacingVal; else dx += letterSpacingVal; } else { // apply explicit kerning adjustments, // discarding any auto-kern dx values if (isVertical()) { dy = (float) gv.getGlyphMetrics(i-1).getBounds2D().getWidth()+ kernVal + letterSpacingVal; } else { dx = (float) gv.getGlyphMetrics(i-1).getBounds2D().getWidth()+ kernVal + letterSpacingVal; } } x += dx; y += dy; newPositions[i] = new Point2D.Float(x, y); } prevPos = gpos; } for (int i=1; i<numGlyphs; ++i) { // assign the new positions glyphPositions[i] = newPositions[i]; gv.setGlyphPosition(i, glyphPositions[i]); } } if (isVertical()) { dx = 0f; dy = (float) gv.getGlyphMetrics(numGlyphs-1).getBounds2D().getHeight()+ kernVal+letterSpacingVal; } else { dx = (float) gv.getGlyphMetrics(numGlyphs-1).getBounds2D().getWidth()+ kernVal+letterSpacingVal; dy = 0f; } } catch (Exception e) { e.printStackTrace(); } //Point2D newAdvance = new Point2D.Float((float) prevPos.getX()+dx, // (float) prevPos.getY()+dy); Point2D newAdvance = advance; gv.setGlyphPosition(numGlyphs, newAdvance); return newAdvance; } protected void rescaleSpacing(float xscale, float yscale) { Rectangle2D bounds = gv.getVisualBounds(); float initX = (float) bounds.getX(); float initY = (float) bounds.getY(); int numGlyphs = gv.getNumGlyphs(); float dx = 0f; float dy = 0f; for (int i=0; i<numGlyphs; ++i) { Point2D gpos = glyphPositions[i]; dx = (float)gpos.getX()-initX; dy = (float)gpos.getY()-initY; glyphPositions[i] = new Point2D.Float(initX+dx*xscale, initY+dy*yscale); gv.setGlyphPosition(i, glyphPositions[i]); } gv.setGlyphPosition(numGlyphs, new Point2D.Float(initX+dx*xscale, initY+dy*yscale)); advance = new Point2D.Float((float)(initX+dx*xscale-offset.getX()), (float)(initY+dy*yscale-offset.getY())); } protected void doExplicitGlyphLayout(boolean applyOffset) { char ch = aci.first(); int i=0; float[] gp = new float[(gv.getNumGlyphs()+1)*2]; gp = (float[]) gv.getGlyphPositions(0, gv.getNumGlyphs(), gp).clone(); float init_x_pos = (float) offset.getX(); float init_y_pos = (float) offset.getY(); float curr_x_pos = gp[0] + init_x_pos; float curr_y_pos = gp[1] + init_y_pos; while ((ch != CharacterIterator.DONE) && (i < gp.length/2)) { Float x = (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.X); Float dx = (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.DX); Float y = (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.Y); Float dy = (Float) aci.getAttribute( GVTAttributedCharacterIterator.TextAttribute.DY); if (x!= null && !x.isNaN()) { if (i==0) { if (applyOffset) { curr_x_pos = (float) offset.getX(); } else { curr_x_pos = x.floatValue(); init_x_pos = curr_x_pos; } } else { curr_x_pos = x.floatValue(); } } else if (dx != null && !dx.isNaN()) { curr_x_pos += dx.floatValue(); } if (y != null && !y.isNaN()) { if (i==0) { if (applyOffset) { curr_y_pos = (float) offset.getY(); } else { curr_y_pos = y.floatValue(); init_y_pos = curr_y_pos; } } else { curr_y_pos = y.floatValue(); } } else if (dy != null && !dy.isNaN()) { curr_y_pos += dy.floatValue(); } else if (i>0) { curr_y_pos += gp[i*2 + 1]-gp[i*2 - 1]; } glyphPositions[i] = new Point2D.Float(curr_x_pos, curr_y_pos); gv.setGlyphPosition(i, glyphPositions[i]); //System.out.print(ch); //System.out.print("["+curr_x_pos+","+curr_y_pos+"]"); curr_x_pos += (float) gv.getGlyphMetrics(i).getAdvance(); ch = aci.next(); ++i; } gv.setGlyphPosition(i, new Point2D.Float(curr_x_pos, curr_y_pos)); //System.out.println(); advance = new Point2D.Float((float) (curr_x_pos-offset.getX()), (float) (curr_y_pos-offset.getY())); offset = new Point2D.Float(init_x_pos, init_y_pos); } }
package org.umlg.sqlg; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.umlg.sqlg.test.*; import org.umlg.sqlg.test.batch.*; import org.umlg.sqlg.test.edgehas.TestEdgeHas; import org.umlg.sqlg.test.edges.*; import org.umlg.sqlg.test.github.TestGithub; import org.umlg.sqlg.test.graph.TestEmptyGraph; import org.umlg.sqlg.test.graph.TestGraphStepWithIds; import org.umlg.sqlg.test.gremlincompile.*; import org.umlg.sqlg.test.index.TestForeignKeyIndexPerformance; import org.umlg.sqlg.test.index.TestIndex; import org.umlg.sqlg.test.json.JsonTest; import org.umlg.sqlg.test.json.TestJsonUpdate; import org.umlg.sqlg.test.labels.TestMultipleLabels; import org.umlg.sqlg.test.localdate.LocalDateTest; import org.umlg.sqlg.test.memory.TestMemoryUsage; import org.umlg.sqlg.test.mod.*; import org.umlg.sqlg.test.multithread.TestMultiThread; import org.umlg.sqlg.test.remove.TestRemoveEdge; import org.umlg.sqlg.test.rollback.TestRollback; import org.umlg.sqlg.test.schema.*; import org.umlg.sqlg.test.topology.TestTopologyUpgrade; import org.umlg.sqlg.test.travers.TestTraversals; import org.umlg.sqlg.test.tree.TestColumnNamePropertyNameMapScope; import org.umlg.sqlg.test.vertex.*; import org.umlg.sqlg.test.vertexout.TestVertexOutWithHas; import org.umlg.sqlg.test.vertexstep.localvertexstep.*; @RunWith(Suite.class) @Suite.SuiteClasses({ TestAddVertexViaMap.class, TestAllEdges.class, TestAllVertices.class, TestArrayProperties.class, TestCountVerticesAndEdges.class, TestDeletedVertex.class, TestEdgeCreation.class, TestEdgeToDifferentLabeledVertexes.class, TestGetById.class, TestHas.class, TestHasLabel.class, TestLoadArrayProperties.class, TestLoadElementProperties.class, TestLoadSchema.class, TestPool.class, TestRemoveElement.class, TestSetProperty.class, TestVertexCreation.class, TestVertexEdgeSameName.class, TestVertexNavToEdges.class, TestByteArray.class, TestQuery.class, TestSchema.class, TestIndex.class, TestVertexOutWithHas.class, TestEdgeHas.class, TestBatch.class, TestNormalBatchUpdate.class, TestForeignKeyIndexPerformance.class, TestMultiThreadedBatch.class, TestRemoveEdge.class, TestEdgeSchemaCreation.class, TestRollback.class, TestMultiThread.class, TestNewVertex.class, TestEdgeCache.class, TestVertexCache.class, TestTinkerpopBug.class, TestLazyLoadSchema.class, TestCreateEdgeBetweenVertices.class, TestRemovedVertex.class, TestCaptureSchemaTableEdges.class, TestGremlinCompileWithHas.class, TestGremlinCompileE.class, TestEmptyGraph.class, TestOutE.class, TestForeignKeysAreOptional.class, TestGremlinCompileWithAs.class, TestGremlinCompileWithInOutV.class, TestGremlinCompileV.class, TestGremlinCompileGraphStep.class, TestGremlinCompileWhere.class, TestColumnNameTranslation.class, TestGraphStepOrderBy.class, TestAggregate.class, TestVertexStepOrderBy.class, TestPathStep.class, LocalDateTest.class, TestStreamVertex.class, TestStreamEdge.class, JsonTest.class, TestSchemaManagerGetTablesFor.class, TestBatchServerSideEdgeCreation.class, TestBatchedStreaming.class, TestBulkWithin.class, TestBulkWithout.class, TestRemoveProperty.class, TestSchemaManagerGetTablesFor.class, TestAggregate.class, TestTreeStep.class, TestRepeatStepGraphOut.class, TestRepeatStepGraphIn.class, TestRepeatStepVertexOut.class, TestRepeatStepGraphBoth.class, TestGraphStepWithIds.class, TestOtherVertex.class, TestGremlinMod.class, TestTopologyUpgrade.class, TestTraversals.class, TestGremlinOptional.class, TestAlias.class, TestGithub.class, TestLocalVertexStepOptional.class, TestLocalVertexStepRepeatStep.class, TestLocalEdgeVertexStep.class, TestLocalEdgeOtherVertexStep.class, TestNormalBatchDateTime.class, TestBatchEdgeDateTime.class, TestBatchJson.class, TestMemoryUsage.class, TestBatchTemporaryVertex.class, TestNormalBatchPrimitiveArrays.class, TestNormalBatchPrimitive.class, TestNormalBatchUpdatePrimitiveArrays.class, TestJsonUpdate.class, TestNormalBatchUpdateDateTime.class, TestOptionalWithOrder.class, TestMultipleLabels.class, TestColumnNamePropertyNameMapScope.class, TestJNDIInitialization.class, TestSchemaTableTreeAndHasContainer.class }) public class AllTest { }
package org.jpos.ee.pm.core; import java.util.List; import org.jpos.ee.pm.security.core.PMSecurityUser; import org.jpos.transaction.Context; import org.jpos.util.Log; /** * An extension of the org.jpos.transaction.Context class with some helpers * for PM. */ public class PMContext extends Context { private String sessionId; public static final String PM_ERRORS = "PM_ERRORS"; public PMContext(String sessionId) { this.sessionId = sessionId; } /** * @return the errors */ public List<PMMessage> getErrors() { return (List<PMMessage>) get(PM_ERRORS); } /** * @param errors the errors to set */ public void setErrors(List<PMMessage> errors) { put(PM_ERRORS, errors); } /** * Getter for PM singleton * @return */ public PresentationManager getPresentationManager() { return PresentationManager.pm; } /** * Return the persistance manager of the PM * @return PersistenceManager */ public PersistenceManager getPersistanceManager() { return getPresentationManager().getPersistenceManager(); } /** * Return the PM log * @return */ public Log getLog() { return getPresentationManager().getLog(); } /** * @param entityContainer the entity_container to set */ public void setEntityContainer(EntityContainer entityContainer) { put(PMCoreObject.PM_ENTITY_CONTAINER, entityContainer); } /** * @return the entity_container * @throws PMException */ public EntityContainer getEntityContainer() throws PMException { EntityContainer entityContainer = (EntityContainer) get(PMCoreObject.PM_ENTITY_CONTAINER); if (entityContainer == null) { PresentationManager.getPm().error("Entity container not found"); throw new PMException("pm_core.entity.not.found"); } return entityContainer; } /** * Retrieve the container with the given id from session * * @param id The entity id * @return The container * @throws PMException when no container was found */ public EntityContainer getEntityContainer(String id) throws PMException { EntityContainer ec = (EntityContainer) getPMSession().getContainer(id); if (ec == null) { throw new PMException("pm_core.entity.not.found"); } return ec; } /** * Returns the entity container * @param ignorenull If true, does not throws an exception on missing container * @return The container * @throws PMException */ public EntityContainer getEntityContainer(boolean ignorenull) throws PMException { EntityContainer entityContainer = (EntityContainer) get(PMCoreObject.PM_ENTITY_CONTAINER); if (ignorenull) { return entityContainer; } if (entityContainer == null) { throw new PMException("pm_core.entity.not.found"); } return entityContainer; } /** * Informs if there is a container in the context * * @return true if there is a container in the context */ public boolean hasEntityContainer() { EntityContainer entityContainer = (EntityContainer) get(PMCoreObject.PM_ENTITY_CONTAINER); return entityContainer != null; } /** * @param operation the operation to set */ public void setOperation(Operation operation) { put(PMCoreObject.PM_OPERATION, operation); } /** * @return the operation */ public Operation getOperation() { return (Operation) get(PMCoreObject.PM_OPERATION); } /** * Return the entity in the container * @return The entity * @throws PMException */ public Entity getEntity() throws PMException { return getEntityContainer().getEntity(); } /** * Return the list of the container * @return The list * @throws PMException */ public PaginatedList getList() throws PMException { return getEntityContainer().getList(); } /** * Return the selected item of the container * @return The EntityInstanceWrapper * @throws PMException */ public EntityInstanceWrapper getSelected() throws PMException { return getEntityContainer().getSelected(); } /** * Indicate if there is a container with an entity * * @return */ public boolean hasEntity() { try { return (hasEntityContainer() && getEntityContainer().getEntity() != null); } catch (PMException e) { return false; } } public PMSession getPMSession() { return getPresentationManager().getSession(getSessionId()); } public String getSessionId() { return sessionId; } /**Getter for the logged user * @return The user */ public PMSecurityUser getUser() { if (getPMSession() == null) { return null; } return getPMSession().getUser(); } /**Indicates if there is a user online * @return True if there is a user online */ public boolean isUserOnLine() { return (getUser() != null); } public Object getParameter(String paramid) { final Object v = get("param_" + paramid); if (v == null) { return null; } else { String[] s = (String[]) v; if (s.length == 1) { return s[0]; } else { return s; } } } public Object[] getParameters(String paramid) { return (Object[]) get("param_" + paramid); } public boolean getBoolean(String id, boolean def) { try { if (get(id) == null) { return def; } return (Boolean) get(id); } catch (Exception e) { return def; } } }
package org.robovm.bindings.mopub.sample; import org.robovm.bindings.mopub.MPAdView; import org.robovm.bindings.mopub.MPAdViewDelegate; import org.robovm.bindings.mopub.MPConstants; import org.robovm.bindings.mopub.MPInterstitialAdController; import org.robovm.bindings.mopub.MPInterstitialAdControllerDelegate; import org.robovm.cocoatouch.coregraphics.CGRect; import org.robovm.cocoatouch.foundation.NSAutoreleasePool; import org.robovm.cocoatouch.uikit.UIApplication; import org.robovm.cocoatouch.uikit.UIApplicationDelegate; import org.robovm.cocoatouch.uikit.UIColor; import org.robovm.cocoatouch.uikit.UIScreen; import org.robovm.cocoatouch.uikit.UIViewController; import org.robovm.cocoatouch.uikit.UIWindow; /** Basic usage of banners and interstitials. */ public class Sample extends UIApplicationDelegate.Adapter { private static final String INTERSTITIAL_AD_UNIT_ID = "YOUR_AD_UNIT_ID"; private static final String BANNER_AD_UNIT_ID = "YOUR_AD_UNIT_ID"; private UIViewController rootViewController; private MPAdViewController adViewController; @Override public void didFinishLaunching (UIApplication application) { // We need a view controller to see ads. rootViewController = new UIViewController(); // If you are already using a UIWindow with a root view controller, get the root view controller (f.e. LibGDX): // rootViewController = UIApplication.getSharedApplication().getKeyWindow().getRootViewController(); // Create an interstitial. final MPInterstitialAdController interstitial = MPInterstitialAdController.getAdController(INTERSTITIAL_AD_UNIT_ID); // The delegate for an interstitial is optional. MPInterstitialAdControllerDelegate delegate = new MPInterstitialAdControllerDelegate.Adapter() { @Override public void didDisappear (MPInterstitialAdController interstitial) { // If the ad disappears, load a new ad, so we can show it immediately the next time. interstitial.loadAd(); } @Override public void didExpire (MPInterstitialAdController interstitial) { // If the ad did expire, load a new ad, so we can show it immediately the next time. interstitial.loadAd(); } @Override public void didLoadAd (MPInterstitialAdController interstitial) { // If the ad is ready, show it. // It's best to call these methods manually and not in didLoadAd(). Use this only for testing purposes! if (interstitial.isReady()) interstitial.show(rootViewController); } @Override public void didFailToLoadAd (MPInterstitialAdController interstitial) { // If the ad did fail to load, load a new ad. Check the debug log to see why it didn't load. interstitial.loadAd(); } }; interstitial.setDelegate(delegate); // Create a MoPub ad. In this case a banner, but you can make it any size you want. final MPAdView banner = new MPAdView(BANNER_AD_UNIT_ID, MPConstants.MOPUB_BANNER_SIZE); // Let's calculate our banner size. We need to do this because the resolution of a retina and normal device is different. float bannerWidth = UIScreen.getMainScreen().getBounds().size().width(); float bannerHeight = bannerWidth / MPConstants.MOPUB_BANNER_SIZE.width() * MPConstants.MOPUB_BANNER_SIZE.height(); // Let's set the frame (bounds) of our banner view. Remember on iOS view coordinates have their origin top-left. // Position banner on the top. // banner.setFrame(new CGRect(0, 0, bannerWidth, bannerHeight)); // Position banner on the bottom. banner.setFrame(new CGRect(0, UIScreen.getMainScreen().getBounds().size().height() - bannerHeight, bannerWidth, bannerHeight)); // Let's color the background for testing, so we can see if it is positioned correctly, even if no ad is loaded yet. banner.setBackgroundColor(new UIColor(1, 0, 0, 1)); // Remove this after testing. // We use our custom ad view controller to notify for orientation changes. adViewController = new MPAdViewController(banner); // The delegate for the banner. It is required to override getViewController() to get ads. MPAdViewDelegate bannerDelegate = new MPAdViewDelegate.Adapter() { @Override public UIViewController getViewController () { return adViewController; } }; banner.setDelegate(bannerDelegate); // Add banner to our view controller. adViewController.getView().addSubview(banner); // We add the ad view controller to our root view controller. rootViewController.addChildViewController(adViewController); rootViewController.getView().addSubview(adViewController.getView()); // Create a standard UIWindow at screen size, add the view controller and show it. UIWindow window = new UIWindow(UIScreen.getMainScreen().getBounds()); window.setRootViewController(rootViewController); window.addSubview(rootViewController.getView()); window.makeKeyAndVisible(); // Load an interstitial ad. interstitial.loadAd(); // Load a banner ad. This ad gets refreshed automatically, although you can refresh it at any time via refreshAd(). banner.loadAd(); } public static void main (String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, Sample.class); pool.drain(); } }
package ru.wapstart.plus1.sdk; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.ImageView; import android.widget.FrameLayout; import android.util.Log; import android.webkit.WebView; import ru.wapstart.plus1.sdk.MraidView.ViewState; public class Plus1BannerView extends FrameLayout { private static final String LOGTAG = "Plus1BannerView"; private OnAutorefreshStateListener mOnAutorefreshChangeListener; private Plus1AdAnimator mAdAnimator = null; private Animation mHideAnimation = null; private Animation mShowAnimation = null; private String mWebViewUserAgent = null; private boolean mHaveCloseButton = false; private boolean mClosed = false; private boolean mInitialized = false; private boolean mAutorefreshEnabled = true; private boolean mExpanded = false; private Plus1BannerViewStateListener mViewStateListener = null; public Plus1BannerView(Context context) { this(context, null); } public Plus1BannerView(Context context, AttributeSet attr) { super(context, attr); setHorizontalScrollBarEnabled(false); setVerticalScrollBarEnabled(false); mWebViewUserAgent = new WebView(context).getSettings().getUserAgentString(); } public void onPause() { if (mAdAnimator != null) { mAdAnimator.stopLoading(); mAdAnimator.clearAnimation(); if (mAdAnimator.getCurrentView() instanceof MraidView) { ((MraidView)mAdAnimator.getCurrentView()) .unregisterBroadcastReceiver(); } } new WebView(getContext()).pauseTimers(); } public void onResume() { if ( mAdAnimator != null && mAdAnimator.getCurrentView() instanceof MraidView ) { ((MraidView)mAdAnimator.getCurrentView()) .registerBroadcastReceiver(); } new WebView(getContext()).resumeTimers(); } public boolean canGoBack() { return mAdAnimator.getCurrentView() != null && mAdAnimator.getCurrentView().canGoBack(); } public void goBack() { if (mAdAnimator.getCurrentView() != null) mAdAnimator.getCurrentView().goBack(); } public String getWebViewUserAgent() { return mWebViewUserAgent; } public boolean isHaveCloseButton() { return mHaveCloseButton; } public Plus1BannerView enableCloseButton() { mHaveCloseButton = true; return this; } public Plus1BannerView setCloseButtonEnabled(boolean closeButtonEnabled) { mHaveCloseButton = closeButtonEnabled; return this; } public boolean isClosed() { return mClosed; } public Plus1BannerView enableAnimationFromTop() { return enableAnimation(-1f); } public Plus1BannerView enableAnimationFromBottom() { return enableAnimation(1f); } public Plus1BannerView disableAnimation() { mShowAnimation = null; mHideAnimation = null; return this; } public void loadAd(String html, String adType) { init(); BaseAdView adView = "mraid".equals(adType) ? makeMraidView() : makeAdView(); mAdAnimator.loadAdView(adView, html); } public MraidView makeMraidView() { MraidView adView = new MraidView(getContext()); Log.d(LOGTAG, "MraidView instance created"); adView.setOnReadyListener(new MraidView.OnReadyListener() { public void onReady(MraidView view) { show(); } }); adView.setOnExpandListener(new MraidView.OnExpandListener() { public void onExpand(MraidView view) { setExpanded(true); //setVisibility(INVISIBLE); // hide without animation } }); adView.setOnCloseListener(new MraidView.OnCloseListener() { public void onClose(MraidView view, ViewState newViewState) { setExpanded(false); } }); adView.setOnFailureListener(new MraidView.OnFailureListener() { public void onFailure(MraidView view) { Log.e(LOGTAG, "Mraid ad failed to load"); } }); return adView; } public AdView makeAdView() { AdView adView = new AdView(getContext()); Log.d(LOGTAG, "AdView instance created"); adView.setOnReadyListener(new AdView.OnReadyListener() { public void onReady() { show(); } }); return adView; } public void setOnAutorefreshChangeListener(OnAutorefreshStateListener listener) { mOnAutorefreshChangeListener = listener; } public Plus1BannerView setAutorefreshEnabled(boolean enabled) { if (mAutorefreshEnabled != enabled) { // NOTE: really changed mAutorefreshEnabled = enabled; if (mOnAutorefreshChangeListener != null) mOnAutorefreshChangeListener.onAutorefreshStateChanged(this); } return this; } public Plus1BannerView setViewStateListener( Plus1BannerViewStateListener viewStateListener ) { mViewStateListener = viewStateListener; return this; } public boolean getAutorefreshEnabled() { return mAutorefreshEnabled; } private void setExpanded(boolean orly) { if (mExpanded != orly) { // NOTE: really changed mExpanded = orly; if (mExpanded) mAdAnimator.stopLoading(); if (mOnAutorefreshChangeListener != null) mOnAutorefreshChangeListener.onAutorefreshStateChanged(this); } } public boolean isExpanded() { return mExpanded; } private void init() { if (mInitialized) return; setVisibility(INVISIBLE); // background setBackgroundResource(R.drawable.wp_banner_background); // shild ImageView shild = new ImageView(getContext()); shild.setImageResource(R.drawable.wp_banner_shild); shild.setMaxWidth(9); shild.setLayoutParams( new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL ) ); mAdAnimator = new Plus1AdAnimator(getContext()); addView( mAdAnimator.getBaseView(), new FrameLayout.LayoutParams( getWidth() - 8, FrameLayout.LayoutParams.FILL_PARENT, Gravity.RIGHT ) ); addView(shild); // close button if (isHaveCloseButton()) { Button closeButton = new Button(getContext()); closeButton.setBackgroundResource(R.drawable.wp_banner_close); closeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mClosed = true; setAutorefreshEnabled(false); hide(); } }); addView( closeButton, new FrameLayout.LayoutParams( 18, 17, Gravity.RIGHT ) ); } mInitialized = true; } private Plus1BannerView enableAnimation(float toYDelta) { mShowAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, toYDelta, Animation.RELATIVE_TO_SELF, 0f ); mShowAnimation.setDuration(500); mHideAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, toYDelta ); mHideAnimation.setDuration(500); return this; } private void show() { if (getVisibility() == INVISIBLE) { if (mShowAnimation != null) startAnimation(mShowAnimation); setVisibility(VISIBLE); if (mViewStateListener != null) mViewStateListener.onShowBannerView(); } mAdAnimator.showAd(); } private void hide() { if (getVisibility() == VISIBLE) { if (mHideAnimation != null) startAnimation(mHideAnimation); setVisibility(INVISIBLE); if (mViewStateListener != null) mViewStateListener.onCloseBannerView(); } } public interface OnAutorefreshStateListener { public void onAutorefreshStateChanged(Plus1BannerView view); } }
package raptor.connector.ics; import java.util.StringTokenizer; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import raptor.Raptor; import raptor.chat.ChatType; import raptor.chat.Bugger.BuggerStatus; import raptor.chess.AtomicGame; import raptor.chess.BughouseGame; import raptor.chess.ClassicGame; import raptor.chess.CrazyhouseGame; import raptor.chess.FischerRandomBughouseGame; import raptor.chess.FischerRandomCrazyhouseGame; import raptor.chess.FischerRandomGame; import raptor.chess.Game; import raptor.chess.GameConstants; import raptor.chess.GameFactory; import raptor.chess.LosersGame; import raptor.chess.Move; import raptor.chess.SetupGame; import raptor.chess.SuicideGame; import raptor.chess.Variant; import raptor.chess.pgn.PgnHeader; import raptor.chess.pgn.PgnUtils; import raptor.chess.pgn.TimeTakenForMove; import raptor.chess.util.GameUtils; import raptor.chess.util.ZobristUtils; import raptor.connector.Connector; import raptor.connector.ics.game.message.G1Message; import raptor.connector.ics.game.message.MovesMessage; import raptor.connector.ics.game.message.Style12Message; import raptor.swt.chess.ChessBoardController; import raptor.swt.chess.ChessBoardUtils; import raptor.swt.chess.controller.BughouseSuggestController; import raptor.swt.chess.controller.ExamineController; import raptor.swt.chess.controller.InactiveController; import raptor.swt.chess.controller.ObserveController; import raptor.swt.chess.controller.PlayingController; import raptor.swt.chess.controller.SetupController; import raptor.util.RaptorStringTokenizer; public class IcsUtils implements GameConstants { public static final String ATOMIC_IDENTIFIER = "atomic"; public static final String BLITZ_IDENTIFIER = "blitz"; public static final String BUGHOUSE_IDENTIFIER = "bughouse"; public static final String CHANNEL_STRIP_CHARS = "()~!@? public static final String CRAZYHOUSE_IDENTIFIER = "crazyhouse"; public static final String FISCHER_RANDOM_IDENTIFIER = "wild/fr"; public static final String LEGAL_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 " + "!@ public static final String LIGHTNING_IDENTIFIER = "lightning"; private static final Log LOG = LogFactory.getLog(IcsUtils.class); public static final String LOSERS_IDENTIFIER = "losers"; public static final String STANDARD_IDENTIFIER = "standard"; public static final String STRIP_CHARS = "()~!@?#$%^&*_+|}{'\";/?<>.,:[]1234567890"; public static final String SUICIDE_IDENTIFIER = "suicide"; public static final String UNTIMED_IDENTIFIER = "untimed"; public static final String VALID_PERSON_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String WILD_IDENTIFIER = "wild"; /** * Returns true if a move was added, false if no move was added (This can * occur on a refresh or a game end.). */ public static boolean addCurrentMove(Game game, Style12Message message) { boolean result = false; if (!message.isWhitesMoveAfterMoveIsMade && game.getColorToMove() != WHITE || message.isWhitesMoveAfterMoveIsMade && game.getColorToMove() == WHITE) { // At the end of a game multiple <12> messages are sent. // The are also sent when a refresh is sent. game.setHeader(PgnHeader.WhiteRemainingMillis, "" + message.whiteRemainingTimeMillis); game.setHeader(PgnHeader.BlackRemainingMillis, "" + message.blackRemainingTimeMillis); if (message.timeTakenForLastMoveMillis != 0) { game.getMoveList().get(game.getMoveList().getSize() - 1) .addAnnotation( new TimeTakenForMove( message.timeTakenForLastMoveMillis)); } } else { if (message.san.equals("none")) { Raptor .getInstance() .onError( "Received a none for san in a style 12 event. This should have contained a move."); } else { Move move = game.makeSanMove(message.san); move.addAnnotation(new TimeTakenForMove( message.timeTakenForLastMoveMillis)); } game.setHeader(PgnHeader.WhiteRemainingMillis, "" + message.whiteRemainingTimeMillis); game.setHeader(PgnHeader.BlackRemainingMillis, "" + message.blackRemainingTimeMillis); if (message.isWhitesMoveAfterMoveIsMade) { String lag = StringUtils.defaultString(game .getHeader(PgnHeader.BlackLagMillis), "0"); game.setHeader(PgnHeader.BlackLagMillis, "" + (Long.parseLong(lag) + message.lagInMillis)); } else { String lag = StringUtils.defaultString(game .getHeader(PgnHeader.WhiteLagMillis), "0"); game.setHeader(PgnHeader.WhiteLagMillis, "" + (Long.parseLong(lag) + message.lagInMillis)); } result = true; } if (message.isClockTicking) { game.addState(Game.IS_CLOCK_TICKING_STATE); } else { game.clearState(Game.IS_CLOCK_TICKING_STATE); } return result; } /** * Returns true if the game was adjusted for takebacks. False otherwise. */ public static boolean adjustToTakebacks(Game game, Style12Message message, Connector connector) { boolean result = false; int currentHalfMove = (message.fullMoveNumber - 1) * 2 + (message.isWhitesMoveAfterMoveIsMade ? 0 : 1); if (LOG.isDebugEnabled()) { LOG.debug("adjustToTakebacks calculatedHalfMove " + currentHalfMove + " 12FulLMoveNumber " + message.fullMoveNumber + " 12isWhitesMoveAfter " + message.isWhitesMoveAfterMoveIsMade + " gameHalfMove " + game.getHalfMoveCount()); } if (currentHalfMove != game.getHalfMoveCount() + 1) { if (game.getHalfMoveCount() < currentHalfMove) { if (LOG.isDebugEnabled()) { LOG .debug("Didnt have all the moves needed for rollback. Resetting game and sending moves request."); } resetGame(game, message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); result = true; } else { while (game.getHalfMoveCount() > currentHalfMove) { if (LOG.isDebugEnabled()) { LOG.debug("Rolled back a move."); } if (game.getLastMove() != null) { game.rollback(); } else { resetGame(game, message); connector.sendMessage("moves " + message.gameId, true, ChatType.MOVES); result = false; break; } } if (game.isInState(Game.OBSERVING_EXAMINED_STATE) && game.getMoveList().getSize() == 0) { game.clear(); updateNonPositionFields(game, message); updatePosition(game, message); game.removeHeader(PgnHeader.ECO); game.removeHeader(PgnHeader.Opening); } result = true; } // At the end of a game multiple <12> messages are sent. // The are also sent when a refresh is sent. game.setHeader(PgnHeader.WhiteRemainingMillis, "" + message.whiteRemainingTimeMillis); game.setHeader(PgnHeader.BlackRemainingMillis, "" + message.blackRemainingTimeMillis); } if (message.isClockTicking) { game.addState(Game.IS_CLOCK_TICKING_STATE); } else { game.clearState(Game.IS_CLOCK_TICKING_STATE); } return result; } public static ChessBoardController buildController(Game game, Connector connector) { return buildController(game, connector, false); } public static ChessBoardController buildController(Game game, Connector connector, boolean isBughouseOtherBoard) { ChessBoardController controller = null; if (game.isInState(Game.OBSERVING_STATE) || game.isInState(Game.OBSERVING_EXAMINED_STATE)) { if (isBughouseOtherBoard) { if (((BughouseGame) game).getOtherBoard().isInState( Game.PLAYING_STATE)) { Game otherGame = ((BughouseGame) game).getOtherBoard(); boolean isPartnerWhite = !StringUtils.equals(otherGame .getHeader(PgnHeader.White), connector .getUserName()); controller = new BughouseSuggestController(game, connector, isPartnerWhite); } else { controller = new ObserveController(game, connector); } } else { controller = new ObserveController(game, connector); } } else if (game.isInState(Game.SETUP_STATE)) { controller = new SetupController(game, connector); } else if (game.isInState(Game.EXAMINING_STATE)) { controller = new ExamineController(game, connector); } else if (game.isInState(Game.PLAYING_STATE)) { controller = new PlayingController(game, connector); } else { // Used for sposition. controller = new InactiveController(game); } return controller; } /** * Cleans up the message by ensuring only \n is used as a line terminator. * \r\n and \r may be used depending on the operating system. */ public static String cleanupMessage(String message) { return StringUtils.remove(message, '\r'); } /** * Clears out all the games position state. */ public static void clearGamePosition(Game game) { game.clear(); } public static Game createExaminedGame( Style12Message gameStateStyle12Message, MovesMessage movesMessage) { Game result = null; if (movesMessage.style12 == null) { result = GameFactory .createStartingPosition(identifierToGameType(movesMessage.gameType)); } else { result = createGameFromVariant( identifierToGameType(movesMessage.gameType), gameStateStyle12Message, false); updatePosition(result, movesMessage.style12); if (result.getVariant() == Variant.fischerRandom) { ((FischerRandomGame) result).initialPositionIsSet(); } else if (result.getVariant() == Variant.fischerRandomBughouse) { ((FischerRandomBughouseGame) result).initialPositionIsSet(); } else if (result.getVariant() == Variant.fischerRandomCrazyhouse) { ((FischerRandomCrazyhouseGame) result).initialPositionIsSet(); } updateNonPositionFields(result, movesMessage.style12); result.setHeader(PgnHeader.FEN, result.toFen()); } result.addState(Game.UPDATING_SAN_STATE); result.addState(Game.UPDATING_ECO_HEADERS_STATE); result.setId(movesMessage.gameId); for (int i = 0; i < movesMessage.moves.length; i++) { try { if (result.isInState(Game.DROPPABLE_STATE)) { result.setDropCount(WHITE, PAWN, 1); result.setDropCount(WHITE, QUEEN, 1); result.setDropCount(WHITE, ROOK, 1); result.setDropCount(WHITE, KNIGHT, 1); result.setDropCount(WHITE, BISHOP, 1); result.setDropCount(BLACK, PAWN, 1); result.setDropCount(BLACK, QUEEN, 1); result.setDropCount(BLACK, ROOK, 1); result.setDropCount(BLACK, KNIGHT, 1); result.setDropCount(BLACK, BISHOP, 1); } Move move = result.makeSanMove(movesMessage.moves[i]); move.addAnnotation(new TimeTakenForMove( movesMessage.timePerMove[i])); } catch (IllegalArgumentException iae) { LOG.error("Could not parse san", iae); Raptor.getInstance().onError("Error update game with moves", iae); } } updateNonPositionFields(result, gameStateStyle12Message); result.setHeader(PgnHeader.Date, PgnUtils.longToPgnDate(System .currentTimeMillis())); result.setHeader(PgnHeader.Round, "?"); result.setHeader(PgnHeader.Site, "freechess.org"); result.setHeader(PgnHeader.TimeControl, PgnUtils .timeIncMillisToTimeControl(0, 0)); result.setHeader(PgnHeader.BlackRemainingMillis, "" + 0); result.setHeader(PgnHeader.WhiteRemainingMillis, "" + 0); result.setHeader(PgnHeader.WhiteClock, PgnUtils.timeToClock(0)); result.setHeader(PgnHeader.BlackClock, PgnUtils.timeToClock(0)); result.setHeader(PgnHeader.BlackElo, ""); result.setHeader(PgnHeader.WhiteElo, ""); result.setHeader(PgnHeader.Event, "Examining " + movesMessage.gameType + " game"); result.setHeader(PgnHeader.Variant, result.getVariant().toString()); return result; } public static Game createGame(G1Message g1, Style12Message style12, boolean isBics) { Variant variant = IcsUtils.identifierToGameType(g1.gameTypeDescription); Game result = createGameFromVariant(variant, style12, isBics); result.setId(g1.gameId); result.addState(Game.UPDATING_SAN_STATE); result.addState(Game.UPDATING_ECO_HEADERS_STATE); result.setHeader(PgnHeader.Date, PgnUtils.longToPgnDate(System .currentTimeMillis())); result.setHeader(PgnHeader.Round, "?"); result.setHeader(PgnHeader.Site, "freechess.org"); result.setHeader(PgnHeader.TimeControl, PgnUtils .timeIncMillisToTimeControl(g1.initialWhiteTimeMillis, g1.initialWhiteIncMillis)); result.setHeader(PgnHeader.BlackRemainingMillis, "" + g1.initialBlackTimeMillis); result.setHeader(PgnHeader.WhiteRemainingMillis, "" + g1.initialWhiteTimeMillis); result.setHeader(PgnHeader.WhiteClock, PgnUtils .timeToClock(g1.initialWhiteTimeMillis)); result.setHeader(PgnHeader.BlackClock, PgnUtils .timeToClock(g1.initialBlackTimeMillis)); result.setHeader(PgnHeader.BlackElo, g1.blackRating); result.setHeader(PgnHeader.WhiteElo, g1.whiteRating); result.setHeader(PgnHeader.Event, g1.initialWhiteTimeMillis / 60000 + " " + g1.initialWhiteIncMillis / 1000 + " " + (!g1.isRated ? "unrated" : "rated") + " " + (g1.isPrivate ? "private " : "") + g1.gameTypeDescription); return result; } public static Game createGame(Style12Message message, String entireMessage) { if (message.relation == Style12Message.EXAMINING_GAME_RELATION) { boolean isSetup = entireMessage.contains("Entering setup mode.\n"); Game game = isSetup ? new SetupGame() : new ClassicGame(); game.setId(message.gameId); game.addState(Game.UPDATING_SAN_STATE); game.addState(Game.UPDATING_ECO_HEADERS_STATE); game.setHeader(PgnHeader.Date, PgnUtils.longToPgnDate(System .currentTimeMillis())); game.setHeader(PgnHeader.Round, "?"); game.setHeader(PgnHeader.Site, "freechess.org"); game.setHeader(PgnHeader.TimeControl, PgnUtils .timeIncMillisToTimeControl(0, 0)); game.setHeader(PgnHeader.BlackRemainingMillis, "" + 0); game.setHeader(PgnHeader.WhiteRemainingMillis, "" + 0); game.setHeader(PgnHeader.WhiteClock, PgnUtils.timeToClock(0)); game.setHeader(PgnHeader.BlackClock, PgnUtils.timeToClock(0)); game.setHeader(PgnHeader.BlackElo, ""); game.setHeader(PgnHeader.WhiteElo, ""); game.setHeader(PgnHeader.Event, isSetup ? "Setting Up Position" : "Examining Game"); updateNonPositionFields(game, message); updatePosition(game, message); verifyLegal(game); return game; } else if (message.relation == Style12Message.ISOLATED_POSITION_RELATION) { Game game = new ClassicGame(); game.setId(message.gameId); game.addState(Game.UPDATING_SAN_STATE); game.addState(Game.UPDATING_ECO_HEADERS_STATE); game.setHeader(PgnHeader.Date, PgnUtils.longToPgnDate(System .currentTimeMillis())); game.setHeader(PgnHeader.Round, "?"); game.setHeader(PgnHeader.Site, "freechess.org"); game.setHeader(PgnHeader.TimeControl, PgnUtils .timeIncMillisToTimeControl(0, 0)); game.setHeader(PgnHeader.BlackRemainingMillis, "" + 0); game.setHeader(PgnHeader.WhiteRemainingMillis, "" + 0); game.setHeader(PgnHeader.WhiteClock, PgnUtils.timeToClock(0)); game.setHeader(PgnHeader.BlackClock, PgnUtils.timeToClock(0)); game.setHeader(PgnHeader.BlackElo, ""); game.setHeader(PgnHeader.WhiteElo, ""); game.setHeader(PgnHeader.Event, "Isolated Position"); updateNonPositionFields(game, message); updatePosition(game, message); verifyLegal(game); return game; } else { LOG.error("Cant create an examined game for relation " + message.relation); throw new IllegalStateException( "Cant created a examined or setup game from a game with relation " + message.relation); } } public static Game createGameFromVariant(Variant variant, Game existingGame) { Game result = null; switch (variant) { case classic: result = new ClassicGame(); break; case wild: result = new ClassicGame(); result.setHeader(PgnHeader.Variant, Variant.wild.name()); break; case suicide: result = new SuicideGame(); break; case losers: result = new LosersGame(); break; case atomic: result = new AtomicGame(); break; case crazyhouse: result = existingGame instanceof FischerRandomCrazyhouseGame ? new FischerRandomCrazyhouseGame() : new CrazyhouseGame(); break; case bughouse: result = existingGame instanceof FischerRandomBughouseGame ? new FischerRandomBughouseGame() : new BughouseGame(); break; case fischerRandom: result = new FischerRandomGame(); break; default: LOG.warn("Unknown variant: " + variant + " assuming its classical"); result = new ClassicGame(); } return result; } public static Game createGameFromVariant(Variant variant, Style12Message message, boolean isBicsMessage) { Game result = null; boolean isFrBugOrFrZh = false; if (isBicsMessage && (variant == Variant.bughouse || variant == Variant.crazyhouse)) { isFrBugOrFrZh = message.position[0][0] != ROOK || message.position[0][1] != KNIGHT || message.position[0][2] != BISHOP || message.position[0][3] != QUEEN || message.position[0][4] != KING || message.position[0][5] != BISHOP || message.position[0][6] != KNIGHT || message.position[0][7] != ROOK; } switch (variant) { case classic: result = new ClassicGame(); break; case wild: result = new ClassicGame(); result.setHeader(PgnHeader.Variant, Variant.wild.name()); break; case suicide: result = new SuicideGame(); break; case losers: result = new LosersGame(); break; case atomic: result = new AtomicGame(); break; case crazyhouse: result = isFrBugOrFrZh ? new FischerRandomCrazyhouseGame() : new CrazyhouseGame(); break; case bughouse: result = isFrBugOrFrZh ? new FischerRandomBughouseGame() : new BughouseGame(); break; case fischerRandom: result = new FischerRandomGame(); break; default: LOG.warn("Unsupported variant: " + variant + " assuming its Classic"); result = new ClassicGame(); } return result; } public static void filterOutbound(StringBuilder message) { for (int i = 0; i < message.length(); i++) { char currentChar = message.charAt(i); if (LEGAL_CHARACTERS.indexOf(currentChar) == -1) { if (currentChar > 256) { int charAsInt = currentChar; String stringVersion = Integer.toString(charAsInt, 16); String replacement = "&#x" + stringVersion + ";"; message.replace(i, i + 1, replacement); i += replacement.length() - 1; } else { message.deleteCharAt(i); i } } } } public static BuggerStatus getBuggserStatus(String status) { if (status.equals(":")) { return BuggerStatus.Closed; } else if (status.equals("^")) { return BuggerStatus.Playing; } else if (status.equals(".")) { return BuggerStatus.Idle; } else if (status.equals("~")) { return BuggerStatus.Simul; } else if (status.equals(" return BuggerStatus.Examining; } else if (status.equals("&")) { return BuggerStatus.InTourney; } else { return BuggerStatus.Available; } } /** * Returns the game type constant for the specified identifier. * */ public static Variant identifierToGameType(String identifier) { Variant result = null; if (identifier.indexOf(SUICIDE_IDENTIFIER) != -1) { result = Variant.suicide; } else if (identifier.indexOf(BUGHOUSE_IDENTIFIER) != -1) { result = Variant.bughouse; } else if (identifier.indexOf(CRAZYHOUSE_IDENTIFIER) != -1) { result = Variant.crazyhouse; } else if (identifier.indexOf(STANDARD_IDENTIFIER) != -1) { result = Variant.classic; } else if (identifier.indexOf(FISCHER_RANDOM_IDENTIFIER) != -1) { result = Variant.fischerRandom; } else if (identifier.indexOf(WILD_IDENTIFIER) != -1) { result = Variant.wild; } else if (identifier.indexOf(LIGHTNING_IDENTIFIER) != -1) { result = Variant.classic; } else if (identifier.indexOf(BLITZ_IDENTIFIER) != -1) { result = Variant.classic; } else if (identifier.indexOf(ATOMIC_IDENTIFIER) != -1) { result = Variant.atomic; } else if (identifier.indexOf(LOSERS_IDENTIFIER) != -1) { result = Variant.losers; } else if (identifier.indexOf(UNTIMED_IDENTIFIER) != -1) { result = Variant.classic; } else { LOG.warn("Unknown identifier " + identifier + " encountered. Assuming its classic."); result = Variant.classic; } return result; } /** * Removes the ICS channel wrapping around a specified channel word * returning only the channel number. * * Returns -1 if the specified word is not a channel. */ public static boolean isLikelyChannel(String word) { boolean result = false; if (word != null) { RaptorStringTokenizer tok = new RaptorStringTokenizer(word, CHANNEL_STRIP_CHARS, true); if (tok.hasMoreTokens()) { String current = tok.nextToken(); try { int channel = Integer.parseInt(current); return channel >= 0 && channel <= 255; } catch (NumberFormatException nfe) { if (tok.hasMoreTokens()) { try { current = tok.nextToken(); int channel = Integer.parseInt(current); return channel >= 0 && channel <= 255; } catch (NumberFormatException nfe2) { if (tok.hasMoreTokens()) { try { current = tok.nextToken(); int channel = Integer.parseInt(current); return channel >= 0 && channel <= 255; } catch (NumberFormatException nfe3) { if (tok.hasMoreTokens()) { try { current = tok.nextToken(); int channel = Integer .parseInt(current); return channel >= 0 && channel <= 255; } catch (NumberFormatException nfe4) { } } } } } } } } } return result; } public static boolean isLikelyGameId(String word) { boolean result = false; if (word != null) { try { int gameId = Integer.parseInt(stripWord(word)); return gameId > 0 && gameId <= 5000; } catch (NumberFormatException nfe) { return false; } } return result; } /** * Returns true if the specified word is probably a persons name. */ public static boolean isLikelyPerson(String word) { String strippedWord = stripWord(word); if (word != null && strippedWord.length() > 2) { boolean result = true; for (int i = 0; result && i < strippedWord.length(); i++) { result = VALID_PERSON_CHARS.indexOf(word.charAt(i)) != -1; } return result; } else { return false; } } /** * Maciejg format, named after him because of his finger notes. Unicode * chars are represented as &#x3b1; &#x3b2; &#x3b3; &#x3b4; &#x3b5; &#x3b6; * unicode equivalent \u03B1,\U03B2,... */ public static String maciejgFormatToUnicode(String inputString) { StringBuilder builder = new StringBuilder(inputString); int unicodePrefix = 0; while ((unicodePrefix = builder.indexOf("&#x", unicodePrefix)) != -1) { int endIndex = builder.indexOf(";", unicodePrefix); if (endIndex == -1) { break; } String maciejgWord = builder.substring(unicodePrefix + 3, endIndex); maciejgWord = StringUtils.replaceChars(maciejgWord, " \\\n", "") .toUpperCase(); if (maciejgWord.length() <= 5) { try { int intValue = Integer.parseInt(maciejgWord, 16); String unicode = new String(new char[] { (char) intValue }); builder.replace(unicodePrefix, endIndex + 1, unicode); } catch (NumberFormatException nfe) { unicodePrefix = endIndex + 1; } } else { unicodePrefix = endIndex + 1; } } return builder.toString(); } /** * Removes all line breaks and excessive spaces from the specified message. * * @param msg * THe message to remove line breaks from. * @return The message without any line breaks. */ public static String removeLineBreaks(String msg) { StringBuilder result = new StringBuilder(msg.length()); RaptorStringTokenizer tok = new RaptorStringTokenizer(msg, "\n\\ ", true); if (tok.hasMoreTokens()) { result.append(tok.nextToken()); } while (tok.hasMoreTokens()) { result.append(" " + tok.nextToken()); } return result.toString(); } public static void resetGame(Game game, Style12Message message) { IcsUtils.clearGamePosition(game); IcsUtils.updateNonPositionFields(game, message); IcsUtils.updatePosition(game, message); verifyLegal(game); } public static String stripChannel(String word) { String result = null; if (word != null) { RaptorStringTokenizer tok = new RaptorStringTokenizer(word, CHANNEL_STRIP_CHARS, true); if (tok.hasMoreTokens()) { String current = tok.nextToken(); try { int channel = Integer.parseInt(current); if (channel >= 0 && channel <= 255) { return "" + channel; } } catch (NumberFormatException nfe) { if (tok.hasMoreTokens()) { try { current = tok.nextToken(); int channel = Integer.parseInt(current); if (channel >= 0 && channel <= 255) { return "" + channel; } } catch (NumberFormatException nfe2) { if (tok.hasMoreTokens()) { try { current = tok.nextToken(); int channel = Integer.parseInt(current); if (channel >= 0 && channel <= 255) { return "" + channel; } } catch (NumberFormatException nfe3) { if (tok.hasMoreTokens()) { try { current = tok.nextToken(); int channel = Integer .parseInt(current); if (channel >= 0 && channel <= 255) { return "" + channel; } } catch (NumberFormatException nfe4) { } } } } } } } } } return result; } public static String stripGameId(String gameId) { return gameId; } public static String stripTitles(String playerName) { StringTokenizer stringtokenizer = new StringTokenizer(playerName, "()~!@ if (stringtokenizer.hasMoreTokens()) { return stringtokenizer.nextToken(); } else { return playerName; } } /** * Returns the word with all characters in: ()~!@?#$%^&*_+|}{'\";/?<>., * :[]1234567890\t\r\n removed. */ public static String stripWord(String word) { if (word != null) { RaptorStringTokenizer stringtokenizer = new RaptorStringTokenizer( word, STRIP_CHARS, true); if (stringtokenizer.hasMoreTokens()) { return stringtokenizer.nextToken(); } else { return word; } } return null; } /** * Converts a time in: (0:00.000) mmm:ss.MMM format into a long value * representing milliseconds. * * @param timeString * The time string. * @return The result. */ public static final long timeToLong(String timeString) { RaptorStringTokenizer tok = new RaptorStringTokenizer(timeString, "(:.)", true); long minutes = Integer.parseInt(tok.nextToken()); long seconds = Integer.parseInt(tok.nextToken()); long millis = Integer.parseInt(tok.nextToken()); return minutes * 1000 * 60 + seconds * 1000 + millis; } /** * Updates the moves that are missing in the game to the ones in the move * message. */ public static void updateGamesMoves(Game game, MovesMessage message) { int halfMoveCountGameStartedOn = game.getHalfMoveCount() - game.getMoveList().getSize(); if (message.moves.length > 0 && halfMoveCountGameStartedOn != 0) { Game gameClone = null; if (message.style12 == null) { gameClone = GameFactory.createStartingPosition(game .getVariant()); } else { gameClone = createGameFromVariant(game.getVariant(), game); updatePosition(gameClone, message.style12); if (gameClone.getVariant() == Variant.fischerRandom) { ((FischerRandomGame) gameClone).initialPositionIsSet(); } else if (gameClone.getVariant() == Variant.fischerRandomBughouse) { ((FischerRandomBughouseGame) gameClone) .initialPositionIsSet(); } else if (gameClone.getVariant() == Variant.fischerRandomCrazyhouse) { ((FischerRandomCrazyhouseGame) gameClone) .initialPositionIsSet(); } updateNonPositionFields(gameClone, message.style12); game.setHeader(PgnHeader.FEN, gameClone.toFen()); } gameClone.addState(Game.UPDATING_SAN_STATE); gameClone.addState(Game.UPDATING_ECO_HEADERS_STATE); for (int i = 0; i < halfMoveCountGameStartedOn; i++) { try { if (gameClone.isInState(Game.DROPPABLE_STATE)) { gameClone.setDropCount(WHITE, PAWN, 1); gameClone.setDropCount(WHITE, QUEEN, 1); gameClone.setDropCount(WHITE, ROOK, 1); gameClone.setDropCount(WHITE, KNIGHT, 1); gameClone.setDropCount(WHITE, BISHOP, 1); gameClone.setDropCount(BLACK, PAWN, 1); gameClone.setDropCount(BLACK, QUEEN, 1); gameClone.setDropCount(BLACK, ROOK, 1); gameClone.setDropCount(BLACK, KNIGHT, 1); gameClone.setDropCount(BLACK, BISHOP, 1); } Move move = gameClone.makeSanMove(message.moves[i]); move.addAnnotation(new TimeTakenForMove( message.timePerMove[i])); } catch (IllegalArgumentException iae) { LOG.error("Could not parse san", iae); Raptor.getInstance().onError( "Error update game with moves", iae); } } Move[] moves = gameClone.getMoveList().asArray(); game.getMoveList().prepend(moves); game.setInitialEpSquare(gameClone.getInitialEpSquare()); if (StringUtils.isBlank(game.getHeader(PgnHeader.ECO)) && StringUtils.isNotBlank(gameClone .getHeader(PgnHeader.ECO))) { game.setHeader(PgnHeader.ECO, gameClone .getHeader(PgnHeader.ECO)); } if (StringUtils.isBlank(game.getHeader(PgnHeader.Opening)) && StringUtils.isNotBlank(gameClone .getHeader(PgnHeader.Opening))) { game.setHeader(PgnHeader.Opening, gameClone .getHeader(PgnHeader.Opening)); } } else if (message.moves.length == 0 && message.style12 != null) { game.clear(); updateNonPositionFields(game, message.style12); updatePosition(game, message.style12); game.setHeader(PgnHeader.FEN, game.toFen()); game.removeHeader(PgnHeader.ECO); game.removeHeader(PgnHeader.Opening); } } /** * Handles updating everything but the position related fields in the game. * i.e. the bitboards,pieces, etc. */ public static void updateNonPositionFields(Game game, Style12Message message) { switch (message.relation) { case Style12Message.EXAMINING_GAME_RELATION: game.addState(Game.EXAMINING_STATE); break; case Style12Message.ISOLATED_POSITION_RELATION: break; case Style12Message.OBSERVING_EXAMINED_GAME_RELATION: game.addState(Game.OBSERVING_EXAMINED_STATE); break; case Style12Message.OBSERVING_GAME_RELATION: game.addState(Game.OBSERVING_STATE); break; case Style12Message.PLAYING_MY_MOVE_RELATION: case Style12Message.PLAYING_OPPONENTS_MOVE_RELATION: game.addState(Game.PLAYING_STATE); break; } if (message.isClockTicking) { game.addState(Game.IS_CLOCK_TICKING_STATE); } else { game.clearState(Game.IS_CLOCK_TICKING_STATE); } game.addState(Game.ACTIVE_STATE); game .setHeader(PgnHeader.Black, IcsUtils .stripTitles(message.blackName)); game .setHeader(PgnHeader.White, IcsUtils .stripTitles(message.whiteName)); game.setHeader(PgnHeader.WhiteRemainingMillis, "" + message.whiteRemainingTimeMillis); game.setHeader(PgnHeader.BlackRemainingMillis, "" + message.blackRemainingTimeMillis); game .setColorToMove(message.isWhitesMoveAfterMoveIsMade ? WHITE : BLACK); game.setCastling(WHITE, message.canWhiteCastleKSide && message.canWhiteCastleQSide ? CASTLE_BOTH : message.canWhiteCastleKSide ? CASTLE_SHORT : message.canWhiteCastleQSide ? CASTLE_LONG : CASTLE_NONE); game.setCastling(BLACK, message.canBlackCastleKSide && message.canBlackCastleQSide ? CASTLE_BOTH : message.canBlackCastleKSide ? CASTLE_SHORT : message.canBlackCastleQSide ? CASTLE_LONG : CASTLE_NONE); if (message.doublePawnPushFile == -1) { game.setEpSquare(EMPTY_SQUARE); game.setInitialEpSquare(EMPTY_SQUARE); } else { int doublePawnPushSquare = GameUtils.getSquare( message.isWhitesMoveAfterMoveIsMade ? 4 : 5, message.doublePawnPushFile); game.setEpSquare(doublePawnPushSquare); game.setInitialEpSquare(doublePawnPushSquare); } game.setFiftyMoveCount(message.numberOfMovesSinceLastIrreversible); int fullMoveCount = message.fullMoveNumber; game .setHalfMoveCount(game.getColorToMove() == BLACK ? fullMoveCount * 2 - 1 : fullMoveCount * 2 - 2); game.incrementRepCount(); } /** * Should be invoked after the castling,EP,and to move data has been set. */ public static void updatePosition(Game game, Style12Message style12) { for (int i = 0; i < style12.position.length; i++) { for (int j = 0; j < style12.position[i].length; j++) { if (style12.position[i][j] != EMPTY) { int square = GameUtils.getSquare(i, j); int pieceColor = ChessBoardUtils .isWhitePiece(style12.position[i][j]) ? WHITE : BLACK; int piece = ChessBoardUtils .pieceFromColoredPiece(style12.position[i][j]); long squareBB = GameUtils.getBitboard(square); game.setPieceCount(pieceColor, piece, game.getPieceCount( pieceColor, piece) + 1); game.getBoard()[square] = piece; game.setColorBB(pieceColor, game.getColorBB(pieceColor) | squareBB); game.setOccupiedBB(game.getOccupiedBB() | squareBB); game.setPieceBB(pieceColor, piece, game.getPieceBB( pieceColor, piece) | squareBB); } } } game.setEmptyBB(~game.getOccupiedBB()); game.setNotColorToMoveBB(~game.getColorBB(game.getColorToMove())); game.setZobristPositionHash(ZobristUtils.zobristHashPositionOnly(game)); game.setZobristGameHash(game.getZobristPositionHash() ^ ZobristUtils.zobrist(game.getColorToMove(), game .getEpSquare(), game.getCastling(WHITE), game .getCastling(BLACK))); if (game.isInState(Game.SETUP_STATE)) { game.setPieceCount(WHITE, PAWN, 1); game.setPieceCount(WHITE, KNIGHT, 1); game.setPieceCount(WHITE, BISHOP, 1); game.setPieceCount(WHITE, ROOK, 1); game.setPieceCount(WHITE, QUEEN, 1); game.setPieceCount(WHITE, KING, 1); game.setPieceCount(BLACK, PAWN, 1); game.setPieceCount(BLACK, KNIGHT, 1); game.setPieceCount(BLACK, BISHOP, 1); game.setPieceCount(BLACK, ROOK, 1); game.setPieceCount(BLACK, QUEEN, 1); game.setPieceCount(BLACK, KING, 1); } } public static void verifyLegal(Game game) { if (!game.isLegalPosition()) { throw new IllegalStateException("Position is not legal: " + game.toString()); } } protected void replaceMaciejgUnicodeWithUnicode() { } }
package ai.h2o.automl; import ai.h2o.automl.strategies.initial.InitModel; import hex.Model; import hex.ModelBuilder; import water.*; import water.api.KeyV3; import water.fvec.Frame; import java.util.Arrays; /** * Initial draft of AutoML * * AutoML is a node-local driver class that is responsible for managing multiple threads * of execution in an effort to discover an optimal supervised model for some given * (dataset, response, loss) combo. */ public final class AutoML extends Keyed<AutoML> implements H2ORunnable { private final String _datasetName; // dataset name private final Frame _fr; // all learning on this frame private final int _response; // response column, -1 for no response column private final String _loss; // overarching loss to minimize (meta loss) private final long _maxTime; // maximum amount of time allotted to automl private final double _minAcc; // minimum accuracy to achieve private final boolean _ensemble; // allow ensembles? private final models[] _modelEx; // model types to exclude; e.g. don't allow DL private final boolean _allowMutations; // allow for INPLACE mutations on input frame FrameMeta _fm; // metadata for _fr private boolean _isClassification; enum models { RF, GBM, GLM, GLRM, DL, KMEANS } // consider EnumSet public AutoML(Key<AutoML> key, String datasetName, Frame fr, int response, String loss, long maxTime, double minAccuracy, boolean ensemble, String[] modelExclude, boolean tryMutations) { super(key); _datasetName=datasetName; _fr=fr; _response=response; _loss=loss; _maxTime=maxTime; _minAcc=minAccuracy; _ensemble=ensemble; _modelEx=modelExclude==null?null:new models[modelExclude.length]; if( modelExclude!=null ) for( int i=0; i<modelExclude.length; ++i ) _modelEx[i] = models.valueOf(modelExclude[i]); _allowMutations=tryMutations; } // used to launch the AutoML asynchronously @Override public void run() { learn(); } // manager thread: // 1. Do extremely cursory pass over data and gather only the most basic information. // During this pass, AutoML will learn how timely it will be to do more info // gathering on _fr. There's already a number of interesting stats available // thru the rollups, so no need to do too much too soon. // 2. Build a very dumb RF (with stopping_rounds=1, stopping_tolerance=0.01) // 3. TODO: refinement passes and strategy selection public void learn() { // step 1: gather initial frame metadata and guess the problem type _fm = new FrameMeta(_fr, _response, _datasetName).computeFrameMetaPass1(); _isClassification = _fm.isClassification(); // step 2: build a fast RF ModelBuilder initModel = selectInitial(_fm); initModel._parms._ignored_columns = _fm.ignoredCols(); Model m = build(initModel); // need to track this... System.out.println("bink"); // gather more data? build more models? start applying transforms? what next ...? } public Key<Model> getLeaderKey() { final Value val = DKV.get(LEADER); if( val==null ) return null; ModelLeader ml = val.get(); return ml._leader; } public void delete() { for(Model m: models()) m.delete(); DKV.remove(MODELLIST); DKV.remove(LEADER); } private ModelBuilder selectInitial(FrameMeta fm) { // may use _isClassification so not static method return InitModel.initRF(fm._fr, fm.response()._name); } // track models built by automl public static final Key<Model> MODELLIST = Key.make(" AutoMLModelList ", (byte) 0, (byte) 2 /*builtin key*/, false); // public for the test static class ModelList extends Keyed { Key<Model>[] _models; ModelList() { super(MODELLIST); _models = new Key[0]; } @Override protected long checksum_impl() { throw H2O.fail("no such method for ModelList"); } } static Model[] models() { final Value val = DKV.get(MODELLIST); if( val==null ) return new Model[0]; ModelList ml = val.get(); Model[] models = new Model[ml._models.length]; int j=0; for( int i=0; i<ml._models.length; i++ ) { final Value model = DKV.get(ml._models[i]); if( model != null ) models[j++] = model.get(); } assert j==models.length; // All models still exist return models; } public static final Key<Model> LEADER = Key.make(" AutoMLModelLeader ", (byte) 0, (byte) 2, false); static class ModelLeader extends Keyed { Key<Model> _leader; ModelLeader() { super(LEADER); _leader = null; } @Override protected long checksum_impl() { throw H2O.fail("no such method for ModelLeader"); } } static Model leader() { final Value val = DKV.get(LEADER); if( val==null ) return null; ModelLeader ml = val.get(); final Value leaderModelKey = DKV.get(ml._leader); assert leaderModelKey!=null; // if the LEADER is in the DKV, then there better be a model! return leaderModelKey.get(); } private void updateLeader(Model m) { Model leader = leader(); final Key leaderKey; if (leader == null) leaderKey = m._key; else { // compare leader to m; get the key that minimizes this._loss leaderKey = leader._key; } // update the leader if needed if (leader == null || leaderKey.equals(leader._key) ) { new TAtomic<ModelLeader>() { @Override public ModelLeader atomic(ModelLeader old) { if (old == null) old = new ModelLeader(); old._leader = leaderKey; return old; } }.invoke(LEADER); } } // all model builds by AutoML call into this // expected to only ever have a single AutoML instance going at a time Model build(ModelBuilder mb) { Model m = (Model)mb.trainModel().get(); final Key<Model> modelKey = m._key; new TAtomic<ModelList>() { @Override public ModelList atomic(ModelList old) { if( old == null ) old = new ModelList(); Key<Model>[] models = old._models; old._models = Arrays.copyOf(models, models.length + 1); old._models[models.length] = modelKey; return old; } }.invoke(MODELLIST); updateLeader(m); return m; } // satisfy typing for job return type... public static class AutoMLKeyV3 extends KeyV3<Iced, AutoMLKeyV3, AutoML>{ public AutoMLKeyV3(){} public AutoMLKeyV3(Key<AutoML> key) { super(key); } } @Override public Class<AutoMLKeyV3> makeSchema() { return AutoMLKeyV3.class; } }
package grakn.core.graql.reasoner.cache; import com.google.common.collect.HashMultimap; import com.google.common.collect.Sets; import grakn.core.concept.answer.ConceptMap; import grakn.core.concept.type.SchemaConcept; import grakn.core.graql.reasoner.query.ReasonerAtomicQuery; import grakn.core.graql.reasoner.query.ReasonerQueries; import grakn.core.graql.reasoner.unifier.MultiUnifier; import grakn.core.graql.reasoner.unifier.MultiUnifierImpl; import grakn.core.graql.reasoner.unifier.UnifierType; import grakn.core.graql.reasoner.utils.Pair; import graql.lang.statement.Variable; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.stream.Collectors.toSet; public abstract class SemanticCache< QE, SE extends Set<ConceptMap>> extends AtomicQueryCacheBase<QE, SE> { final private HashMultimap<SchemaConcept, QE> families = HashMultimap.create(); final private HashMultimap<QE, QE> parents = HashMultimap.create(); UnifierType semanticUnifier(){ return UnifierType.RULE;} @Override public void clear(){ super.clear(); families.clear(); parents.clear(); } /** * Propagate ALL answers between entries provided they satisfy the corresponding semantic difference. * * @param parentEntry parent entry we want to propagate answers from * @param childEntry cache entry we want to propagate answers to * @param inferred true if inferred answers should be propagated * @return true if new answers were found during propagation */ protected abstract boolean propagateAnswers(CacheEntry<ReasonerAtomicQuery, SE> parentEntry, CacheEntry<ReasonerAtomicQuery, SE> childEntry, boolean inferred); protected abstract Stream<ConceptMap> entryToAnswerStream(CacheEntry<ReasonerAtomicQuery, SE> entry); protected abstract Pair<Stream<ConceptMap>, MultiUnifier> entryToAnswerStreamWithUnifier(ReasonerAtomicQuery query, CacheEntry<ReasonerAtomicQuery, SE> entry); /** * @param query to be checked for answers * @return true if cache answers the input query */ protected abstract boolean answersQuery(ReasonerAtomicQuery query); abstract CacheEntry<ReasonerAtomicQuery, SE> createEntry(ReasonerAtomicQuery query, Set<ConceptMap> answers); private CacheEntry<ReasonerAtomicQuery, SE> addEntry(CacheEntry<ReasonerAtomicQuery, SE> entry){ CacheEntry<ReasonerAtomicQuery, SE> cacheEntry = putEntry(entry); ReasonerAtomicQuery query = cacheEntry.query(); updateFamily(query); computeParents(query); propagateAnswersToQuery(query, cacheEntry, query.isGround()); return cacheEntry; } @Override public boolean isComplete(ReasonerAtomicQuery query){ return super.isComplete(query) || getParents(query).stream().anyMatch(q -> super.isComplete(keyToQuery(q))); } /** * propagate answers within the cache (children fetch answers from parents) */ public void propagateAnswers(){ queries().stream() .filter(this::isComplete) .forEach(child-> { CacheEntry<ReasonerAtomicQuery, SE> childEntry = getEntry(child); if (childEntry != null) { propagateAnswersToQuery(child, childEntry, true); ackCompleteness(child); } }); } private Set<QE> getParents(ReasonerAtomicQuery child){ Set<QE> parents = this.parents.get(queryToKey(child)); if (parents.isEmpty()) parents = computeParents(child); return parents.stream() .filter(parent -> child.subsumes(keyToQuery(parent))) .collect(toSet()); } /** * @param query to find * @return queries that belong to the same family as input query */ private Set<QE> getFamily(ReasonerAtomicQuery query){ SchemaConcept schemaConcept = query.getAtom().getSchemaConcept(); if (schemaConcept == null) return new HashSet<>(); Set<QE> family = families.get(schemaConcept); return family != null? family.stream().filter(q -> !q.equals(queryToKey(query))).collect(toSet()) : new HashSet<>(); } private void updateFamily(ReasonerAtomicQuery query){ SchemaConcept schemaConcept = query.getAtom().getSchemaConcept(); if (schemaConcept != null){ Set<QE> familyEntry = families.get(schemaConcept); QE familyQuery = queryToKey(query); if (familyEntry != null){ familyEntry.add(familyQuery); } else { families.put(schemaConcept, familyQuery); } } } private Set<QE> computeParents(ReasonerAtomicQuery child){ Set<QE> family = getFamily(child); Set<QE> computedParents = new HashSet<>(); family.stream() .map(this::keyToQuery) .filter(child::subsumes) .map(this::queryToKey) .peek(computedParents::add) .forEach(parent -> parents.put(queryToKey(child), parent)); return computedParents; } /** * NB: uses getEntry * NB: target and childMatch.query() are in general not the same hence explicit arguments * @param target query we want propagate the answers to * @param childMatch entry to which we want to propagate answers * @param inferred true if inferred answers should be propagated */ private boolean propagateAnswersToQuery(ReasonerAtomicQuery target, CacheEntry<ReasonerAtomicQuery, SE> childMatch, boolean inferred){ ReasonerAtomicQuery child = childMatch.query(); boolean[] newAnswersFound = {false}; boolean childGround = child.isGround(); getParents(target) .forEach(parent -> { boolean parentDbComplete = isDBComplete(keyToQuery(parent)); if (parentDbComplete || childGround){ boolean parentComplete = isComplete(keyToQuery(parent)); CacheEntry<ReasonerAtomicQuery, SE> parentMatch = getEntry(keyToQuery(parent)); boolean newAnswers = propagateAnswers(parentMatch, childMatch, inferred || parentComplete); newAnswersFound[0] = newAnswers; if (parentDbComplete || newAnswers) ackDBCompleteness(target); if (parentComplete) ackCompleteness(target); } }); return newAnswersFound[0]; } @Override public CacheEntry<ReasonerAtomicQuery, SE> record( ReasonerAtomicQuery query, ConceptMap answer, @Nullable CacheEntry<ReasonerAtomicQuery, SE> entry, @Nullable MultiUnifier unifier) { assert(query.isPositive()); validateAnswer(answer, query, query.getVarNames()); /* * find SE entry * - if entry exists - easy * - if not, add entry and establish whether any parents present */ CacheEntry<ReasonerAtomicQuery, SE> match = entry != null? entry : this.getEntry(query); if (match != null){ ReasonerAtomicQuery equivalentQuery = match.query(); SE answerSet = match.cachedElement(); MultiUnifier multiUnifier = unifier == null? query.getMultiUnifier(equivalentQuery, unifierType()) : unifier; Set<Variable> cacheVars = equivalentQuery.getVarNames(); //NB: this indexes answer according to all indices in the set multiUnifier .apply(answer) .peek(ans -> validateAnswer(ans, equivalentQuery, cacheVars)) .forEach(answerSet::add); return match; } return addEntry(createEntry(query, Sets.newHashSet(answer))); } @Override public CacheEntry<ReasonerAtomicQuery, SE> record(ReasonerAtomicQuery query, Set<ConceptMap> answers) { ConceptMap first = answers.stream().findFirst().orElse(null); if (first == null) return null; CacheEntry<ReasonerAtomicQuery, SE> record = record(query, first); Sets.difference(answers, Sets.newHashSet(first)).forEach(ans -> record(query, ans, record, null)); return record; } @Override public CacheEntry<ReasonerAtomicQuery, SE> record(ReasonerAtomicQuery query, Stream<ConceptMap> answers) { return record(query, answers.collect(toSet())); } private Pair<Stream<ConceptMap>, MultiUnifier> getDBAnswerStreamWithUnifier(ReasonerAtomicQuery query){ return new Pair<>( structuralCache().get(query), MultiUnifierImpl.trivial() ); } private static final Logger LOG = LoggerFactory.getLogger(SemanticCache.class); @Override public Pair<Stream<ConceptMap>, MultiUnifier> getAnswerStreamWithUnifier(ReasonerAtomicQuery query) { assert(query.isPositive()); CacheEntry<ReasonerAtomicQuery, SE> match = getEntry(query); boolean queryGround = query.isGround(); if (match != null) { boolean answersToGroundQuery = false; boolean queryDBComplete = isDBComplete(query); if (queryGround) { boolean newAnswersPropagated = propagateAnswersToQuery(query, match, true); if (newAnswersPropagated) answersToGroundQuery = answersQuery(query); } //extra check is a quasi-completeness check if there's no parent present we have no guarantees about completeness with respect to the db. Pair<Stream<ConceptMap>, MultiUnifier> cachePair = entryToAnswerStreamWithUnifier(query, match); //if db complete or we found answers to ground query via propagation we don't need to hit the database if (queryDBComplete || answersToGroundQuery) return cachePair; //otherwise lookup and add inferred answers on top return new Pair<>( Stream.concat( getDBAnswerStreamWithUnifier(query).getKey(), cachePair.getKey().filter(ans -> ans.explanation().isRuleExplanation()) ), cachePair.getValue()); } //if no match but db-complete parent exists, use parent to create entry Set<QE> parents = getParents(query); boolean fetchFromParent = parents.stream().anyMatch(p -> queryGround || isDBComplete(keyToQuery(p)) ); if (fetchFromParent){ LOG.trace("Query Cache miss: {} with fetch from parents {}", query, parents); CacheEntry<ReasonerAtomicQuery, SE> newEntry = addEntry(createEntry(query, new HashSet<>())); return new Pair<>(entryToAnswerStream(newEntry), MultiUnifierImpl.trivial()); } return getDBAnswerStreamWithUnifier(query); } @Override public Stream<ConceptMap> getAnswerStream(ReasonerAtomicQuery query) { return getAnswerStreamWithUnifier(query).getKey(); } @Override public Set<ConceptMap> getAnswers(ReasonerAtomicQuery query) { return getAnswerStream(query).collect(toSet()); } @Override public Pair<Set<ConceptMap>, MultiUnifier> getAnswersWithUnifier(ReasonerAtomicQuery query) { Pair<Stream<ConceptMap>, MultiUnifier> answerStreamWithUnifier = getAnswerStreamWithUnifier(query); return new Pair<>( answerStreamWithUnifier.getKey().collect(toSet()), answerStreamWithUnifier.getValue() ); } @Override public ConceptMap findAnswer(ReasonerAtomicQuery query, ConceptMap ans) { if(ans.isEmpty()) return ans; ConceptMap answer = getAnswerStreamWithUnifier(ReasonerQueries.atomic(query, ans)).getKey().findFirst().orElse(null); if (answer != null) return answer; //TODO should it create a cache entry? List<ConceptMap> answers = query.tx().execute(ReasonerQueries.create(query, ans).getQuery(), false); return answers.isEmpty()? new ConceptMap() : answers.iterator().next(); } }
package io.druid.cli; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.name.Names; import com.metamx.common.lifecycle.Lifecycle; import com.metamx.common.logger.Logger; import io.airlift.command.Command; import io.druid.concurrent.Execs; import io.druid.curator.PotentiallyGzippedCompressionProvider; import io.druid.curator.announcement.Announcer; import io.druid.curator.discovery.ServerDiscoveryFactory; import io.druid.curator.discovery.ServerDiscoverySelector; import io.druid.db.DatabaseSegmentManager; import io.druid.db.DatabaseSegmentManagerConfig; import io.druid.db.DatabaseSegmentManagerProvider; import io.druid.guice.ConfigProvider; import io.druid.guice.Jerseys; import io.druid.guice.JsonConfigProvider; import io.druid.guice.LazySingleton; import io.druid.guice.LifecycleModule; import io.druid.guice.ManageLifecycle; import io.druid.guice.ManageLifecycleLast; import io.druid.guice.NodeTypeConfig; import io.druid.query.QuerySegmentWalker; import io.druid.server.QueryResource; import io.druid.server.bridge.Bridge; import io.druid.server.bridge.BridgeCuratorConfig; import io.druid.server.bridge.BridgeQuerySegmentWalker; import io.druid.server.bridge.BridgeZkCoordinator; import io.druid.server.bridge.DruidClusterBridge; import io.druid.server.bridge.DruidClusterBridgeConfig; import io.druid.server.coordination.AbstractDataSegmentAnnouncer; import io.druid.server.coordination.BatchDataSegmentAnnouncer; import io.druid.server.coordination.DruidServerMetadata; import io.druid.server.initialization.BatchDataSegmentAnnouncerConfig; import io.druid.server.initialization.JettyServerInitializer; import io.druid.server.initialization.ZkPathsConfig; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.BoundedExponentialBackoffRetry; import org.eclipse.jetty.server.Server; import java.util.List; @Command( name = "bridge", description = "This is a highly experimental node to use at your own discretion" ) public class CliBridge extends ServerRunnable { private static final Logger log = new Logger(CliBridge.class); public CliBridge() { super(log); } @Override protected List<Object> getModules() { return ImmutableList.<Object>of( new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/bridge"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8089); ConfigProvider.bind(binder, BridgeCuratorConfig.class); binder.bind(BridgeZkCoordinator.class).in(ManageLifecycle.class); binder.bind(NodeTypeConfig.class).toInstance(new NodeTypeConfig("bridge")); JsonConfigProvider.bind(binder, "druid.manager.segments", DatabaseSegmentManagerConfig.class); binder.bind(DatabaseSegmentManager.class) .toProvider(DatabaseSegmentManagerProvider.class) .in(ManageLifecycle.class); binder.bind(QuerySegmentWalker.class).to(BridgeQuerySegmentWalker.class).in(LazySingleton.class); binder.bind(JettyServerInitializer.class).to(QueryJettyServerInitializer.class).in(LazySingleton.class); Jerseys.addResource(binder, QueryResource.class); LifecycleModule.register(binder, QueryResource.class); ConfigProvider.bind(binder, DruidClusterBridgeConfig.class); binder.bind(DruidClusterBridge.class); LifecycleModule.register(binder, DruidClusterBridge.class); LifecycleModule.register(binder, BridgeZkCoordinator.class); LifecycleModule.register(binder, Server.class); } @Provides @LazySingleton @Bridge public CuratorFramework getBridgeCurator(final BridgeCuratorConfig bridgeCuratorConfig, Lifecycle lifecycle) { final CuratorFramework framework = CuratorFrameworkFactory.builder() .connectString(bridgeCuratorConfig.getParentZkHosts()) .sessionTimeoutMs(bridgeCuratorConfig.getZkSessionTimeoutMs()) .retryPolicy(new BoundedExponentialBackoffRetry(1000, 45000, 30)) .compressionProvider( new PotentiallyGzippedCompressionProvider( bridgeCuratorConfig.enableCompression() ) ) .build(); lifecycle.addHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { log.info("Starting Curator for %s", bridgeCuratorConfig.getParentZkHosts()); framework.start(); } @Override public void stop() { log.info("Stopping Curator"); framework.close(); } } ); return framework; } @Provides @ManageLifecycle public ServerDiscoverySelector getServerDiscoverySelector( DruidClusterBridgeConfig config, ServerDiscoveryFactory factory ) { return factory.createSelector(config.getBrokerServiceName()); } @Provides @ManageLifecycle @Bridge public Announcer getBridgeAnnouncer( @Bridge CuratorFramework curator ) { return new Announcer(curator, Execs.singleThreaded("BridgeAnnouncer-%s")); } @Provides @ManageLifecycleLast @Bridge public AbstractDataSegmentAnnouncer getBridgeDataSegmentAnnouncer( DruidServerMetadata metadata, BatchDataSegmentAnnouncerConfig config, ZkPathsConfig zkPathsConfig, @Bridge Announcer announcer, ObjectMapper jsonMapper ) { return new BatchDataSegmentAnnouncer( metadata, config, zkPathsConfig, announcer, jsonMapper ); } } ); } }
package com.scg.net.server; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.scg.domain.ClientAccount; import com.scg.domain.Consultant; import com.scg.net.cmd.Command; /** * The server for creating new clients, consultants and time cards as well as * creation of account invoices. Maintains it's own list of clients and * consultants, but not time cards. * * @author Russ Moul */ public class InvoiceServer { /** The class' logger. */ private static final Logger logger = LoggerFactory.getLogger(InvoiceServer.class); /** The clients/accounts. */ private final List<ClientAccount> clientList; /** The consultants. */ private final List<Consultant> consultantList; /** The server socket socket. */ private ServerSocket serverSocket = null; /** The server socket port. */ private final int port; /** The name of the directory to be used for files output by commands. */ private String outputDirectoryName = "."; /** * Construct an InvoiceServer with a port. * * @param port The port for this server to listen on * @param clientList the initial list of clients * @param consultantList the initial list of consultants * @param outputDirectoryName the directory to be used for files output by commands */ //Docs have it throw an IO exception public InvoiceServer(final int port, final List<ClientAccount> clientList, final List<Consultant> consultantList, final String outputDirectoryName) { this.port = port; this.clientList = clientList; this.consultantList = consultantList; this.outputDirectoryName = outputDirectoryName; this.serverSocket = new ServerSocket(port) } /** * Run this server, establishing connections, receiving commands, and * dispatching them to the CommandProcesser. */ public void run() { int processorNum = 0; while (!serverSocket.isClosed()) { try{ logger.info("InvoiceServer waiting for connection on port " + port); Socket client = serverSocket.accept(); final CommandProcessor commandProcess = new CommandProcessor(client, "CommandProcessor_"+processorNum,clientList,consultantList,this); final File serverDir = new File(outputDirectoryName,Integer.toString(processorNum)); if(serverDir.exists()||serverDir.mkdirs()){ commandProcess.setOutput(serverDir.getAbsolutePath()); final Thread thread = new Thread(commandProcess,"CommandProcessor_"+processorNum); processorNum++; } else{ logger.error("Poop"); } } catch (final SocketException sx) { logger.info("Server socket closed."); } catch (final IOException e1) { //there a try block here. logger.error("Unable to bind server socket to port " + port); } } /*try (ServerSocket serverSocket = new ServerSocket(port)) { this.serverSocket = serverSocket; logger.info("InvoiceServer started on: " + serverSocket.getInetAddress().getHostName() + ":" + serverSocket.getLocalPort()); while (!serverSocket.isClosed()) { logger.info("InvoiceServer waiting for connection on port " + port); try (Socket client = serverSocket.accept()) { serviceConnection(client); } catch (final SocketException sx) { logger.info("Server socket closed."); } } } catch (final IOException e1) { logger.error("Unable to bind server socket to port " + port); }*/ } /** * Read and process commands from the provided socket. * @param client the socket to read from */ void serviceConnection(final Socket client) { try { client.shutdownOutput(); InputStream is = client.getInputStream(); ObjectInputStream in = new ObjectInputStream(is); logger.info("Connection made."); final CommandProcessor cmdProc = new CommandProcessor(client, "name", clientList, consultantList, this); cmdProc.setOutPutDirectoryName(outputDirectoryName); while (!client.isClosed()) { final Object obj = in.readObject(); if (obj == null) { client.close(); } else if (obj instanceof Command<?>) { final Command<?> command = (Command<?>)obj; logger.info("Received command: " + command.getClass().getSimpleName()); command.setReceiver(cmdProc); command.execute(); } else { logger.warn(String.format("Received non command object, %s, discarding.", obj.getClass().getSimpleName())); } } } catch (final IOException ex) { logger.error("IO failure.", ex); } catch (final ClassNotFoundException ex) { logger.error("Unable to resolve read object.", ex); } } /** * Shutdown the server. */ void shutdown() { try { if (serverSocket != null && !serverSocket.isClosed()) { serverSocket.close(); } } catch (final IOException e) { logger.error("Shutdown unable to close listening socket.", e); } } }
package app.hongs; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public abstract class CoreSerial implements Serializable { /** * * @param path * @param name * @param time * @throws app.hongs.HongsException */ public CoreSerial(String path, String name, long time) throws HongsException { this.init(path, name, time); } /** * * @param path * @param name * @param date * @throws app.hongs.HongsException */ public CoreSerial(String path, String name, Date date) throws HongsException { this.init(path, name, date); } /** * * @param name * @param time * @throws app.hongs.HongsException */ public CoreSerial(String name, long time) throws HongsException { this.init(name, time); } /** * * @param name * @param date * @throws app.hongs.HongsException */ public CoreSerial(String name, Date date) throws HongsException { this.init(name, date); } /** * * @param name * @throws app.hongs.HongsException */ public CoreSerial(String name) throws HongsException { this.init(name); } /** * (init) */ public CoreSerial() { // TODO: init } /** * * @throws app.hongs.HongsException */ abstract protected void imports() throws HongsException; /** * * @param time * @return true * @throws app.hongs.HongsException */ protected boolean expired(long time) throws HongsException { return time != 0 && time < System.currentTimeMillis(); } /** * () * @param path * @param name * @param time * @throws app.hongs.HongsException */ protected final void init(String path, String name, long time) throws HongsException { if (path == null) { path = Core.DATA_PATH + File.separator + "serial"; } File file = new File(path + File.separator + name + ".ser"); this.load(file, time + file.lastModified( )); } /** * () * @param path * @param name * @param date * @throws app.hongs.HongsException */ protected final void init(String path, String name, Date date) throws HongsException { if (path == null) { path = Core.DATA_PATH + File.separator + "serial"; } File file = new File(path + File.separator + name + ".ser"); this.load(file, date!=null?date.getTime():0); } protected final void init(String name, long time) throws HongsException { this.init(null, name, time); } protected final void init(String name, Date date) throws HongsException { this.init(null, name, date); } protected final void init(String name) throws HongsException { this.init(null, name, null); } /** * * @param file * @param time * @throws app.hongs.HongsException */ protected void load(File file, long time) throws HongsException { ReadWriteLock rwlock = lock(file.getAbsolutePath()); Lock lock; lock = rwlock. readLock(); lock.lock(); try { if (file.exists() && !expired(time)) { load(file); return; } } finally { lock.unlock( ); } lock = rwlock.writeLock(); lock.lock(); try { imports( ); save(file); } finally { lock.unlock( ); } } /** * * @param file * @throws app.hongs.HongsException */ protected final void load(File file) throws HongsException { try { FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis ); //fis.getChannel().lock(); Map map = (Map)ois.readObject(); load( map ); ois.close(); } catch (ClassNotFoundException ex) { throw new HongsException(0x10d8, ex); } catch (FileNotFoundException ex) { throw new HongsException(0x10d6, ex); } catch (IOException ex) { throw new HongsException(0x10d4, ex); } } /** * * @param file * @throws app.hongs.HongsException */ protected final void save(File file) throws HongsException { if (!file.exists()) { File dn = file.getParentFile(); if (!dn.exists()) { dn.mkdirs(); } try { file.createNewFile( ); } catch (IOException ex) { throw new HongsException(0x10d0, ex); } } try { FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos ); //fos.getChannel().lock(); Map map = new HashMap(); save( map ); oos.writeObject ( map ); oos.flush(); oos.close(); } catch (FileNotFoundException ex) { throw new HongsException(0x10d6, ex); } catch (IOException ex) { throw new HongsException(0x10d2, ex); } } /** * * @param map * @throws app.hongs.HongsException */ private void load(Map<String, Object> map) throws HongsException { Field[] fields; fields = this.getClass().getFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); try { field.set(this, map.get(name)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } fields = this.getClass().getDeclaredFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isPublic(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); field.setAccessible ( true ); try { field.set(this, map.get(name)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } } /** * * @param map * @throws HongsException */ private void save(Map<String, Object> map) throws HongsException { Field[] fields; fields = this.getClass().getFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); try { map.put(name, field.get(this)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } fields = this.getClass().getDeclaredFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isPublic(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); field.setAccessible ( true ); try { map.put(name, field.get(this)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } } private ReadWriteLock lock(String flag) { ReadWriteLock rwlock; Lock lock; lock = lockr. readLock(); lock.lock(); try { rwlock = locks.get(flag); if (rwlock != null) { return rwlock; } } finally { lock.unlock(); } lock = lockr.writeLock(); lock.lock(); try { rwlock = new ReentrantReadWriteLock(); locks.put(flag, rwlock); return rwlock; } finally { lock.unlock(); } } private static Map<String, ReadWriteLock> locks = new HashMap( ); private static ReadWriteLock lockr = new ReentrantReadWriteLock(); }
// reproduction or usage of this software in whole or in part without the // express written consent of Statens vegvesen is strictly prohibited. package no.vegvesen.nvdb.sosi; import no.vegvesen.nvdb.sosi.encoding.SosiEncoding; import no.vegvesen.nvdb.sosi.reader.SosiReader; import no.vegvesen.nvdb.sosi.reader.SosiReaderImpl; import no.vegvesen.nvdb.sosi.utils.BufferPoolImpl; import no.vegvesen.nvdb.sosi.parser.SosiParserImpl; import no.vegvesen.nvdb.sosi.parser.SosiParser; import no.vegvesen.nvdb.sosi.writer.SosiValueFormatter; import no.vegvesen.nvdb.sosi.writer.SosiWriter; import no.vegvesen.nvdb.sosi.writer.SosiWriterImpl; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; /** * Factory to create {@link no.vegvesen.nvdb.sosi.parser.SosiParser} and {@link SosiReader} instances. * * <p> * For example, a SOSI parser for parsing a simple SOSI string could be created as follows: * <pre> * <code> * StringReader reader = new StringReader(".HODE ..EIER Sosekopp .SLUTT"); * SosiParser parser = Sosi.createParser(reader); * </code> * </pre> * * <p> * All of the methods in this class are safe for use by multiple concurrent threads. * * Based on the javax.json.Json class. * * @author Tore Eide Andersen (Kantega AS) */ public class Sosi { private Sosi() { } /** * Detects the encoding of a SOSI file. * * @param sosi the SOSI file content. * @return the encoding */ public static Charset getEncoding(byte[] sosi) { return SosiEncoding.charsetOf(sosi).orElseGet(SosiEncoding::defaultCharset); } /** * Creates a SOSI parser from the specified character stream * * @param reader i/o reader from which SOSI is to be read */ public static SosiParser createParser(Reader reader) { return new SosiParserImpl(reader, new BufferPoolImpl()); } public static SosiParser createParser(InputStream in) { return new SosiParserImpl(in, new BufferPoolImpl()); } /** * Creates a SOSI reader which can be used to read SOSI text from the * specified character stream. * * @param reader a i/o reader from which SOSI is read */ public static SosiReader createReader(Reader reader) { return new SosiReaderImpl(reader, new BufferPoolImpl()); } /** * Creates a SOSI reader which can be used to read SOSI text from the * specified byte stream. * * @param in i/o stream from which SOSI is read */ public static SosiReader createReader(InputStream in) { return new SosiReaderImpl(in, new BufferPoolImpl()); } /** * Creates a SOSI writer which can be used to write SOSI document to the * specified character stream. * * @param writer a i/o writer to which SOSI is written */ public static SosiWriter createWriter(Writer writer) { return new SosiWriterImpl(writer); } /** * Creates a SOSI writer which can be used to write SOSI document to the * specified character stream using a custom value formatter. * * @param writer a i/o writer to which SOSI is written */ public static SosiWriter createWriter(Writer writer, SosiValueFormatter valueFormatter) { return new SosiWriterImpl(writer, valueFormatter); } /** * Creates a SOSI writer which can be used to write SOSI document to the * specified byte stream. * * @param out i/o stream to which SOSI is written * @param encoding the desired character encoding */ public static SosiWriter createWriter(OutputStream out, Charset encoding) { return new SosiWriterImpl(out, encoding); } }
package consulo.web.servlet; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.util.TimeoutUtil; import consulo.ui.*; import consulo.ui.internal.WGwtListBoxImpl; import consulo.ui.internal.WGwtModalWindowImpl; import consulo.ui.model.ImmutableListModel; import consulo.ui.shared.Size; import consulo.web.AppInit; import consulo.web.servlet.ui.UIBuilder; import consulo.web.servlet.ui.UIServlet; import org.jetbrains.annotations.NotNull; import javax.servlet.annotation.WebServlet; import java.util.ArrayList; import java.util.List; public class AppUIBuilder extends UIBuilder { @WebServlet("/app") public static class Servlet extends UIServlet { public Servlet() { super(AppUIBuilder.class); } } @Override protected void build(@NotNull Window window) { ApplicationEx application = ApplicationManagerEx.getApplicationEx(); if (application == null || !application.isLoaded()) { AppInit.initApplication(); while (true) { application = ApplicationManagerEx.getApplicationEx(); if (application != null && application.isLoaded()) { break; } TimeoutUtil.sleep(500L); } } final WGwtModalWindowImpl modalWindow = new WGwtModalWindowImpl(); modalWindow.setSize(new Size(777, 460)); List<String> c = new ArrayList<String>(); for (int i = 0; i < 200; i++) { c.add("Some: " + i); } WGwtListBoxImpl<String> list = new WGwtListBoxImpl<String>(new ImmutableListModel<String>(c)); list.addValueListener(new ValueComponent.ValueListener<String>() { @Override public void valueChanged(@NotNull ValueComponent.ValueEvent<String> event) { System.out.println(event.getValue() + " selected"); modalWindow.setVisible(false); } }); modalWindow.setContent(Layouts.horizontalSplit().setFirstComponent(list).setSecondComponent(Components.label("Some labe"))); modalWindow.setVisible(true); final Menu file = MenuItems.menu("File"); file.add(MenuItems.menu("New").add(MenuItems.item("Class"))); file.separate(); file.add(MenuItems.item("Exit")); window.setMenuBar(MenuItems.menuBar().add(file).add(MenuItems.item("Help"))); final SplitLayout splitLayout = Layouts.horizontalSplit(); final TabbedLayout tabbed = Layouts.tabbed(); final VerticalLayout vertical = Layouts.vertical(); BooleanValueGroup group = new BooleanValueGroup(); final RadioButton component = Components.radioButton("Test 1", true); vertical.add(component); final RadioButton component1 = Components.radioButton("Test 2"); vertical.add(component1); group.add(component).add(component1); tabbed.addTab("Hello", vertical); final LabeledLayout labeled = Layouts.labeled("Some Panel Label"); tabbed.addTab("Hello2", labeled.set(Components.label("test 1"))); splitLayout.setFirstComponent(Components.label("tree")); splitLayout.setSecondComponent(tabbed); splitLayout.setProportion(20); window.setContent(splitLayout); } }
package VASSAL.build.module.map.boardPicker; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.image.ImageObserver; import java.io.File; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.swing.ImageIcon; import VASSAL.build.AbstractConfigurable; import VASSAL.build.Buildable; import VASSAL.build.Builder; import VASSAL.build.GameModule; import VASSAL.build.module.GameComponent; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.boardPicker.board.HexGrid; import VASSAL.build.module.map.boardPicker.board.MapGrid; import VASSAL.build.module.map.boardPicker.board.RegionGrid; import VASSAL.build.module.map.boardPicker.board.SquareGrid; import VASSAL.build.module.map.boardPicker.board.ZonedGrid; import VASSAL.build.module.map.boardPicker.board.mapgrid.GridContainer; import VASSAL.command.Command; import VASSAL.configure.ColorConfigurer; import VASSAL.configure.SingleChildInstance; import VASSAL.configure.VisibilityCondition; import VASSAL.tools.ErrorDialog; import VASSAL.tools.imageop.ImageOp; import VASSAL.tools.imageop.Op; import VASSAL.tools.imageop.OpErrorDialog; import VASSAL.tools.imageop.Repainter; import VASSAL.tools.imageop.ScaleOp; import VASSAL.tools.imageop.SourceOp; public class Board extends AbstractConfigurable implements GridContainer { /** * A Board is a piece of a Map. * A Map can cantain a set of boards layed out in a rectangular grid. */ public static final String NAME = "name"; public static final String IMAGE = "image"; public static final String WIDTH = "width"; public static final String HEIGHT = "height"; public static final String COLOR = "color"; public static final String REVERSIBLE = "reversible"; protected Point pos = new Point(0, 0); protected Rectangle boundaries = new Rectangle(0, 0, 500, 500); protected String imageFile; protected boolean reversible = false; protected boolean reversed = false; protected boolean fixedBoundaries = false; protected Color color = null; protected MapGrid grid = null; protected Map map; protected double magnification = 1.0; @Deprecated protected String boardName = "Board 1"; @Deprecated protected Image boardImage; protected SourceOp boardImageOp; protected ScaleOp scaledImageOp; public Board() { } /** * @return this <code>Board</code>'s {@link Map}. * Until a game is started that is using this board, the map will be null. */ public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public String getLocalizedName() { final String s = getLocalizedConfigureName(); return s != null ? s : ""; } public String getName() { final String s = getConfigureName(); return s != null ? s : ""; } public void addTo(Buildable b) { validator = new SingleChildInstance(this, MapGrid.class); } public void removeFrom(Buildable b) { } public String[] getAttributeNames() { return new String[] { NAME, IMAGE, REVERSIBLE, WIDTH, HEIGHT, COLOR }; } public String[] getAttributeDescriptions() { return new String[] { "Board name: ", "Board image: ", "Reversible: ", "Board width: ", "Board height: ", "Background color: " }; } public static String getConfigureTypeName() { return "Board"; } public Class<?>[] getAttributeTypes() { return new Class<?>[] { String.class, Image.class, Boolean.class, Integer.class, Integer.class, Color.class }; } public VisibilityCondition getAttributeVisibility(String name) { if (REVERSIBLE.equals(name)) { return new VisibilityCondition() { public boolean shouldBeVisible() { return imageFile != null; } }; } else if (WIDTH.equals(name) || HEIGHT.equals(name) || COLOR.equals(name)) { return new VisibilityCondition() { public boolean shouldBeVisible() { return imageFile == null; } }; } else { return null; } } public String getAttributeValueString(String key) { if (NAME.equals(key)) { return getConfigureName(); } else if (IMAGE.equals(key)) { return imageFile; } else if (WIDTH.equals(key)) { return imageFile == null ? String.valueOf(boundaries.width) : null; } else if (HEIGHT.equals(key)) { return imageFile == null ? String.valueOf(boundaries.height) : null; } else if (COLOR.equals(key)) { return imageFile == null ? ColorConfigurer.colorToString(color) : null; } else if (REVERSIBLE.equals(key)) { return String.valueOf(reversible); } return null; } public void setAttribute(String key, Object val) { if (NAME.equals(key)) { setConfigureName((String) val); } else if (IMAGE.equals(key)) { if (val instanceof File) { val = ((File) val).getName(); } imageFile = (String) val; boardImageOp = imageFile == null || imageFile.trim().length() == 0 ? null : Op.load(imageFile); } else if (WIDTH.equals(key)) { if (val instanceof String) { val = new Integer((String) val); } if (val != null) { boundaries.setSize(((Integer) val).intValue(), boundaries.height); } } else if (HEIGHT.equals(key)) { if (val instanceof String) { val = new Integer((String) val); } if (val != null) { boundaries.setSize(boundaries.width, ((Integer) val).intValue()); } } else if (COLOR.equals(key)) { if (val instanceof String) { val = ColorConfigurer.stringToColor((String) val); } color = (Color) val; } else if (REVERSIBLE.equals(key)) { if (val instanceof String) { val = Boolean.valueOf((String) val); } reversible = ((Boolean) val).booleanValue(); } } public Class[] getAllowableConfigureComponents() { return new Class[] { HexGrid.class, SquareGrid.class, RegionGrid.class, ZonedGrid.class }; } public void draw(Graphics g, int x, int y, double zoom, Component obs) { drawRegion(g, new Point(x,y), new Rectangle(x, y, Math.round((float) zoom*boundaries.width), Math.round((float) zoom*boundaries.height)), zoom, obs); } private java.util.Map<Point,Future<Image>> requested = new ConcurrentHashMap<Point,Future<Image>>(); private static Comparator<Point> tileOrdering = new Comparator<Point>() { public int compare(Point t1, Point t2) { if (t1.y < t2.y) return -1; if (t1.y > t2.y) return 1; return t1.x - t2.x; } }; protected static final Image throbber; protected static final int thxoff; protected static final int thyoff; protected static final Color tileOutlineColor = new Color(0xCCCCCC); static { // The throbber must not be loaded with something which // produces a BufferedImage, becuase it's an animated GIF. throbber = Toolkit.getDefaultToolkit().createImage( Board.class.getResource("/images/roller.gif")); new ImageIcon(throbber); // force complete loading thxoff = throbber.getWidth(null)/2; thyoff = throbber.getHeight(null)/2; } public void drawRegion(final Graphics g, final Point location, Rectangle visibleRect, double zoom, final Component obs) { zoom *= magnification; final Rectangle bounds = new Rectangle(location.x, location.y, Math.round(boundaries.width * (float) zoom), Math.round(boundaries.height * (float) zoom)); if (visibleRect.intersects(bounds)) { visibleRect = visibleRect.intersection(bounds); if (boardImageOp != null) { final ImageOp op; if (zoom == 1.0 && !reversed) { op = boardImageOp; } else { if (scaledImageOp == null || scaledImageOp.getScale() != zoom) { scaledImageOp = Op.scale(boardImageOp, zoom); } op = reversed ? Op.rotate(scaledImageOp, 180) : scaledImageOp; } final Rectangle r = new Rectangle(visibleRect.x - location.x, visibleRect.y - location.y, visibleRect.width, visibleRect.height); final int ow = op.getTileWidth(); final int oh = op.getTileHeight(); final Point[] tiles = op.getTileIndices(r); for (Point tile : tiles) { // find tile position final int tx = location.x + tile.x*ow; final int ty = location.y + tile.y*oh; // find actual tile size final int tw = Math.min(ow, location.x+bounds.width-tx); final int th = Math.min(oh, location.y+bounds.height-ty); final Repainter rep = obs == null ? null : new Repainter(obs, tx, ty, tw, th); try { final Future<Image> fim = op.getFutureTile(tile.x, tile.y, rep); if (fim.isDone() || obs == null) { try { g.drawImage(fim.get(), tx, ty, obs); } catch (CancellationException e) { // FIXME: bug until we permit cancellation ErrorDialog.bug(e); } catch (InterruptedException e) { ErrorDialog.bug(e); } catch (ExecutionException e) { OpErrorDialog.error(e, op); } requested.remove(tile); final ThrobberObserver tobs = throbberObservers.remove(tile); if (tobs != null) tobs.stop(); } else { if (requested.get(tile) == null) { requested.put(tile, fim); } // draw tile outline final Color oldColor = g.getColor(); g.setColor(tileOutlineColor); g.drawRect(tx, ty, tw, th); g.setColor(oldColor); // draw animated throbber ThrobberObserver tobs = throbberObservers.get(tile); if (tobs == null) { tobs = throbberObservers.put(tile, new ThrobberObserver(obs, zoom)); } else if (zoom != tobs.getZoom()) { throbberObservers.remove(tobs); tobs.stop(); tobs = throbberObservers.put(tile, new ThrobberObserver(obs, zoom)); } g.drawImage(throbber, tx+tw/2-thxoff, ty+th/2-thyoff, tobs); } } // FIXME: should getTileFuture() throw these? catch (CancellationException e) { // FIXME: bug until we permit cancellation ErrorDialog.bug(e); } catch (ExecutionException e) { // FIXME: bug until we figure out why getTileFuture() throws this ErrorDialog.bug(e); } } for (Point tile : requested.keySet().toArray(new Point[0])) { if (Arrays.binarySearch(tiles, tile, tileOrdering) < 0) { requested.remove(tile); final ThrobberObserver tobs = throbberObservers.remove(tile); if (tobs != null) tobs.stop(); } } /* final StringBuilder sb = new StringBuilder(); for (Point tile : requested.keySet().toArray(new Point[0])) { if (Arrays.binarySearch(tiles, tile, tileOrdering) < 0) { final Future<Image> fim = requested.remove(tile); if (!fim.isDone()) { sb.append("(") .append(tile.x) .append(",") .append(tile.y) .append(") "); } } } if (sb.length() > 0) { sb.insert(0, "cancelling: ").append("\n"); System.out.print(sb.toString()); } */ } else { if (color != null) { g.setColor(color); g.fillRect(visibleRect.x, visibleRect.y, visibleRect.width, visibleRect.height); } else { g.clearRect(visibleRect.x, visibleRect.y, visibleRect.width, visibleRect.height); } } if (grid != null) { grid.draw(g, bounds, visibleRect, zoom, reversed); } } } private java.util.Map<Point,ThrobberObserver> throbberObservers = new ConcurrentHashMap<Point,ThrobberObserver>(); public static class ThrobberObserver implements ImageObserver { private final Component c; private final double zoom; private boolean done = false; public ThrobberObserver(Component c, double zoom) { this.c = c; this.zoom = zoom; } public double getZoom() { return zoom; } public void stop() { done = true; } public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) { return !done && c.imageUpdate(img, flags, x, y, w, h); } } @Deprecated public synchronized Image getScaledImage(double zoom, Component obs) { try { final ImageOp sop = Op.scale(boardImageOp, zoom); return (reversed ? Op.rotate(sop, 180) : sop).getImage(null); } catch (CancellationException e) { ErrorDialog.bug(e); } catch (InterruptedException e) { ErrorDialog.bug(e); } catch (ExecutionException e) { OpErrorDialog.error(e, boardImageOp); } return null; } public void setReversed(boolean val) { if (reversible) { if (reversed != val) { reversed = val; scaledImageOp = null; // get a new rendered version on next paint } } } public boolean isReversed() { return reversed; } /** * If this board is reversed, return the location in un-reversed coordinates */ public Point localCoordinates(Point p) { if (reversed) { p.x = bounds().width - p.x; p.y = bounds().height - p.y; } if (magnification != 1.0) { p.x = (int) Math.round(p.x/magnification); p.y = (int) Math.round(p.y/magnification); } return p; } /** * If this board is reversed, return the location in reversed coordinates */ public Point globalCoordinates(Point p) { if (magnification != 1.0) { p.x = (int) Math.round(p.x*magnification); p.y = (int) Math.round(p.y*magnification); } if (reversed) { p.x = bounds().width - p.x; p.y = bounds().height - p.y; } return p; } public void setGrid(MapGrid mg) { grid = mg; } public void removeGrid(MapGrid grid) { if (this.grid == grid) { this.grid = null; } } public Board getBoard() { return this; } public Dimension getSize() { return bounds().getSize(); } public MapGrid getGrid() { return grid; } public Board copy() { Board b = new Board(); b.build(getBuildElement(Builder.createNewDocument())); return b; } /** * @deprecated Images are now fixed automagically using {@link ImageOp}s. */ @Deprecated public void fixImage(Component map) { } /** * @deprecated Images are now fixed automagically using {@link ImageOp}s. */ @Deprecated public void fixImage() { } public String locationName(Point p) { return grid == null ? null : grid.locationName(localCoordinates(p)); } public String localizedLocationName(Point p) { return grid == null ? null : grid.localizedLocationName(localCoordinates(p)); } public Point snapTo(Point p) { return grid == null ? p : globalCoordinates(grid.snapTo(localCoordinates(p))); } /** * @return true if the given point may not be a local location. * I.e., if this grid will attempt to snap it to the nearest grid location. */ public boolean isLocationRestricted(Point p) { return grid == null ? false : grid.isLocationRestricted(localCoordinates(p)); } public String fileName() { return imageFile; } /** * @return Position of this board relative to the other boards (0,0) is the upper left, (0,1) is to the right, etc. */ public Point relativePosition() { return pos; } /** * @return The (read-only) boundaries of this Board within the overall Map */ public Rectangle bounds() { if (imageFile != null && boardImageOp != null && !fixedBoundaries) { boundaries.setSize(boardImageOp.getSize()); if (magnification != 1.0) { boundaries.setSize((int)Math.round(magnification*boundaries.width), (int)Math.round(magnification*boundaries.height)); } fixedBoundaries = true; } return new Rectangle(boundaries); } /** * @deprecated Bounds are now fixed automagically by {@link ImageOp}s. */ @Deprecated protected void fixBounds() { } /** * Translate the location of the board by the given number of pixels * * @see #bounds() */ public void translate(int x, int y) { boundaries.translate(x, y); } /** * Set the location of this board * * @see #bounds() */ public void setLocation(int x, int y) { boundaries.setLocation(x, y); } public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("Board.htm"); } /** * Removes board images from the {@link VASSAL.tools.DataArchive} cache * @deprecated Board images are removed automatically now, when under * memory pressure. */ @Deprecated public void cleanUp() { if (imageFile != null) { GameModule.getGameModule().getDataArchive().unCacheImage("images/" + imageFile); } if (boardImage != null) { GameModule.getGameModule().getDataArchive().unCacheImage(boardImage); boardImage = null; } } /** * Cleans up {@link Board}s (by invoking {@link Board#cleanUp}) when a * game is closed * @deprecated Only used to cleanup <code>Board</code> images, which * is now handled automatically by the cache. */ @Deprecated public static class Cleanup implements GameComponent { private static Cleanup instance; private Set<Board> toClean = new HashSet<Board>(); private boolean gameStarted = false; public static void init() { if (instance == null) { instance = new Cleanup(); } } private Cleanup() { GameModule.getGameModule().getGameState().addGameComponent(this); } public static Cleanup getInstance() { return instance; } /** * Mark this board as needing to be cleaned up when the game is closed * * @param b */ public void addBoard(Board b) { toClean.add(b); } public Command getRestoreCommand() { return null; } public void setup(boolean gameStarting) { if (gameStarted && !gameStarting) { for (Board board : toClean) { board.cleanUp(); } toClean.clear(); } gameStarted = gameStarting; } } public double getMagnification() { return magnification; } public void setMagnification(double magnification) { this.magnification = magnification; fixedBoundaries = false; bounds(); } }
import org.antlr.v4.runtime.Token; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.snt.inmemantlr.GenericParser; import org.snt.inmemantlr.exceptions.CompilationException; import org.snt.inmemantlr.exceptions.IllegalWorkflowException; import org.snt.inmemantlr.utils.FileUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestLexerGrammar { private static final Logger LOGGER = LoggerFactory.getLogger(TestSimple.class); String sgrammarcontent = ""; @Test public void testInterpreter() throws IOException { try (InputStream sgrammar = getClass().getClassLoader() .getResourceAsStream("inmemantlr/LexerGrammar.g4")) { sgrammarcontent = FileUtils.getStringFromStream(sgrammar); } GenericParser gp = new GenericParser(sgrammarcontent); final File f = new File(getClass().getProtectionDomain().getCodeSource() .getLocation().getPath()); boolean compile; try { gp.compile(); compile = true; } catch (CompilationException e) { compile = false; } Assertions.assertTrue(compile); try { List<Token> tokens = gp.lex("a09"); Assertions.assertEquals(tokens.size(), 2); } catch (IllegalWorkflowException e) { Assertions.assertFalse(true); } } }
package io.scif.img; import io.scif.ByteArrayPlane; import io.scif.DefaultImageMetadata; import io.scif.DefaultMetadata; import io.scif.FormatException; import io.scif.ImageMetadata; import io.scif.Metadata; import io.scif.Translator; import io.scif.Writer; import io.scif.common.DataTools; import io.scif.config.SCIFIOConfig; import io.scif.services.FormatService; import io.scif.services.TranslatorService; import io.scif.util.FormatTools; import io.scif.util.SCIFIOMetadataTools; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.imglib2.exception.ImgLibException; import net.imglib2.exception.IncompatibleTypeException; import net.imglib2.img.Img; import net.imglib2.img.basictypeaccess.PlanarAccess; import net.imglib2.img.planar.PlanarImg; import net.imglib2.meta.Axes; import net.imglib2.meta.CalibratedAxis; import net.imglib2.meta.ImgPlus; import org.scijava.Context; import org.scijava.app.StatusService; import org.scijava.plugin.Parameter; /** * Writes out an {@link ImgPlus} using SCIFIO. * * @author Mark Hiner * @author Curtis Rueden */ public class ImgSaver extends AbstractImgIOComponent { @Parameter private StatusService statusService; @Parameter private FormatService formatService; @Parameter private TranslatorService translatorService; // -- Constructors -- public ImgSaver() { super(); } public ImgSaver(final Context context) { super(context); } // -- ImgSaver methods -- /** * saveImg is the entry point for saving an {@link ImgPlus} The goal is to get * to a {@link Writer} and {@link ImgPlus} which are then passed to * {@link #writePlanes}. These saveImg signatures facilitate multiple pathways * to that goal. This method is called when a String id and {@link Img} are * provided. * * @param id * @param img * @throws ImgIOException * @throws IncompatibleTypeException */ public Metadata saveImg(final String id, final Img<?> img) throws ImgIOException, IncompatibleTypeException { return saveImg(id, img, new SCIFIOConfig()); } /** * String id provided. {@link ImgPlus} provided, or wrapped {@link Img} in * previous saveImg. * * @param id * @param img * @throws ImgIOException * @throws IncompatibleTypeException */ public Metadata saveImg(final String id, final SCIFIOImgPlus<?> img, final int imageIndex) throws ImgIOException, IncompatibleTypeException { return saveImg(id, img, imageIndex, new SCIFIOConfig()); } /** * As {@link #saveImg(String, Img)} with configuration options. * * @param id * @param img * @param config Configuration information to use for this write. * @throws ImgIOException * @throws IncompatibleTypeException */ public Metadata saveImg(final String id, final Img<?> img, final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { return saveImg(id, utils().makeSCIFIOImgPlus(img), 0, config); } /** * As {@link #saveImg(String, SCIFIOImgPlus, int)} with configuration options. * * @param id * @param img * @param config Configuration information to use for this write. * @throws ImgIOException * @throws IncompatibleTypeException */ public Metadata saveImg(final String id, final SCIFIOImgPlus<?> img, final int imageIndex, final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { img.setSource(id); img.setName(new File(id).getName()); return saveImg(initializeWriter(id, img, imageIndex, config), img, imageIndex, false, config); } /** * {@link Writer} and {@link Img} provided * * @param w * @param img * @throws ImgIOException * @throws IncompatibleTypeException */ public void saveImg(final Writer w, final Img<?> img) throws ImgIOException, IncompatibleTypeException { saveImg(w, img, new SCIFIOConfig()); } // TODO IFormatHandler needs to be promoted to be able to get the current // file, to get its full path, to provide the ImgPluSCIFIOImgPlusending that, these two IFormatWriter methods are not guaranteed to be // useful /** * {@link Writer} provided. {@link ImgPlus} provided, or wrapped provided * {@link Img}. * * @param w * @param img * @throws ImgIOException * @throws IncompatibleTypeException */ public void saveImg(final Writer w, final SCIFIOImgPlus<?> img, final int imageIndex) throws ImgIOException, IncompatibleTypeException { saveImg(w, img, imageIndex, new SCIFIOConfig()); } /** * As {@link #saveImg(Writer, Img)}, with configuration options. * * @param w * @param img * @param config Configuration information to use for this write. * @throws ImgIOException * @throws IncompatibleTypeException */ public void saveImg(final Writer w, final Img<?> img, final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { saveImg(w, utils().makeSCIFIOImgPlus(img), 0, config); } // TODO IFormatHandler needs to be promoted to be able to get the current // file, to get its full path, to provide the ImgPlus // pending that, these two IFormatWriter methods are not guaranteed to be // useful /** * As {@link #saveImg(Writer, SCIFIOImgPlus, int)}, with configuration options. * * @param w * @param img * @param config Configuration information to use for this write. * @throws ImgIOException * @throws IncompatibleTypeException */ public void saveImg(final Writer w, final SCIFIOImgPlus<?> img, final int imageIndex, final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { saveImg(w, img, imageIndex, true, config); } // -- Utility methods -- /** * The ImgLib axes structure can contain multiple unknown axes. This method * will determine if the provided dimension order, obtained from an ImgLib * AxisType array, can be converted to a 5-dimensional sequence compatible * with SCIFIO, and returns that sequence if it exists and null otherwise. * * @param newLengths - updated to hold the lengths of the newly ordered axes */ public static String guessDimOrder(final CalibratedAxis[] axes, final long[] dimLengths, final long[] newLengths) { String oldOrder = ""; String newOrder = ""; // initialize newLengths to be 1 for simpler multiplication logic later for (int i = 0; i < newLengths.length; i++) { newLengths[i] = 1; } // Signifies if the given axis is present in the dimension order, // X=0, Y=1, Z=2, C=3, T=4 final boolean[] haveDim = new boolean[5]; // number of "blocks" of unknown axes, e.g. YUUUZU = 2 int contiguousUnknown = 0; // how many axis slots we have to work with int missingAxisCount = 0; // flag to determine how many contiguous blocks of unknowns present boolean unknownBlock = false; // first pass to determine which axes are missing and how many // unknown blocks are present. // We build oldOrder to iterate over on pass 2, for convenience for (int i = 0; i < axes.length; i++) { switch (axes[i].type().getLabel().toUpperCase().charAt(0)) { case 'X': oldOrder += "X"; haveDim[0] = true; unknownBlock = false; break; case 'Y': oldOrder += "Y"; haveDim[1] = true; unknownBlock = false; break; case 'Z': oldOrder += "Z"; haveDim[2] = true; unknownBlock = false; break; case 'C': oldOrder += "C"; haveDim[3] = true; unknownBlock = false; break; case 'T': oldOrder += "T"; haveDim[4] = true; unknownBlock = false; break; default: oldOrder += "U"; // dimensions of size 1 can be skipped, and only will // be considered in pass 2 if the number of missing axes is // greater than the number of contiguous unknown chunks found if (dimLengths[i] > 1) { if (!unknownBlock) { unknownBlock = true; contiguousUnknown++; } } break; } } // determine how many axes are missing for (final boolean d : haveDim) { if (!d) missingAxisCount++; } // check to see if we can make a valid dimension ordering if (contiguousUnknown > missingAxisCount) { return null; } int axesPlaced = 0; unknownBlock = false; // Flag to determine if the current unknownBlock was started by // an unknown of size 1. boolean sizeOneUnknown = false; // Second pass to assign new ordering and calculate lengths for (int i = 0; i < axes.length; i++) { switch (oldOrder.charAt(0)) { case 'U': // dimensions of size 1 have no effect on the ordering if (dimLengths[i] > 1 || contiguousUnknown < missingAxisCount) { if (!unknownBlock) { unknownBlock = true; // length of this unknown == 1 if (contiguousUnknown < missingAxisCount) { contiguousUnknown++; sizeOneUnknown = true; } // assign a label to this dimension if (!haveDim[0]) { newOrder += "X"; haveDim[0] = true; } else if (!haveDim[1]) { newOrder += "Y"; haveDim[1] = true; } else if (!haveDim[2]) { newOrder += "Z"; haveDim[2] = true; } else if (!haveDim[3]) { newOrder += "C"; haveDim[3] = true; } else if (!haveDim[4]) { newOrder += "T"; haveDim[4] = true; } } else if (dimLengths[i] > 1 && sizeOneUnknown) { // we are in a block of unknowns that was started by // one of size 1, but contains an unknown of size > 1, // thus was double counted (once in pass 1, once in pass 2) sizeOneUnknown = false; contiguousUnknown } newLengths[axesPlaced] *= dimLengths[i]; } break; default: // "cap" the current unknown block if (unknownBlock) { axesPlaced++; unknownBlock = false; sizeOneUnknown = false; } newOrder += oldOrder.charAt(i); newLengths[axesPlaced] = dimLengths[i]; axesPlaced++; break; } } // append any remaining missing axes // only have to update order string, as lengths are already 1 for (int i = 0; i < haveDim.length; i++) { if (!haveDim[i]) { switch (i) { case 0: newOrder += "X"; break; case 1: newOrder += "Y"; break; case 2: newOrder += "Z"; break; case 3: newOrder += "C"; break; case 4: newOrder += "T"; break; } } } return newOrder; } // -- Helper methods -- /** * Entry point for writePlanes method, the actual workhorse to save pixels to * disk. */ private Metadata saveImg(final Writer w, final SCIFIOImgPlus<?> img, final int imageIndex, final boolean initializeWriter, final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { // use the ImgPlus to calculate necessary metadata if if (initializeWriter) { populateMeta(w.getMetadata(), img, config); } if (img.getSource().length() == 0) { throw new ImgIOException("Provided Image has no attached source."); } final long startTime = System.currentTimeMillis(); final String id = img.getSource(); final int sliceCount = countSlices(img); // write pixels writePlanes(w, img, imageIndex, config); final long endTime = System.currentTimeMillis(); final float time = (endTime - startTime) / 1000f; statusService.showStatus(sliceCount, sliceCount, id + ": wrote " + sliceCount + " planes in " + time + " s"); return w.getMetadata(); } // -- Helper Methods -- /** * Counts the number of slices in the provided ImgPlus. * <p> * NumSlices = product of the sizes of all non-X,Y planes. * </p> */ private int countSlices(final SCIFIOImgPlus<?> img) { int sliceCount = 1; for (int i = 0; i < img.numDimensions(); i++) { if (!(img.axis(i).type().equals(Axes.X) || img.axis(i).type().equals( Axes.Y))) { sliceCount *= img.dimension(i); } } return sliceCount; } /** * Iterates through the planes of the provided {@link SCIFIOImgPlus}, * converting each to a byte[] if necessary (the SCIFIO writer requires a * byte[]) and saving the plane. Currently only {@link PlanarImg} is * supported. * * @throws IncompatibleTypeException */ private void writePlanes(Writer w, final SCIFIOImgPlus<?> img, final int imageIndex, final SCIFIOConfig config) throws ImgIOException, IncompatibleTypeException { final PlanarAccess<?> planarAccess = utils().getPlanarAccess(img); if (planarAccess == null) { throw new IncompatibleTypeException(new ImgLibException(), "Only " + PlanarAccess.class + " images supported at this time."); } final PlanarImg<?, ?> planarImg = (PlanarImg<?, ?>) planarAccess; final int planeCount = planarImg.numSlices(); final Metadata mOut = w.getMetadata(); final int rgbChannelCount = mOut.get(imageIndex).isMultichannel() ? (int) mOut.get(imageIndex) .getAxisLength(Axes.CHANNEL) : 1; final boolean interleaved = mOut.get(imageIndex).getInterleavedAxisCount() > 0; if (img.numDimensions() > 0) { final Class<?> arrayType = planarImg.getPlane(0).getCurrentStorageArray().getClass(); byte[] sourcePlane = null; // if we know this image will pass to SCIFIO to be saved, // then delete the old file if it exists if (arrayType == int[].class || arrayType == byte[].class || arrayType == short[].class || arrayType == long[].class || arrayType == double[].class || arrayType == float[].class) { final File f = new File(img.getSource()); if (f.exists()) { f.delete(); w = initializeWriter(img.getSource(), img, imageIndex, config); } } // iterate over each plane final long planeOutCount = w.getMetadata().get(imageIndex).getPlaneCount(); if (planeOutCount < planeCount / rgbChannelCount) { // Warn that some planes were truncated (e.g. going from 4D format to statusService.showStatus(0, 0, "Source dataset contains: " + planeCount + " planes, but writer format only supports: " + rgbChannelCount * planeOutCount, true); } for (int planeIndex = 0; planeIndex < planeOutCount; planeIndex++) { statusService.showStatus(planeIndex, (int) planeOutCount, "Saving plane " + (planeIndex + 1) + "/" + planeOutCount); // save bytes try { final Metadata meta = w.getMetadata(); final long[] planarLengths = meta.get(imageIndex).getAxesLengthsPlanar(); final long[] planarMin = SCIFIOMetadataTools.modifyPlanar(imageIndex, meta, new long[planarLengths.length]); final ByteArrayPlane destPlane = new ByteArrayPlane(getContext(), meta.get(imageIndex), planarMin, planarLengths); for (int cIndex = 0; cIndex < rgbChannelCount; cIndex++) { final Object curPlane = planarImg.getPlane(cIndex + (planeIndex * rgbChannelCount)) .getCurrentStorageArray(); // Convert current plane if necessary if (arrayType == int[].class) { sourcePlane = DataTools.intsToBytes((int[]) curPlane, false); } else if (arrayType == byte[].class) { sourcePlane = (byte[]) curPlane; } else if (arrayType == short[].class) { sourcePlane = DataTools.shortsToBytes((short[]) curPlane, false); } else if (arrayType == long[].class) { sourcePlane = DataTools.longsToBytes((long[]) curPlane, false); } else if (arrayType == double[].class) { sourcePlane = DataTools.doublesToBytes((double[]) curPlane, false); } else if (arrayType == float[].class) { sourcePlane = DataTools.floatsToBytes((float[]) curPlane, false); } else { throw new IncompatibleTypeException(new ImgLibException(), "PlanarImgs of type " + planarImg.getPlane(0).getClass() + " not supported."); } if (interleaved) { final int bpp = FormatTools.getBytesPerPixel(meta.get(imageIndex) .getPixelType()); // TODO: Assign all elements in a for loop rather than // using many small System.arraycopy calls. Calling // System.arraycopy is less efficient than element-by-element // copying for small array lengths (~24 elements or less). for (int i = 0; i < sourcePlane.length / bpp; i += bpp) { System.arraycopy(sourcePlane, i, destPlane.getData(), ((i * rgbChannelCount) + cIndex) * bpp, bpp); } } else { // TODO: Consider using destPlane.setData(sourcePlane) instead. // Ideally would also make modifications to avoid the initial // allocation overhead of the destPlane's internal buffer. System.arraycopy(sourcePlane, 0, destPlane.getData(), cIndex * sourcePlane.length, sourcePlane.length); } } w.savePlane(imageIndex, planeIndex, destPlane); } catch (final FormatException e) { throw new ImgIOException(e); } catch (final IOException e) { throw new ImgIOException(e); } } } try { w.close(); } catch (final IOException e) { throw new ImgIOException(e); } } /** * Creates a new {@link Writer} and sets its id to the provided String. */ private Writer initializeWriter(final String id, final SCIFIOImgPlus<?> img, final int imageIndex, final SCIFIOConfig config) throws ImgIOException { Writer writer = null; Metadata meta = null; try { writer = formatService.getWriterByExtension(id); meta = writer.getFormat().createMetadata(); populateMeta(meta, img, config); writer.setMetadata(meta); writer.setDest(id, imageIndex, config); } catch (final FormatException e) { throw new ImgIOException(e); } catch (final IOException e) { throw new ImgIOException(e); } return writer; } /** * Uses the provided {@link SCIFIOImgPlus} to populate the minimum metadata fields * necessary for writing. */ private void populateMeta(final Metadata meta, final SCIFIOImgPlus<?> img, final SCIFIOConfig config) throws ImgIOException { statusService.showStatus("Initializing " + img.getName()); // Get format-specific metadata Metadata imgMeta = img.getMetadata(); List<ImageMetadata> imageMeta = new ArrayList<ImageMetadata>(); if (imgMeta == null) { imgMeta = new DefaultMetadata(); imgMeta.createImageMetadata(1); imageMeta.add(imgMeta.get(0)); } else { for (int i=0; i<imgMeta.getImageCount(); i++) { imageMeta.add(new DefaultImageMetadata()); } } // Create Img-specific ImageMetadata final int pixelType = utils().makeType(img.firstElement()); // TODO is there some way to consolidate this with the isCompressible // method? final CalibratedAxis[] axes = new CalibratedAxis[img.numDimensions()]; img.axes(axes); final long[] axisLengths = new long[img.numDimensions()]; img.dimensions(axisLengths); for (int i = 0; i < imageMeta.size(); i++) { ImageMetadata iMeta = imageMeta.get(i); iMeta.populate(Arrays.asList(axes), axisLengths, pixelType, true, false, false, false, true); // Adjust for RGB information if (img.getCompositeChannelCount() > 1) { if (config.imgSaverGetWriteRGB()) { iMeta.setPlanarAxisCount(3); } iMeta.setAxisType(2, Axes.CHANNEL); // Split Axes.CHANNEL if necessary if (iMeta.getAxisLength(Axes.CHANNEL) > img.getCompositeChannelCount()) { iMeta.addAxis(Axes.get("Channel-planes", false), iMeta .getAxisLength(Axes.CHANNEL) / img.getCompositeChannelCount()); iMeta.setAxisLength(Axes.CHANNEL, img.getCompositeChannelCount()); } } } // Translate to the output metadata Translator t = translatorService.findTranslator(imgMeta, meta, false); t.translate(imgMeta, imageMeta, meta); } }
package authoring.gameObjects; import javax.imageio.ImageIO; import javax.swing.*; import com.sun.org.apache.bcel.internal.Constants; import Data.FileLister; import authoring.SpringUtilities; import authoring.features.FeatureManager; import java.awt.FlowLayout; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.*; /** * Creation class for players and enemies. Handles the GUI creation window * @author Pritam M, Richard Cao, Davis Treybig, Jacob Lettie * */ @SuppressWarnings("ALL") public class PlayerEnemyCreation extends CommonAttributes implements ActionListener { private JComboBox<String> playerEnemyImages; private String[] weaponNames; private String[] itemNames; private JRadioButton isRandomEnemy; private JRadioButton isEnemy; private ButtonGroup movementCheck; private JTextField mon; private JTextField exp; public PlayerEnemyCreation(){} @Override public void actionPerformed(ActionEvent e) { if("mapenemy".equals(e.getActionCommand())){ playerEnemyImages.setEnabled(true); itemList.setEnabled(false); xcoor.setEnabled(true); ycoor.setEnabled(true); mon.setEnabled(true); exp.setEnabled(true); worldList.setEnabled(false); } else if("random".equals(e.getActionCommand())){ playerEnemyImages.setEnabled(false); itemList.setEnabled(false); xcoor.setEnabled(false); ycoor.setEnabled(false); mon.setEnabled(true); exp.setEnabled(true); worldList.setEnabled(true); } else{ playerEnemyImages.setEnabled(true); itemList.setEnabled(true); xcoor.setEnabled(true); ycoor.setEnabled(true); mon.setEnabled(false); exp.setEnabled(false); worldList.setEnabled(false); } } /** * Creates the GUI creation window */ public void creationPanel(){ JTabbedPane pane = new JTabbedPane(); String weaponItemTab = "Weapon/Items"; ButtonGroup buttonChoices = new ButtonGroup(); JRadioButton isPlayer = new JRadioButton("Player"); isPlayer.setSelected(true); isPlayer.setActionCommand("player"); isPlayer.addActionListener(this); isEnemy = new JRadioButton("Map Enemy"); isEnemy.setActionCommand("mapenemy"); isEnemy.addActionListener(this); isEnemy.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if(e.getStateChange()==ItemEvent.SELECTED){ one.setEnabled(true); two.setEnabled(true); three.setEnabled(true); } else{ one.setEnabled(false); two.setEnabled(false); three.setEnabled(false); } } }); isRandomEnemy = new JRadioButton("Random Enemy"); isRandomEnemy.setActionCommand("random"); isRandomEnemy.addActionListener(this); worldList = new JComboBox(getWorldArray()); worldList.setEnabled(false); playerEnemyImages = spriteField(); JPanel namePanel = nameImageFields(); JPanel superNamePanel = new JPanel(); superNamePanel.setLayout(new BoxLayout(superNamePanel,BoxLayout.PAGE_AXIS)); superNamePanel.add(namePanel); superNamePanel.add(worldList); superNamePanel.add(playerEnemyImages); JPanel personPanel = new JPanel(); buttonChoices.add(isPlayer); buttonChoices.add(isEnemy); buttonChoices.add(isRandomEnemy); personPanel.add(isPlayer); personPanel.add(isEnemy); personPanel.add(isRandomEnemy); superNamePanel.add(personPanel); JPanel movementPanel = new JPanel(); movementCheck = new ButtonGroup(); one = new JCheckBox("1: Side-Side"); two = new JCheckBox("2: Player Follow"); three = new JCheckBox("3: Stand-Still"); one.setEnabled(false); two.setEnabled(false); three.setEnabled(false); movementCheck.add(one); movementCheck.add(two); movementCheck.add(three); movementPanel.add(one); movementPanel.add(two); movementPanel.add(three); superNamePanel.add(movementPanel); JPanel locationPanel = locationFields(); JPanel obtainPanel = new JPanel(new SpringLayout()); JLabel money = new JLabel("Money:"); JLabel experience = new JLabel("Experience:"); mon = new JTextField("100",5); exp = new JTextField("50",5); mon.setEnabled(false); exp.setEnabled(false); obtainPanel.add(money); money.setLabelFor(mon); obtainPanel.add(mon); obtainPanel.add(experience); experience.setLabelFor(exp); obtainPanel.add(exp); SpringUtilities.makeCompactGrid(obtainPanel,2,2,6,10,6,10); JPanel combinePanel = new JPanel(); combinePanel.setLayout(new BoxLayout(combinePanel,BoxLayout.PAGE_AXIS)); combinePanel.add(locationPanel); combinePanel.add(obtainPanel); JLabel playInfo = new JLabel("Player: max - 4 weapons & 4 items",JLabel.CENTER); JLabel meneInfo = new JLabel("Map Enemy: max - 4 weapons & no items",JLabel.CENTER); JLabel randInfo = new JLabel("Random Enemy: max - 1 weapon & no items",JLabel.CENTER); JPanel infoPanel = new JPanel(); infoPanel.setLayout(new BoxLayout(infoPanel,BoxLayout.PAGE_AXIS)); infoPanel.add(playInfo); infoPanel.add(meneInfo); infoPanel.add(randInfo); JPanel overPanel = new JPanel(); overPanel.setLayout(new BoxLayout(overPanel,BoxLayout.PAGE_AXIS)); JPanel weaponItemPanel = new JPanel(); weaponItemPanel.setLayout(new BoxLayout(weaponItemPanel,BoxLayout.LINE_AXIS)); weaponList = new JList(weaponListModel); weaponList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); weaponList.setVisibleRowCount(5); weaponList.setTransferHandler(new TransferHandler(){ public boolean canImport(TransferSupport info){ if(!info.isDataFlavorSupported(DataFlavor.stringFlavor)){ return false; } JList.DropLocation dl = (JList.DropLocation)info.getDropLocation(); if(dl.getIndex()==-1){ return false; } return true; } public boolean importData(TransferSupport info){ if(!info.isDrop()){ return false; } if(!info.isDataFlavorSupported(DataFlavor.stringFlavor)){ return false; } JList.DropLocation dl = (JList.DropLocation)info.getDropLocation(); DefaultListModel listModel = (DefaultListModel) weaponList.getModel(); int index = dl.getIndex(); boolean insert = dl.isInsert(); Transferable t = info.getTransferable(); String data; try{ data = (String)t.getTransferData(DataFlavor.stringFlavor); } catch (Exception e){ return false; } if(insert){ listModel.add(index,data); } else{ listModel.set(index,data); } return true; } }); itemList = new JList(itemListModel); itemList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); itemList.setVisibleRowCount(5); JScrollPane weaponScroll = new JScrollPane(weaponList); JScrollPane itemScroll = new JScrollPane(itemList); weaponItemPanel.add(weaponScroll); weaponItemPanel.add(itemScroll); overPanel.add(infoPanel); overPanel.add(weaponItemPanel); pane.add(nameTab,superNamePanel); pane.add(locationTab,combinePanel); pane.add(attributeTab,attributeFields()); pane.add(weaponItemTab,overPanel); frame=new JFrame("Player/Enemy Creation"); frame.setLayout(new FlowLayout()); frame.add(pane); JButton createNPC=new JButton("Create Player/Enemy"); createNPC.addActionListener(new PlayerEnemyActionListener()); frame.add(createNPC); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); iterateWeaponsAndItems(); } private class PlayerEnemyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { name = itemName.getText(); x = Integer.parseInt(xcoor.getText()); y = Integer.parseInt(ycoor.getText()); image = (String) playerEnemyImages.getSelectedItem(); for(String s: textValues.keySet()){ attributeValues.put(s,Integer.parseInt(textValues.get(s).getText())); } int wListSize = weaponList.getModel().getSize(); int iListSize = itemList.getModel().getSize(); int wCounter = 0; int iCounter = 0; weaponNames = new String[wListSize]; itemNames = new String[iListSize]; for(Object o: weaponList.getSelectedValuesList()){ String weaponName = (String)o; weaponNames[wCounter] = weaponName; wCounter++; } for(Object p: itemList.getSelectedValuesList()){ String item = (String)p; itemNames[iCounter] = item; iCounter++; } if(isEnemy.isSelected()||isRandomEnemy.isSelected()){ if(isRandomEnemy.isSelected()){ makeRandomEnemy(); } else { movement = movementCheck.getSelection(); makeEnemy(); } } else{ makePlayer(); } frame.dispose(); } } /** * Makes the corresponding random enemy based on user-input */ private void makeRandomEnemy() { RandomEnemy madeRandomEnemy = new RandomEnemy(0,0, editor.getSelectedImage().getDescription(),name,attributeValues,weaponNames,0, Integer.parseInt(mon.getText()),Integer.parseInt(exp.getText())); FeatureManager.getWorldData().saveRandomEnemy(madeRandomEnemy); FeatureManager.getWorldData().getMap((String)worldList.getSelectedItem()).saveRandomEnemy(madeRandomEnemy); } /** * Gets the movement type from the check boxes * @return Integer representing the movement type */ private int getMovementType(){ if(one.isSelected()){ return 1; } else if (two.isSelected()){ return 2; } else if (three.isSelected()){ return 3; } return 3; } /** * Makes the corresponding Player based on user-input */ private void makePlayer() { PlayerData madePlayer = new PlayerData(x,y,image,name,attributeValues,weaponNames,itemNames); FeatureManager.getWorldData().setPrimaryMap(FeatureManager.getWorldData().getCurrentMapName()); FeatureManager.getWorldData().savePlayer(madePlayer); addImage(); } /** * Makes the corresponding regular enemy based on user-input */ private void makeEnemy() { EnemyData madeEnemy = new EnemyData(x,y,image,name,attributeValues,weaponNames,getMovementType(), Integer.parseInt(mon.getText()),Integer.parseInt(exp.getText())); FeatureManager.getWorldData().saveEnemy(madeEnemy); addImage(); //madeEnemy.init(); } private void addImage(){ FileLister f=new FileLister(); List<String> imageList=f.getFileList(util.Constants.PLAYER_IMAGE_FILE+image); String first=imageList.get(0); System.out.println(first); File img=new File(util.Constants.PLAYER_IMAGE_FILE+image+"/"+first); BufferedImage bimg=null; try { bimg=ImageIO.read(img); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ImageIcon icon=new ImageIcon(bimg); new GridObjectPainter(x, y, 1, 1, icon); } }
package beast.app.packagemanager; import beast.app.util.Arguments; import beast.core.BEASTInterface; import beast.core.BEASTObject; import beast.core.Citation; import beast.core.Description; import beast.core.util.Log; import beast.util.Package; import beast.util.PackageDependency; import beast.util.PackageManager; import beast.util.PackageVersion; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Print the citation annotated in a class inherited from BEASTObject. * Note: The current @Citation is automatically inherited. * If the class has no @Citation but its parent class has, * then it will use the same citation as its parent class. * * Usage: PackageCitations <-instAll> * -instAll use PackageManager to update/install all packages * @author Walter Xie */ public class PackageCitations { // protected final Package pkg; protected File[] libJarFile; protected Map<String, CitedClass> citedClassMap = new TreeMap<>(); //TODO unique citations ? public PackageCitations(Package pkg) { // this.pkg = pkg; try { libJarFile = guessLibJarFile(pkg); assert libJarFile != null; addJarFilesToClassPath(); setCitedClassMap(libJarFile); } catch (IOException e) { e.printStackTrace(); } } public void addJarFilesToClassPath() throws IOException { // add all jars to class path for (File f: libJarFile) PackageManager.addURL(f.toURL()); } public void removeJarFilesFromClassPath() { String separator = System.getProperty("path.separator"); String classpath = System.getProperty("java.class.path"); for (File f: libJarFile) { String fPath = f.toString(); if (classpath.contains(fPath)) { classpath = classpath.replace(separator + fPath, ""); } } System.setProperty("java.class.path", classpath); } /** * Find all cited classes from a {@link Package beast package}. * @return the total number of cited classes * @throws IOException */ public int findAllCitedClasses() { // setCitedClassMap(libJarFile); printCitedClasses(getCitedClassMap()); return getCitedClassMap().size(); } public Map<String, CitedClass> getCitedClassMap() { return citedClassMap; } /** * Add all cited classes from jar files in a {@link Package beast package} lib dir. * @param libJarFile jar files * @throws IOException */ private void setCitedClassMap(File[] libJarFile) throws IOException { for (File f: libJarFile) { Log.info.println("Load classes from : " + f + ""); Map<String, CitedClass> tmp = getAllCitedClasses(f); // add all to the final map tmp.keySet().removeAll(citedClassMap.keySet()); citedClassMap.putAll(tmp); } Log.info.println(); } /** * get a {@link Citation Citation} list from a beast class. * @see BEASTInterface#getCitationList() * @param beastClass * @return */ public List<Citation> getCitationList(Class<?> beastClass) { final Annotation[] classAnnotations = beastClass.getAnnotations(); List<Citation> citations = new ArrayList<>(); for (final Annotation annotation : classAnnotations) { if (annotation instanceof Citation) { citations.add((Citation) annotation); } if (annotation instanceof Citation.Citations) { for (Citation citation : ((Citation.Citations) annotation).value()) { citations.add(citation); } } } return citations; } /** * get a description from a beast class. * @see BEASTInterface#getDescription() * @param beastClass * @return */ public String getDescription(Class<?> beastClass) { final Annotation[] classAnnotations = beastClass.getAnnotations(); for (final Annotation annotation : classAnnotations) { if (annotation instanceof Description) { final Description description = (Description) annotation; return description.value(); } } return "Not documented!!!"; } // find all *.jar in lib, but exclude *.src.jar private File[] guessLibJarFile(Package pkg) throws IOException { // get dir where pkg is installed String dirName = PackageManager.getPackageDir(pkg, pkg.getLatestVersion(), false, null); // beast installed package path File libDir = new File(dirName + File.separator + "lib"); if (!libDir.exists()) throw new IOException("Cannot find package " + pkg.getName() + " in path " + dirName); // first guess: *.jar but exclude *.src.jar File[] libFiles = libDir.listFiles((dir, name) -> name.endsWith(".jar") && !name.endsWith("src.jar")); if (libFiles == null || libFiles.length < 1) throw new IOException("Cannot find jar file in package " + pkg.getName() + " in path " + dirName); return libFiles; } // find all cited classes from a jar file private Map<String, CitedClass> getAllCitedClasses(File libFile) throws IOException { // find all *.class in the jar JarFile jarFile = new JarFile(libFile); Enumeration allEntries = jarFile.entries(); Map<String, CitedClass> citedClassMap = new TreeMap<>(); while (allEntries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) allEntries.nextElement(); String name = jarEntry.getName(); // exclude tests, cern (colt.jar) and com (google) have troubles if ( name.endsWith(".class") && !(name.startsWith("test") || name.startsWith("cern") || name.startsWith("com")) ) { String className = name.replaceAll("/", "\\."); className = className.substring(0, className.lastIndexOf('.')); // if (!className.startsWith("beast")) // System.out.println(className); // System.out.println(System.getProperty("java.class.path")); // making own child classloader // https://stackoverflow.com/questions/60764/how-should-i-load-jars-dynamically-at-runtime/60775#60775 URLClassLoader child = new URLClassLoader(new URL[]{libFile.toURL()}, PackageCitations.class.getClassLoader()); Class<?> beastClass = null; try { beastClass = Class.forName(className, false, child); } catch (Throwable t) { t.printStackTrace(); throw new IOException(className + " cannot be loaded by ClassLoader !"); } // no abstract classes if (!Modifier.isAbstract(beastClass.getModifiers()) && // must implement interface (beastClass.isInterface() && PackageManager.hasInterface(BEASTObject.class, beastClass)) || // must be derived from class (!beastClass.isInterface() && PackageManager.isSubclass(BEASTObject.class, beastClass))) { List<Citation> citations = getCitationList(beastClass); // add citations (if any) if (citations.size() > 0) { // System.out.println(className); CitedClass citedClass = new CitedClass(className, citations); String description = getDescription(beastClass); // add description when having a citation citedClass.setDescription(description); citedClassMap.put(className, citedClass); } } } } return citedClassMap; } // print citedClassMap private void printCitedClasses(Map<String, CitedClass> citedClassMap) { for (Map.Entry<String, CitedClass> entry : citedClassMap.entrySet()) { Log.info.println(entry.getKey()); CitedClass citedClass = entry.getValue(); Log.info.println(citedClass.getCitations()); Log.info.println("Description : " + citedClass.getDescription() + "\n"); } Log.info.println("Find total " + citedClassMap.size() + " cited BEAST classes."); Log.info.println(); } private void toXML(){ //TODO } // use PackageManager to update/install all packages private static void installOrUpdateAllPackages(Map<String, Package> packageMap) throws IOException { Log.info.println("\nStart update/install all packages ...\n"); for (Package aPackage : packageMap.values()) { Map<Package, PackageVersion> packagesToInstall = new HashMap<>(); // always latest version packagesToInstall.put(aPackage, aPackage.getLatestVersion()); try { // Populate given map with versions of packages to install which satisfy dependencies PackageManager.populatePackagesToInstall(packageMap, packagesToInstall); } catch (PackageManager.DependencyResolutionException ex) { Log.err("Installation aborted: " + ex.getMessage()); } // Look through packages to be installed, // and uninstall any that are already installed but not match the version that is to be installed. PackageManager.prepareForInstall(packagesToInstall, false, null); // Download and install specified versions of packages Map<String, String> dirs = PackageManager.installPackages(packagesToInstall, false, null); if (dirs.size() == 0) { Log.info.println("Skip installed latest version package " + aPackage + " " + aPackage.getLatestVersion() + "."); } else { for (String pkgName : dirs.keySet()) Log.info.println("Package " + pkgName + " is installed in " + dirs.get(pkgName) + "."); } } } //find all installed and available packages private static Map<String, Package> getInstalledAvailablePackages() { // String::compareToIgnoreCase Map<String, Package> packageMap = new TreeMap<>(Comparator.comparing(String::toLowerCase)); try { PackageManager.addInstalledPackages(packageMap); PackageManager.addAvailablePackages(packageMap); } catch (PackageManager.PackageListRetrievalException e) { Log.warning.println(e.getMessage()); if (e.getCause() instanceof IOException) Log.warning.println(PackageManager.NO_CONNECTION_MESSAGE); return null; } Log.info.println("Find installed and available " + packageMap.size() + " packages."); return packageMap; } // process citations for pkg and add name to processedPkgMap private static int processCitations(Package pkg, Map<String, PackageCitations> processedPkgMap) throws IOException { if (processedPkgMap.containsKey(pkg.getName())) { PackageCitations packageCitations = processedPkgMap.get(pkg.getName()); packageCitations.addJarFilesToClassPath(); return 0; } else { Log.info.println("====== Package " + (processedPkgMap.size() + 1) + " : " + pkg.getName() + " ======\n"); PackageCitations packageCitations = new PackageCitations(pkg); processedPkgMap.put(pkg.getName(), packageCitations); return packageCitations.findAllCitedClasses(); } } private static void cleanClassPath(Map<String, PackageCitations> processedPkgMap) throws MalformedURLException { for (Map.Entry<String, PackageCitations> entry : processedPkgMap.entrySet()) { if (! (entry.getKey().equalsIgnoreCase("beast2") || entry.getKey().equalsIgnoreCase("beast")) ) { PackageCitations packageCitations = entry.getValue(); packageCitations.removeJarFilesFromClassPath(); } } } // only work for BEASTObject public static void main(String[] args) throws IOException { Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.Option("instAll", "Be careful, it will update/install all available packages."), }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException e) { e.printStackTrace(); } // Map<String, Package> packageMap = getInstalledAvailablePackages(); if (packageMap == null) return; // if (arguments.hasOption("instAll")) installOrUpdateAllPackages(packageMap); // int cc = 0; Map<String, PackageCitations> processedPkgMap = new TreeMap<>(Comparator.comparing(String::toLowerCase)); for (Map.Entry<String, Package> entry : packageMap.entrySet()) { Package pkg = entry.getValue(); // process depended packages first Set<PackageDependency> dependencies = pkg.getDependencies(pkg.getLatestVersion()); for (PackageDependency dependency : dependencies) { Package depPkg = packageMap.get(dependency.dependencyName); cc += processCitations(depPkg, processedPkgMap); } cc += processCitations(pkg, processedPkgMap); cleanClassPath(processedPkgMap); //System.out.println(System.getProperty("java.class.path")); } Log.info.println("====== Summary ======\n"); Log.info.println("Find " + packageMap.size() + " BEAST packages, processed " + processedPkgMap.size() + "."); Log.info.println("Find total " + cc + " cited BEAST classes. \n"); } }
package com.aryan.donttextme.core; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.telephony.SmsMessage; import com.aryan.donttextme.model.SMS; import java.util.ArrayList; public class DataBaseManager extends SQLiteOpenHelper { private SmsMessage SMS; private static final String DATABASE_NAME = "dont_text"; private static final int DATABASE_VERSION = 1; private static final String lock = "lock"; private static final String TABLE_INBOX = "inbox"; private static final String TABLE_BLACKLIST = "black_list"; private static final String TABLE_WHITE_LIST = "white_list"; private static final String TABLE_SETTINGS = "settings"; private static final String COLUMN_TIME = "time"; private static final String COLUMN_SENDER = "sender"; private static final String COLUMN_BODY = "body"; private static final String COLUMN_UNREAD = "unread"; private static final String COLUMN_FILTER_KEY = "filter_key"; private static final String COLUMN_SPECIFIC_NUMBER_FILTER = "specific_number_filter"; private static final String COLUMN_STARTING_NUMBER_FILTER = "starting_number_filter"; private static final String COLUMN_KEYWORD_FILTER = "keyword_filter"; private static final String COLUMN_NUMBER_RANGE_FILTER = "number_range_filter"; private static final String COLUMN_NAME = "name"; private static final int COLUMN_INDEX_FILTER_KEY = 0; private static final int COLUMN_INDEX_COLUMN_NAME = 1; private static final int COLUMN_INDEX_SPECIFIC_NUMBER = 2; private static final int COLUMN_INDEX_STARTING_NUMBER = 3; private static final int COLUMN_INDEX_NUMBER_RANGE = 4; private static final int COLUMN_INDEX_KEYWORD = 5; private static final String PLUS = "+"; private static final String SEPARATOR = "-"; private static final String CREATE_STATEMENT_INBOX = String.format( "CREATE TABLE %s (%s INTEGER PRIMARY KEY, %s TEXT, %s TEXT, %s BOOLEAN, %s INTEGER)", TABLE_INBOX, COLUMN_TIME, COLUMN_SENDER, COLUMN_BODY, COLUMN_UNREAD, COLUMN_FILTER_KEY); private static final String CREATE_STATEMENT_BLACKLIST = String.format( "CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)", TABLE_BLACKLIST, COLUMN_FILTER_KEY, COLUMN_NAME, COLUMN_SPECIFIC_NUMBER_FILTER, COLUMN_STARTING_NUMBER_FILTER, COLUMN_NUMBER_RANGE_FILTER, COLUMN_KEYWORD_FILTER); private static final String CREATE_STATEMENT_WHITE_LIST = String.format( "CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)", TABLE_WHITE_LIST, COLUMN_FILTER_KEY, COLUMN_NAME, COLUMN_SPECIFIC_NUMBER_FILTER, COLUMN_STARTING_NUMBER_FILTER, COLUMN_NUMBER_RANGE_FILTER, COLUMN_KEYWORD_FILTER); public DataBaseManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_STATEMENT_INBOX); db.execSQL(CREATE_STATEMENT_BLACKLIST); db.execSQL(CREATE_STATEMENT_WHITE_LIST); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) { } public ArrayList<SMS> getAllSms() { ArrayList<SMS> list = new ArrayList<SMS>(); SQLiteDatabase db = getReadableDatabase(); synchronized (lock) { Cursor cursor = db.rawQuery(String.format("SELECT %s, %s, %s FROM %s", COLUMN_TIME, COLUMN_SENDER, COLUMN_BODY, TABLE_INBOX), null); long time; String sender; String body; cursor.moveToFirst(); while (!cursor.isAfterLast()) { time = cursor.getLong(0); sender = cursor.getString(1); body = cursor.getString(2); list.add(new SMS(time, sender, body, true, 1)); cursor.moveToNext(); } cursor.close(); } return list; } public boolean isInBlackListAndNotInWhiteList(SmsMessage smsMessage) { SMS = smsMessage; SQLiteDatabase db = getReadableDatabase(); synchronized (lock) { Cursor cursor = db.rawQuery(String.format("SELECT %s FROM %s WHERE %s='%s' AND %s NOT IN(SELECT %s FROM %s)" , COLUMN_FILTER_KEY, TABLE_BLACKLIST, COLUMN_SPECIFIC_NUMBER_FILTER, smsMessage.getOriginatingAddress() , COLUMN_SPECIFIC_NUMBER_FILTER, COLUMN_SPECIFIC_NUMBER_FILTER, TABLE_WHITE_LIST), null); cursor.moveToFirst(); if (!cursor.isAfterLast()) {// sender number is in specific numbers AddToInbox(smsMessage, cursor.getInt(0)); db.close(); return true; } cursor = db.rawQuery(String.format("SELECT %s,%s FROM %s WHERE %s IS NOT NULL AND %s NOT IN (SELECT %s FROM %s)" , COLUMN_FILTER_KEY, COLUMN_KEYWORD_FILTER, TABLE_BLACKLIST, COLUMN_KEYWORD_FILTER , COLUMN_KEYWORD_FILTER, COLUMN_KEYWORD_FILTER, TABLE_WHITE_LIST), null); if (hasTheKeywords(cursor, smsMessage.getMessageBody())) { db.close(); return true; } if (senderAddressIsNumber(smsMessage.getOriginatingAddress())) { cursor = db.rawQuery(String.format("SELECT %s,%s FROM %s WHERE %s IS NOT NULL AND %s NOT IN (SELECT %s FROM %s)" , COLUMN_FILTER_KEY, COLUMN_STARTING_NUMBER_FILTER, TABLE_BLACKLIST, COLUMN_STARTING_NUMBER_FILTER , COLUMN_STARTING_NUMBER_FILTER, COLUMN_STARTING_NUMBER_FILTER, TABLE_WHITE_LIST), null); if (senderNumberIsStartingWith(cursor, smsMessage.getOriginatingAddress())) { db.close(); return true; } cursor = db.rawQuery(String.format("SELECT %s,%s FROM %s WHERE %s IS NOT NULL AND %s NOT IN (SELECT %s FROM %s)" , COLUMN_FILTER_KEY, COLUMN_NUMBER_RANGE_FILTER, TABLE_BLACKLIST, COLUMN_NUMBER_RANGE_FILTER , COLUMN_NUMBER_RANGE_FILTER, COLUMN_NUMBER_RANGE_FILTER, TABLE_WHITE_LIST), null); if (isInNumberRanges(cursor, smsMessage.getOriginatingAddress())) { db.close(); return true; } } } db.close(); return false; } private boolean isInNumberRanges(Cursor cursor, String senderNumber) { cursor.moveToFirst(); if (senderNumber.startsWith(PLUS)) senderNumber = senderNumber.replace(PLUS, ""); long number = Long.getLong(senderNumber); long[] range = new long[2]; String[] temp; while (!cursor.isAfterLast()) { temp = cursor.getString(1).split(SEPARATOR); range[0] = Long.getLong(temp[0]); range[1] = Long.getLong(temp[1]); if (number > range[0] && number < range[1]) { AddToInbox(SMS, cursor.getInt(COLUMN_INDEX_FILTER_KEY)); return true; } cursor.moveToNext(); } return false; } private boolean senderIsInSpecificNumbers(Cursor cursor) { cursor.moveToFirst(); if (!cursor.isAfterLast()) { AddToInbox(SMS, cursor.getInt(COLUMN_INDEX_FILTER_KEY)); return true; } else return false; } private boolean hasTheKeywords(Cursor cursor, String smsBody) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (smsBody.toLowerCase().contains(cursor.getString(1))) { AddToInbox(SMS, cursor.getInt(COLUMN_INDEX_FILTER_KEY)); return true; } cursor.moveToNext(); } return false; } private boolean senderNumberIsStartingWith(Cursor cursor, String senderNumber) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (senderNumber.startsWith(cursor.getString(1))) { AddToInbox(SMS, cursor.getInt(COLUMN_INDEX_FILTER_KEY)); return true; } cursor.moveToNext(); } return false; } private boolean senderAddressIsNumber(String address) { if (address.contains("+")) return true; else if (address.contains("9")) return true; else if (address.contains("0")) return true; else if (address.contains("3")) return true; else if (address.contains("1")) return true; else if (address.contains("2")) return true; else if (address.contains("5")) return true; else if (address.contains("4")) return true; else if (address.contains("7")) return true; else if (address.contains("6")) return true; else return false; } //region Add & Remove public void AddToInbox(SmsMessage smsMessage, int filterKey) { long time = smsMessage.getTimestampMillis(); String sender = smsMessage.getOriginatingAddress(); String body = smsMessage.getMessageBody(); SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_TIME, time); cv.put(COLUMN_SENDER, sender); cv.put(COLUMN_BODY, body); cv.put(COLUMN_UNREAD, true); cv.put(COLUMN_FILTER_KEY, filterKey); db.insert(TABLE_INBOX, null, cv); } db.close(); } public void AddToSpecificNumbersBlackList(String number) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_SPECIFIC_NUMBER_FILTER, number); db.insert(TABLE_BLACKLIST, null, cv); } db.close(); } public void AddToSpecificNumbersWhiteList(String number) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_SPECIFIC_NUMBER_FILTER, number); db.insert(TABLE_WHITE_LIST, null, cv); } db.close(); } public void AddToKeywordsBlackList(String keyword) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_KEYWORD_FILTER, keyword.toLowerCase()); db.insert(TABLE_BLACKLIST, null, cv); } db.close(); } public void AddToKeywordsWhiteList(String keyword) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_KEYWORD_FILTER, keyword.toLowerCase()); db.insert(TABLE_WHITE_LIST, null, cv); } db.close(); } public void AddToStartingNumbersBlackList(String number) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_STARTING_NUMBER_FILTER, number); db.insert(TABLE_BLACKLIST, null, cv); } db.close(); } public void AddToStartingNumbersWhiteList(String number) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); synchronized (lock) { cv.put(COLUMN_STARTING_NUMBER_FILTER, number); db.insert(TABLE_WHITE_LIST, null, cv); } db.close(); } public void AddToNumberRangesBlackList(long[] range) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); String rangeText = String.valueOf(range[0]) + SEPARATOR + String.valueOf(range[1]); synchronized (lock) { cv.put(COLUMN_NUMBER_RANGE_FILTER, rangeText); db.insert(TABLE_BLACKLIST, null, cv); } db.close(); } public void AddToNumberRangesWhiteList(long[] range) { SQLiteDatabase db = getWritableDatabase(); ContentValues cv = new ContentValues(); String rangeText = String.valueOf(range[0]) + SEPARATOR + String.valueOf(range[1]); synchronized (lock) { cv.put(COLUMN_NUMBER_RANGE_FILTER, rangeText); db.insert(TABLE_WHITE_LIST, null, cv); } db.close(); } //end of region public void eraseInbox() { SQLiteDatabase db = getWritableDatabase(); synchronized (lock) { db.delete(TABLE_INBOX, null, null); } db.close(); } public void eraseBlacklist() { SQLiteDatabase db = getWritableDatabase(); synchronized (lock) { db.delete(TABLE_BLACKLIST, null, null); } db.close(); } }
package com.axiastudio.zoefx.view; import com.axiastudio.zoefx.controller.FXController; import javafx.fxml.FXMLLoader; import javafx.fxml.JavaFXBuilderFactory; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import java.io.IOException; import java.net.URL; public class ZoeSceneBuilder { public static Scene build(URL url, DataContext context){ FXMLLoader loader = new FXMLLoader(); loader.setLocation(url); loader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root=null; try { root = (Parent) loader.load(url.openStream()); } catch (IOException e) { e.printStackTrace(); } Scene scene = new Scene(root, 500, 375); ZoeToolBar toolBar = new ZoeToolBar(); AnchorPane pane = (AnchorPane) root; pane.getChildren().add(toolBar); FXController controller = loader.getController(); toolBar.setController(controller); controller.setScene(scene); controller.bindDataContext(context); return scene; } }
package com.bkahlert.nebula.widgets.editor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicReference; import org.apache.log4j.Logger; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Listener; import com.bkahlert.nebula.utils.EventDelegator; import com.bkahlert.nebula.utils.ExecUtils; import com.bkahlert.nebula.utils.NamedJob; import com.bkahlert.nebula.utils.colors.RGB; import com.bkahlert.nebula.widgets.browser.exception.BrowserTimeoutException; import com.bkahlert.nebula.widgets.browser.extended.BootstrapBrowser; import com.bkahlert.nebula.widgets.browser.listener.IAnkerListener; import com.bkahlert.nebula.widgets.composer.Composer; import com.bkahlert.nebula.widgets.composer.Composer.ToolbarSet; import com.bkahlert.nebula.widgets.composer.IAnkerLabelProvider; /** * Instances of this class wrap a {@link BootstrapBrowser} and add load and save * functionality. * <p> * If multiple {@link Editor}s loaded the same information, only the one in * focus saved its changed whereas the other reflect them. * * @param <T> * type of the objects that can be loaded in this {@link Editor} * * @author bkahlert * */ public abstract class Editor<T> extends Composite { private static final Logger LOGGER = Logger.getLogger(Editor.class); /** * Reference to the {@link Editor} that executed the last save action. * <p> * Used to distinguish the saving {@link AbstractMemoView} from the others * which need to reload their contents if they loaded the same object. */ private static Map<Object, List<Editor<Object>>> responsibleEditors = new HashMap<Object, List<Editor<Object>>>(); private static Map<Object, Editor<?>> lastFocussedEditor = new HashMap<Object, Editor<?>>(); private T loadedObject = null; private NamedJob loadJob = null; private final Map<T, Job> saveJobs = new HashMap<T, Job>(); protected Composer composer = null; /** * * @param parent * @param style * @param delayChangeEventUpTo * is the delay that must have been passed in order save the * currently loaded object. If 0 no delay will be applied. The * minimal delay however defined by the wrapped {@link Image}. * @param toolbarSet */ public Editor(Composite parent, int style, final long delayChangeEventUpTo, ToolbarSet toolbarSet) { super(parent, style & ~SWT.BORDER); this.setLayout(new FillLayout()); this.composer = new Composer(this, style & SWT.BORDER, delayChangeEventUpTo, toolbarSet); this.composer.setEnabled(false); this.composer.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { lastFocussedEditor.put(Editor.this.loadedObject, Editor.this); } }); this.composer.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { try { Editor.this.save(); } catch (Exception e1) { LOGGER.error( "Error saving content of " + Editor.this.getClass(), e1); } } }); } public ToolbarSet getToolbarSet() { return this.composer.getToolbarSet(); } @Override public void addListener(int eventType, Listener listener) { if (EventDelegator.mustDelegate(eventType, this)) { this.composer.addListener(eventType, listener); } else { super.addListener(eventType, listener); } } /** * @param ankerListener * @see com.bkahlert.nebula.widgets.browser.Browser#addAnkerListener(com.bkahlert.nebula.widgets.browser.listener.IAnkerListener) */ public void addAnkerListener(IAnkerListener ankerListener) { this.composer.addAnkerListener(ankerListener); } /** * @param ankerListener * @see com.bkahlert.nebula.widgets.browser.Browser#removeAnkerListener(com.bkahlert.nebula.widgets.browser.listener.IAnkerListener) */ public void removeAnkerListener(IAnkerListener ankerListener) { this.composer.removeAnkerListener(ankerListener); } /** * @param ankerLabelProvider * @see com.bkahlert.nebula.widgets.composer.Composer#addAnkerLabelProvider(com.bkahlert.nebula.widgets.composer.IAnkerLabelProvider) */ public void addAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) { this.composer.addAnkerLabelProvider(ankerLabelProvider); } /** * @param ankerLabelProvider * @see com.bkahlert.nebula.widgets.composer.Composer#removeAnkerLabelProvider(com.bkahlert.nebula.widgets.composer.IAnkerLabelProvider) */ public void removeAnkerLabelProvider(IAnkerLabelProvider ankerLabelProvider) { this.composer.removeAnkerLabelProvider(ankerLabelProvider); } /** * * @see com.bkahlert.nebula.widgets.composer.Composer#showSource() */ public void showSource() { this.composer.showSource(); } /** * * @see com.bkahlert.nebula.widgets.composer.Composer#hideSource() */ public void hideSource() { this.composer.hideSource(); } @Override public void setBackground(Color color) { this.composer.setBackground(color); } public void setBackground(RGB rgb) { this.composer.setBackground(rgb); } @Override public boolean setFocus() { lastFocussedEditor.put(this.loadedObject, this); return this.composer.setFocus(); } public T getLoadedObject() { return this.loadedObject; } /** * Loads the given object and immediately returns. * <p> * May safely be called multiple times. If this {@link Editor} is still * loading the current load job is cancelled. * * @ArbitraryThread may be called from whatever thread you like. * * @param objectToLoad * @return the {@link Job} used to load the object; null if no object to be * loaded. * @throws Exception */ public final NamedJob load(final T objectToLoad) { if (responsibleEditors.get(this.loadedObject) != null) { responsibleEditors.get(this.loadedObject).remove(this); if (responsibleEditors.get(this.loadedObject).isEmpty()) { responsibleEditors.remove(this.loadedObject); } } if (this.loadedObject == objectToLoad) { return null; } if (this.loadJob != null) { this.loadJob.cancel(); } if (objectToLoad == null) { // refreshHeader(); this.loadedObject = null; ExecUtils.asyncExec(new Runnable() { @Override public void run() { Editor.this.composer.setSource(""); Editor.this.composer.setEnabled(false); } }); return null; } else { this.loadJob = new NamedJob(Editor.class, "Loading " + objectToLoad) { @SuppressWarnings("unchecked") @Override protected IStatus runNamed(IProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { Editor.this.loadedObject = null; return Status.CANCEL_STATUS; } SubMonitor monitor = SubMonitor.convert(progressMonitor, 3); final AtomicReference<String> html = new AtomicReference<String>(); try { html.set(Editor.this.getHtml(objectToLoad, monitor.newChild(1))); // refreshHeader(); monitor.worked(1); Future<Boolean> success = Editor.this.composer .setSource(html.get()); if (!success.get()) { throw new Exception( "Could not set source's content"); } monitor.worked(1); monitor.done(); Editor.this.loadedObject = objectToLoad; if (responsibleEditors.get(objectToLoad) == null) { responsibleEditors.put(objectToLoad, new ArrayList<Editor<Object>>()); } responsibleEditors.get(objectToLoad).add( (Editor<Object>) Editor.this); ExecUtils.syncExec(new Runnable() { @Override public void run() { Editor.this.composer.setEnabled(true); } }); } catch (Exception e) { boolean log = true; if (e.getCause() != null && e.getCause().getCause() != null) { Throwable cause = e.getCause().getCause(); if (cause.getClass() == BrowserTimeoutException.class || cause.getClass() == SWTException.class) { log = false; } } if (log) { LOGGER.error("Error while loading content of " + objectToLoad, e); } Editor.this.loadedObject = null; return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; this.loadJob.schedule(); return this.loadJob; } } /** * Saves the current content of the {@link Editor} to the loaded object. * * @ArbitraryThread may be called from whatever thread you like. * * @return the {@link Job} used to save the object. * @throws Exception */ public final Job save() throws Exception { String html = ExecUtils.syncExec(new Callable<String>() { @Override public String call() throws Exception { return Editor.this.composer.getSource(); } }); return this.save(html); } /** * Saves the given html to the loaded object. * <p> * In contrast to {@link #save()} this method does not use the * {@link Editor}'s content and thus also works if this widget is being * disposed. * * @ArbitraryThread may be called from whatever thread you like. * * @param html * @return the {@link Job} used to save the object. */ synchronized Job save(final String html) { if (this.loadedObject == null) { return null; } if (lastFocussedEditor.get(this.loadedObject) != this) { return null; } if (responsibleEditors.get(this.loadedObject) != null) { for (Editor<Object> responsibleEditor : responsibleEditors .get(this.loadedObject)) { if (responsibleEditor != this) { responsibleEditor.composer.setSource(html); } } } final T savedLoadedObject = this.loadedObject; if (this.saveJobs.get(savedLoadedObject) != null) { this.saveJobs.get(savedLoadedObject).cancel(); } // make the loaded object still accessible even if another one has been // loaded already so the save job can finish Job saveJob = new Job("Saving " + savedLoadedObject) { @Override protected IStatus run(IProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { return Status.CANCEL_STATUS; } SubMonitor monitor = SubMonitor.convert(progressMonitor, 2); monitor.worked(1); try { Editor.this.setHtml(savedLoadedObject, html, monitor.newChild(1)); } catch (Exception e) { LOGGER.error("Error while saving content of " + savedLoadedObject, e); } monitor.done(); return Status.OK_STATUS; } }; saveJob.schedule(); this.saveJobs.put(savedLoadedObject, saveJob); return saveJob; } /** * Returns the html for the given object. * * @param objectToLoad * @param monitor * @return */ public abstract String getHtml(T objectToLoad, IProgressMonitor monitor) throws Exception; /** * Sets the given html to the loaded object. * * @param loadedObject * @param html * @param monitor */ public abstract void setHtml(T loadedObject, String html, IProgressMonitor monitor) throws Exception; }
package com.ecyrd.jspwiki.filters; import java.util.Properties; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; /** * Provides a base implementation of a PageFilter. None of the callbacks * do anything, so it is a good idea for you to extend from this class * and implement only methods that you need. * * @author Janne Jalkanen */ public class BasicPageFilter implements PageFilter { protected WikiEngine m_engine; /** * If you override this, you should call super.initialize() first. */ public void initialize( WikiEngine engine, Properties properties ) throws FilterException { m_engine = engine; } public String preTranslate( WikiContext wikiContext, String content ) throws FilterException { return content; } public String postTranslate( WikiContext wikiContext, String htmlContent ) throws FilterException { return htmlContent; } public String preSave( WikiContext wikiContext, String content ) throws FilterException { return content; } public void postSave( WikiContext wikiContext, String content ) throws FilterException { } public void destroy( WikiEngine engine ) { } }
package com.edinarobotics.utils.sensors; import com.sun.squawk.util.MathUtils; /** * takes a series of values and smooths them using FIR filtering * */ public class FIRFilter implements FilterDouble{ private double[] tapWeights; private double[] values; /** * constructs a FIR filter that has weights given by tapWeights[] * @param tapWeights is an array of the weights to be assigned to each tap */ public FIRFilter(double[] tapWeights) { this.tapWeights = tapWeights; values = new double[this.tapWeights.length]; } /** * Generates an FIRFilter with size taps as determined by the formula 2k/(n^2+n) * where n = size * @param size, the number of taps to be included in the filter * @return an FIRFilter object */ public static FIRFilter autoWeightedFilter(int size) { double[] tempValues = new double[size]; for(int x = 0; x<tempValues.length; x++) { tempValues[x] = (2*(size-x))/(MathUtils.pow(size, 2)+size); } return new FIRFilter(tempValues); } /** * Performs FIR smoothing on values[] * @param currentVal is the newest value * @return a double representing the FIR smoothed value */ public double filter(double currentVal) { //Shift values over 1 index, then add currentVal to values shiftArray(); values[0] = currentVal; //Filtering double FIRValue = 0.0; for(int index = 0; index<values.length&&index<tapWeights.length; index++) { FIRValue +=values[index]*tapWeights[index]; } return FIRValue; } /** * Shifts the array down one */ private void shiftArray() { double[] tempArray = new double[values.length]; for(int index = 1; index < tempArray.length; index++) { tempArray[index] = values[index-1]; } tempArray[0] = 0.0; values = tempArray; } }
package com.edinarobotics.zeke.subsystems; import com.edinarobotics.utils.log.Level; import com.edinarobotics.utils.log.LogSystem; import com.edinarobotics.utils.log.Logger; import com.edinarobotics.utils.subsystems.Subsystem1816; import com.edinarobotics.zeke.Components; import edu.wpi.first.wpilibj.AnalogPotentiometer; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Talon; public class Shooter extends Subsystem1816 { private Talon winch; private DoubleSolenoid solenoidRelease; private AnalogPotentiometer shooterPot; private DigitalInput lowerLimitSwitch; private Logger log = LogSystem.getLogger("zeke.shooter"); private WinchState winchState; private static final double SCALE = 6.317; private static final double OFFSET = -1.579; private static final double MIN_HEIGHT = 0.0; private static final double SLOW_MOVEMENT_HEIGHT = 1.0; private static final DoubleSolenoid.Value ENGAGED = DoubleSolenoid.Value.kForward; private static final DoubleSolenoid.Value DISENGAGED = DoubleSolenoid.Value.kReverse; public Shooter(int winchPort, int doubleSolenoidForward, int doubleSolenoidReverse, int shooterPort, DigitalInput limitSwitch) { winch = new Talon(winchPort); solenoidRelease = new DoubleSolenoid(doubleSolenoidForward , doubleSolenoidReverse); shooterPot = new AnalogPotentiometer(shooterPort, SCALE, OFFSET); lowerLimitSwitch = limitSwitch; winchState = WinchState.STOPPED; } public void setWinchState(WinchState winchState) { if(winchState != null) { this.winchState = winchState; } else { log.log(Level.SEVERE, "Shooter.setWinchState got null."); } update(); } public double getStringPot() { return shooterPot.get(); } public WinchState getWinchState() { return winchState; } public void update() { if(getStringPot() < MIN_HEIGHT && getShooterLimitSwitch() && (winchState.equals(WinchState.LOWERING) || winchState.equals(WinchState.LOWERING_SLOW))) { winchState = WinchState.STOPPED; } winch.set(winchState.getMotorSpeed()); solenoidRelease.set(winchState.isPistonEngaged() ? ENGAGED : DISENGAGED); } public boolean getShooterLimitSwitch() { return lowerLimitSwitch.get(); } public static final class WinchState { public static final WinchState LOWERING = new WinchState((byte)-1, false, 1.0, "lowering"); public static final WinchState LOWERING_SLOW = new WinchState((byte)-1, false, 0.5, "lowering slow"); public static final WinchState STOPPED = new WinchState((byte)0, false, 0.0, "stopped"); public static final WinchState FREE = new WinchState((byte)1, true, 0.0, "free"); private byte winchState; private boolean isPistonEngaged; private double motorSpeed; private String stateName; private WinchState(byte winchState, boolean isPistonEngaged, double motorSpeed, String stateName) { this.winchState = winchState; this.isPistonEngaged = isPistonEngaged; this.motorSpeed = motorSpeed; this.stateName = stateName; } private byte getWinchState() { return winchState; } private boolean isPistonEngaged() { return isPistonEngaged; } private double getMotorSpeed() { return motorSpeed; } public boolean equals(Object winchState) { if(winchState instanceof WinchState) { return ((WinchState)winchState).getWinchState() == this.getWinchState(); } return false; } public String toString() { return stateName.toLowerCase(); } } }
package com.jcwhatever.bukkit.generic; import com.jcwhatever.bukkit.generic.internal.InternalScriptManager; import com.jcwhatever.bukkit.generic.internal.InternalTitleManager; import com.jcwhatever.bukkit.generic.internal.commands.CommandHandler; import com.jcwhatever.bukkit.generic.internal.listeners.JCGEventListener; import com.jcwhatever.bukkit.generic.inventory.KitManager; import com.jcwhatever.bukkit.generic.items.equipper.EntityEquipperManager; import com.jcwhatever.bukkit.generic.items.equipper.IEntityEquipper; import com.jcwhatever.bukkit.generic.jail.JailManager; import com.jcwhatever.bukkit.generic.regions.RegionManager; import com.jcwhatever.bukkit.generic.scheduler.BukkitTaskScheduler; import com.jcwhatever.bukkit.generic.scheduler.ITaskScheduler; import com.jcwhatever.bukkit.generic.scripting.GenericsScriptEngineManager; import com.jcwhatever.bukkit.generic.titles.GenericsNamedTitleFactory; import com.jcwhatever.bukkit.generic.titles.INamedTitle; import com.jcwhatever.bukkit.generic.titles.TitleManager; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.generic.utils.ScriptUtils; import com.jcwhatever.bukkit.generic.utils.text.TextColor; import org.bukkit.entity.EntityType; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import javax.script.ScriptEngineManager; /** * GenericsLib Bukkit plugin. */ public class GenericsLib extends GenericsPlugin { private static GenericsLib _instance; private static Map<String, GenericsPlugin> _pluginNameMap = new HashMap<>(25); private static Map<Class<? extends GenericsPlugin>, GenericsPlugin> _pluginClassMap = new HashMap<>(25); private InternalTitleManager _titleManager; private JailManager _jailManager; private RegionManager _regionManager; private EntityEquipperManager _equipperManager; private ITaskScheduler _scheduler; private ScriptEngineManager _scriptEngineManager; private InternalScriptManager _scriptManager; private KitManager _kitManager; private CommandHandler _commandHandler; /** * Get the {@code GenericsLib} plugin instance. */ public static GenericsLib getLib() { return _instance; } /** * Get a Bukkit plugin that implements {@code GenericsPlugin} by name. * * @param name The name of the plugin. * * @return Null if not found. */ @Nullable public static GenericsPlugin getGenericsPlugin(String name) { PreCon.notNullOrEmpty(name); return _pluginNameMap.get(name.toLowerCase()); } /** * Get a Bukkit plugin that implements {@code GenericsPlugin}. * * @param pluginClass The plugin class. * * @param <T> The plugin type. * * @return Null if not found. */ @Nullable public static <T extends GenericsPlugin> T getGenericsPlugin(Class<T> pluginClass) { PreCon.notNull(pluginClass); GenericsPlugin plugin = _pluginClassMap.get(pluginClass); if (plugin == null) return null; return pluginClass.cast(plugin); } /** * Get all Bukkit plugins that implement {@code GenericsPlugin}. */ public static List<GenericsPlugin> getGenericsPlugins() { return new ArrayList<>(_pluginNameMap.values()); } /** * Get the default task scheduler. */ public static ITaskScheduler getScheduler() { return _instance._scheduler; } /** * Get the global {@code RegionManager}. */ public static RegionManager getRegionManager() { return _instance._regionManager; } /** * Get the default Jail Manager. */ public static JailManager getJailManager() { return _instance._jailManager; } /** * Get the default entity equipper manager. */ public static EntityEquipperManager getEquipperManager() { return _instance._equipperManager; } /** * Get the default script engine manager. * * <p>Returns an instance of {@code GenericsScriptEngineManager}.</p> * * <p>Engines returned from the script engine manager are singleton * instances that are used globally.</p> */ public static ScriptEngineManager getScriptEngineManager() { return _instance._scriptEngineManager; } /** * Get the default script manager. */ public static InternalScriptManager getScriptManager() { return _instance._scriptManager; } /** * Get an entity equipper from the default entity equipper manager * for the specified entity type. * * @param entityType The entity type */ public static IEntityEquipper getEquipper(EntityType entityType) { return _instance._equipperManager.getEquipper(entityType); } /** * Get the default kit manager. */ public static KitManager getKitManager() { return _instance._kitManager; } /** * Get the default title manager. */ public static TitleManager<INamedTitle> getTitleManager() { return _instance._titleManager; } /** * Get GenericsLib's internal command handler. */ public CommandHandler getCommandHandler() { return _commandHandler; } /** * Constructor. */ public GenericsLib() { super(); _instance = this; } /** * Get the chat prefix. */ @Override public String getChatPrefix() { return TextColor.BLUE + "[" + TextColor.WHITE + "Generics" + TextColor.BLUE + "] " + TextColor.WHITE; } /** * Get the console prefix. */ @Override public String getConsolePrefix() { return getChatPrefix(); } @Override protected void onEnablePlugin() { _commandHandler = new CommandHandler(); _scheduler = new BukkitTaskScheduler(); _scriptEngineManager = new GenericsScriptEngineManager(); _kitManager = new KitManager(this, getDataNode().getNode("kits")); _titleManager = new InternalTitleManager(this, getDataNode().getNode("titles"), new GenericsNamedTitleFactory()); _regionManager = new RegionManager(this); _jailManager = new JailManager(this, "default", getDataNode().getNode("jail")); _equipperManager = new EntityEquipperManager(); registerEventListeners(new JCGEventListener()); registerCommands(_commandHandler); loadScriptManager(); } @Override protected void onDisablePlugin() { // make sure that evaluated scripts are disposed if (_scriptManager != null) { _scriptManager.clearScripts(); } } /* * Register GenericsPlugin instance. */ void registerPlugin(GenericsPlugin plugin) { _pluginNameMap.put(plugin.getName().toLowerCase(), plugin); _pluginClassMap.put(plugin.getClass(), plugin); } /* * Unregister GenericsPlugin instance. */ void unregisterPlugin(GenericsPlugin plugin) { _pluginNameMap.remove(plugin.getName().toLowerCase()); _pluginClassMap.remove(plugin.getClass()); } private void loadScriptManager() { File scriptFolder = new File(getDataFolder(), "scripts"); if (!scriptFolder.exists() && !scriptFolder.mkdirs()) { throw new RuntimeException("Failed to create script folder."); } _scriptManager = new InternalScriptManager(this, scriptFolder); _scriptManager.addScriptApi(ScriptUtils.getDefaultApi(this, _scriptManager)); _scriptManager.reload(); } }
// BBN Technologies // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 package com.jwetherell.openmap.common; public class LatLonPoint { public final static double NORTH_POLE = 90.0; public final static double SOUTH_POLE = -NORTH_POLE; public final static double DATELINE = 180.0; public final static double LON_RANGE = 360.0; public final static double EQUIVALENT_TOLERANCE = 0.00001; protected double lat; protected double lon; protected transient double radLat; protected transient double radLon; /** * Default constructor, values set to 0, 0. */ public LatLonPoint() {} /** * Set the latitude, longitude for this point in decimal degrees. * * @param lat latitude * @param lon longitude. */ public LatLonPoint(double lat, double lon) { setLatLon(lat, lon, false); } /** * Set the latitude, longitude for this point, with the option of noting * whether the values are in degrees or radians. * * @param lat latitude * @param lon longitude. * @param isRadians true of values are radians. */ public LatLonPoint(double lat, double lon, boolean isRadian) { setLatLon(lat, lon, isRadian); } /** * Create Double version from another LatLonPoint. * * @param llp */ public LatLonPoint(LatLonPoint llp) { setLatLon(llp.getY(), llp.getX(), false); } /** * Point2D method, inheriting signature!! * * @param x longitude value in decimal degrees. * @param y latitude value in decimal degrees. */ public void setLocation(double x, double y) { setLatLon(y, x, false); } /** * Set latitude and longitude. * * @param lat latitude in decimal degrees. * @param lon longitude in decimal degrees. */ public void setLatLon(double lat, double lon) { setLatLon(lat, lon, false); } /** * Set latitude and longitude. * * @param lat latitude. * @param lon longitude. * @param isRadians true if lat/lon values are radians. */ public void setLatLon(double lat, double lon, boolean isRadians) { if (isRadians) { radLat = lat; radLon = lon; this.lat = ProjMath.radToDeg(lat); this.lon = ProjMath.radToDeg(lon); } else { this.lat = normalizeLatitude(lat); this.lon = wrapLongitude(lon); radLat = ProjMath.degToRad(lat); radLon = ProjMath.degToRad(lon); } } /** * @return longitude in decimal degrees. */ public double getX() { return lon; } /** * @return latitude in decimal degrees. */ public double getY() { return lat; } /** * @return float latitude in decimal degrees. */ public float getLatitude() { return (float) lat; } /** * @return float longitude in decimal degrees. */ public float getLongitude() { return (float) lon; } /** * @return radian longitude. */ public double getRadLon() { return radLon; } /** * @return radian latitude. */ public double getRadLat() { return radLat; } /** * Set latitude. * * @param lat latitude in decimal degrees */ public void setLatitude(double lat) { this.lat = normalizeLatitude(lat); radLat = ProjMath.degToRad(lat); } /** * Set longitude. * * @param lon longitude in decimal degrees */ public void setLongitude(double lon) { this.lon = wrapLongitude(lon); radLon = ProjMath.degToRad(lon); } /** * Set location values from another lat/lon point. * * @param llp */ public void setLatLon(LatLonPoint llp) { setLatLon(llp.getY(), llp.getX(), false); } /** * Ensure latitude is between the poles. * * @param lat * @return */ public final static float normalizeLatitude(float lat) { return (float) normalizeLatitude((double) lat); } /** * Sets latitude to something sane. * * @param lat latitude in decimal degrees * @return float normalized latitude in decimal degrees (&minus;90&deg; &le; * &phi; &le; 90&deg;) */ public final static double normalizeLatitude(double lat) { if (lat > NORTH_POLE) { lat = NORTH_POLE; } if (lat < SOUTH_POLE) { lat = SOUTH_POLE; } return lat; } /** * Ensure the longitude is between the date line. * * @param lon * @return */ public final static float wrapLongitude(float lon) { return (float) wrapLongitude((double) lon); } /** * Sets longitude to something sane. * * @param lon longitude in decimal degrees * @return float wrapped longitude in decimal degrees (&minus;180&deg; &le; * &lambda; &le; 180&deg;) */ public final static double wrapLongitude(double lon) { if ((lon < -DATELINE) || (lon > DATELINE)) { // System.out.print("LatLonPoint: wrapping longitude " // lon); lon += DATELINE; lon = lon % LON_RANGE; lon = (lon < 0) ? DATELINE + lon : -DATELINE + lon; // Debug.output(" to " + lon); } return lon; } /** * Check if latitude is bogus. Latitude is invalid if lat &gt; 90&deg; or if * lat &lt; &minus;90&deg;. * * @param lat latitude in decimal degrees * @return boolean true if latitude is invalid */ public static boolean isInvalidLatitude(double lat) { return ((lat > NORTH_POLE) || (lat < SOUTH_POLE)); } /** * Check if longitude is bogus. Longitude is invalid if lon &gt; 180&deg; or * if lon &lt; &minus;180&deg;. * * @param lon longitude in decimal degrees * @return boolean true if longitude is invalid */ public static boolean isInvalidLongitude(double lon) { return ((lon < -DATELINE) || (lon > DATELINE)); } /** * Determines whether two LatLonPoints are equal. * * @param obj Object * @return Whether the two points are equal up to a tolerance of 10 <sup>-5 * </sup> degrees in latitude and longitude. */ public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LatLonPoint pt = (LatLonPoint)obj; return (MoreMath.approximately_equal(getY(), pt.getY(), EQUIVALENT_TOLERANCE) && MoreMath.approximately_equal(getX(), pt.getX(), EQUIVALENT_TOLERANCE)); } /** * Find the distance to another LatLonPoint, based on a earth spherical * model. * * @param toPoint LatLonPoint * @return distance, in radians. You can use an com.bbn.openmap.proj.Length * to convert the radians to other units. */ public double distance(LatLonPoint toPoint) { return GreatCircle.sphericalDistance( getRadLat(), getRadLon(), toPoint.getRadLat(), toPoint.getRadLon()); } /** * Find the azimuth to another point, based on the spherical earth model. * * @param toPoint LatLonPoint * @return the azimuth `Az' east of north from this point bearing toward the * one provided as an argument.(-PI &lt;= Az &lt;= PI). * */ public double azimuth(LatLonPoint toPoint) { return GreatCircle.sphericalAzimuth(getRadLat(), getRadLon(), toPoint.getRadLat(), toPoint.getRadLon()); } /** * Get a new LatLonPoint a distance and azimuth from another point, based on the spherical earth model. * @param distance radians * @param azimuth radians * @return */ public LatLonPoint getPoint(double distance, double azimuth) { return GreatCircle.sphericalBetween(getRadLat(), getRadLon(), distance, azimuth); } /** * {@inheritDoc} */ @Override public String toString() { return "Lat="+lat+", Lon="+lon; } }
package com.opera.core.systems; import java.io.File; import java.util.List; import java.util.Map; import com.opera.core.systems.profile.ProfileUtils; import com.opera.core.systems.runner.launcher.OperaLauncherRunner; import com.opera.core.systems.scope.exceptions.CommunicationException; import com.opera.core.systems.scope.internal.OperaIntervals; import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType; import com.opera.core.systems.scope.protos.SystemInputProtos.ModifierPressed; import com.opera.core.systems.scope.services.IDesktopWindowManager; import com.opera.core.systems.scope.services.IDesktopUtils; import com.opera.core.systems.scope.services.ums.SystemInputManager; import com.opera.core.systems.settings.OperaDriverSettings; public class OperaDesktopDriver extends OperaDriver { private IDesktopWindowManager desktopWindowManager; private SystemInputManager systemInputManager; private IDesktopUtils desktopUtils; private ProfileUtils profileUtils; private boolean firstTestRun = true; public OperaDesktopDriver(OperaDriverSettings settings){ super(settings); } /** * For testing override this method. */ protected void init() { super.init(); desktopWindowManager = services.getDesktopWindowManager(); systemInputManager = services.getSystemInputManager(); desktopUtils = services.getDesktopUtils(); // Opera will be running at this point so we can retrieve and // store all the profile folders settings.SetLargePrefsFolder(getLargePreferencesPath()); settings.SetSmallPrefsFolder(getSmallPreferencesPath()); settings.SetCachePrefsFolder(getCachePreferencesPath()); profileUtils = new ProfileUtils(settings); // If the Opera Binary isn't set we are assuming Opera is up and we // can ask it for the location of itself if (this.settings != null && this.settings.getOperaBinaryLocation() == null && this.settings.getNoRestart() == false) { String opera_path = getOperaPath(); logger.info("OperaBinaryLocation retrieved from Opera: " + opera_path); if (!opera_path.isEmpty()) { this.settings.setOperaBinaryLocation(opera_path); // Get pid of Opera, needed to wait for it to quit after calling quit_opera int pid = desktopUtils.getOperaPid(); // Now create the OperaLauncherRunner that we have the binary path this.operaRunner = new OperaLauncherRunner(this.settings); // Quit and wait for opera to quit properly this.services.quit(this.operaRunner, pid); // Delete the profile to start the first test with a clean profile this.profileUtils.deleteProfile(); // Work around stop and restart Opera so the Launcher has control of it now // Initialising the services will start Opera if the OperaLauncherRunner is // setup correctly startOpera(); } } } // TODO: FIXME protected Map<String, String> getServicesList() { Map<String, String> versions = super.getServicesList(); // This is the minimum versions of the services this version // of the web-driver require work versions.put("desktop-window-manager", "2.0"); versions.put("system-input", "1.0"); versions.put("desktop-utils", "2.0"); return versions; } protected IDesktopWindowManager getDesktopWindowManager() { return desktopWindowManager; } protected SystemInputManager getSystemInputManager() { return systemInputManager; } /** * Shutdown the driver without quiting Opera */ public void quitDriver() { super.shutdown(); } /** * Quit Opera */ public void quitOpera() { if (this.operaRunner != null){ if (this.operaRunner.isOperaRunning()) { // Quit Opera this.operaRunner.stopOpera(); // Cut off the services connection to free the port this.services.shutdown(); } } else { // Quit with action as opera wasn't started with the launcher String opera_path = desktopUtils.getOperaPath(); logger.info("OperaBinaryLocation retrieved from Opera: " + opera_path); int pid = 0; if (!opera_path.isEmpty()) { this.settings.setOperaBinaryLocation(opera_path); pid = desktopUtils.getOperaPid(); } // Now create the OperaLauncherRunner that we have the binary path // So we can control the shutdown this.operaRunner = new OperaLauncherRunner(this.settings); // Quit and wait for opera to quit properly this.services.quit(this.operaRunner, pid); // Reset the runner this.operaRunner = null; } } /** * @return active window id */ public int getActiveWindowID() { return desktopWindowManager.getActiveWindowId(); } /** * @param winName * @return list of widgets in the window with name winName * If winName is empty, it gets the widgets in the active window */ public List<QuickWidget> getQuickWidgetList(String winName) { int id = getWindowID(winName); if (id >= 0 || winName.length() == 0) { return getQuickWidgetList(id); } // Couldn't find window with winName return null; } /** * @param winId - windowId of window to get widgets in * @return list of widgets in the window with id winId * If winId -1, gets the widgets in the active window */ public List<QuickWidget> getQuickWidgetList(int winId) { return desktopWindowManager.getQuickWidgetList(winId); } /** * * * @returnlist of windows */ public List<QuickWindow> getWindowList() { return desktopWindowManager.getQuickWindowList(); } /** * @param name * @return window id of window with windowName */ public int getWindowID(String windowName) { return desktopWindowManager.getWindowID(windowName); } /** * @param windowName * @return QuickWindow with the given name */ public QuickWindow getWindow(String windowName) { return desktopWindowManager.getWindow(windowName); } /** * @param windowId * @param widgetName * @return QuickWidget with the given name in the window with id windowId */ public QuickWidget findWidgetByName(int windowId, String widgetName){ return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.NAME, widgetName); } /** * * @param windowId * @param widgetName * @param parentName * @return QuickWidget with widgetName and parent in the window given by windowId */ public QuickWidget findWidgetByName(int windowId, String widgetName, String parentName){ return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.NAME, widgetName, parentName); } public QuickWidget findWidgetByText(int windowId, String text){ return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.TEXT, text); } public QuickWidget findWidgetByText(int windowId, String text, String parentName){ return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.TEXT, text, parentName); } public QuickWidget findWidgetByStringId(int windowId, String stringId){ String text = desktopUtils.getString(stringId); return findWidgetByText(windowId, text); } public QuickWidget findWidgetByStringId(int windowId, String stringId, String parentName){ String text = desktopUtils.getString(stringId); return findWidgetByText(windowId, text, parentName); } public QuickWidget findWidgetByPosition(int windowId, int row, int column){ return desktopWindowManager.getQuickWidgetByPos(windowId, row, column); } public QuickWidget findWidgetByPosition(int windowId, int row, int column, String parentName){ return desktopWindowManager.getQuickWidgetByPos(windowId, row, column, parentName); } public QuickWindow findWindowByName(String windowName){ return desktopWindowManager.getQuickWindow(QuickWidgetSearchType.NAME, windowName); } public QuickWindow findWindowById(int windowId){ return desktopWindowManager.getQuickWindowById(windowId); } /** * @param windowId * @return String: name of the window */ public String getWindowName(int windowId) { return desktopWindowManager.getWindowName(windowId); } /** * * @param enum_text * @return the string specified by the id @param enum_text */ public String getString(String enum_text){ return desktopUtils.getString(enum_text); } public String getOperaPath() { return desktopUtils.getOperaPath(); } public String getLargePreferencesPath() { return desktopUtils.getLargePreferencesPath(); } public String getSmallPreferencesPath() { return desktopUtils.getSmallPreferencesPath(); } public String getCachePreferencesPath() { return desktopUtils.getCachePreferencesPath(); } /** * * @param key * @param modifier * @return */ public void keyPress(String key, List<ModifierPressed> modifiers) { systemInputManager.keyPress(key, modifiers); } public void keyUp(String key, List<ModifierPressed> modifiers) { systemInputManager.keyUp(key, modifiers); } public void keyDown(String key, List<ModifierPressed> modifiers) { systemInputManager.keyDown(key, modifiers); } public int getWindowCount() { //TODO FIXME //return desktopWindowManager.getOpenWindowCount(); return 0; } /** * Execute opera action * @param using - action_name * @param data - data parameter * @param dataString - data string parameter * @param dataStringParam - parameter to data string */ public void operaDesktopAction(String using, int data, String dataString, String dataStringParam) { exec.action(using, data, dataString, dataStringParam); } /* * Starts a process of waiting for a window to show * After this call, messages to the driver about window events are not thrown away, * so that the notification about window shown is not lost because of other events or messages */ public void waitStart() { if (services.getConnection() == null) throw new CommunicationException("waiting for a window failed because Opera is not connected."); services.waitStart(); } /** * Wait for any window update event */ public void waitForWindowUpdated() { waitForWindowUpdated(""); } /** * Wait for any window activated event */ public void waitForWindowActivated() { waitForWindowActivated(""); } /** * Wait for any window close event */ public void waitForWindowClose() { waitForWindowClose(""); } /** * Wait until the window given by the @param win_name is shown, and then returns the * window id of this window * * @param win_name - window to wait for shown event on * @return id of window * @throws CommuncationException if no connection */ public int waitForWindowShown(String win_name) { if (services.getConnection() == null) throw new CommunicationException("waiting for a window failed because Opera is not connected."); return services.waitForDesktopWindowShown(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue()); } /** * Wait until the window given by the @param win_name is updated, and then returns the * window id of this window * * @param win_name - window to wait for shown event on * @return id of window * @throws CommuncationException if no connection */ public int waitForWindowUpdated(String win_name) { if (services.getConnection() == null) throw new CommunicationException("waiting for a window failed because Opera is not connected."); return services.waitForDesktopWindowUpdated(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue()); } /** * Wait until the window given by the @param win_name is activated, and then returns the * window id of this window * * @param win_name - window to wait for shown event on * @return id of window * @throws CommuncationException if no connection */ public int waitForWindowActivated(String win_name) { if (services.getConnection() == null) throw new CommunicationException("waiting for a window failed because Opera is not connected."); return services.waitForDesktopWindowActivated(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue()); } /** * Wait until the window given by the @param win_name is closed, and then returns the * window id of this window * * @param win_name - window to wait for shown event on * @return id of window * @throws CommuncationException if no connection */ public int waitForWindowClose(String win_name) { if (services.getConnection() == null) throw new CommunicationException("waiting for a window failed because Opera is not connected."); return services.waitForDesktopWindowClosed(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue()); } public int waitForWindowLoaded(String win_name) { if (services.getConnection() == null) throw new CommunicationException("waiting for a window failed because Opera is not connected."); return services.waitForDesktopWindowLoaded(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue()); } public void resetOperaPrefs(String newPrefs) { // Always delete and copy over a test profile except for when running // the first test which doesn't have a profile to copy over if (firstTestRun == false || new File(newPrefs).exists()) { // Quit and wait for opera to quit properly quitOpera(); // Cleanup old profile profileUtils.deleteProfile(); // Copy in the profile for the test (only if it exists) profileUtils.copyProfile(newPrefs); // Relaunch Opera and the webdriver service connection startOpera(); } // No longer the first test run firstTestRun = false; } public void deleteOperaPrefs() { profileUtils.deleteProfile(); } private void startOpera() { init(); } }
package com.robrua.orianna.api.core; 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.Map; import java.util.Set; import com.robrua.orianna.api.Utils; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.api.LoadPolicy; import com.robrua.orianna.type.core.staticdata.Champion; import com.robrua.orianna.type.core.staticdata.Item; import com.robrua.orianna.type.core.staticdata.MapDetails; import com.robrua.orianna.type.core.staticdata.Mastery; import com.robrua.orianna.type.core.staticdata.Realm; import com.robrua.orianna.type.core.staticdata.Rune; import com.robrua.orianna.type.core.staticdata.SummonerSpell; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.ItemList; import com.robrua.orianna.type.dto.staticdata.MapData; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; public abstract class StaticDataAPI { private static Set<Long> IGNORE_ITEMS = new HashSet<>(Arrays.asList(new Long[] {0L, 1080L, 2037L, 2039L, 2040L, 3005L, 3039L, 3123L, 3128L, 3131L, 3160L, 3166L, 3167L, 3168L, 3169L, 3175L, 3176L, 3171L, 3186L, 3188L, 3205L, 3206L, 3207L, 3209L, 3210L, 3250L, 3255L, 3265L, 3260L, 3275L, 3270L, 3280L, 3405L, 3406L, 3407L, 3408L, 3409L, 3410L, 3411L, 3412L, 3413L, 3414L, 3415L, 3416L, 3417L, 3419L, 3420L})); private static Set<Long> IGNORE_RUNES = new HashSet<>(Arrays.asList(new Long[] {8028L})); private static Set<Long> IGNORE_SPELLS = new HashSet<>(Arrays.asList(new Long[] {10L})); private static Map<Long, Long> REMAPPED_ITEMS = remappedItems(); /** * @param ID * the ID of the champion to get * @return the champion */ public synchronized static Champion getChampionByID(final long ID) { Champion champion = RiotAPI.store.get(Champion.class, (int)ID); if(champion != null) { return champion; } final com.robrua.orianna.type.dto.staticdata.Champion champ = BaseRiotAPI.getChampion(ID); if(champ == null) { return null; } champion = new Champion(champ); if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getItems(new ArrayList<>(champ.getItemIDs())); } RiotAPI.store.store(champion, (int)ID); return champion; } /** * @param name * the name of the champion to get * @return the champion */ public static Champion getChampionByName(final String name) { final List<Champion> champions = getChampions(); for(final Champion champion : champions) { if(champion.getName().equals(name)) { return champion; } } return null; } /** * @return all the champions */ public synchronized static List<Champion> getChampions() { if(RiotAPI.store.hasAll(Champion.class)) { return RiotAPI.store.getAll(Champion.class); } final ChampionList champs = BaseRiotAPI.getChampions(); final List<Champion> champions = new ArrayList<>(champs.getData().size()); final List<Long> IDs = new ArrayList<>(champions.size()); for(final com.robrua.orianna.type.dto.staticdata.Champion champ : champs.getData().values()) { champions.add(new Champion(champ)); IDs.add(champ.getId().longValue()); } if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getItems(new ArrayList<>(champs.getItemIDs())); } RiotAPI.store.store(champions, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(champions); } /** * @param IDs * the IDs of the champions to get * @return the champions */ public synchronized static List<Champion> getChampionsByID(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Champion> champions = RiotAPI.store.get(Champion.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(champions.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return champions; } if(toGet.size() == 1) { champions.set(index.get(0), getChampionByID(toGet.get(0))); return champions; } getChampions(); final List<Champion> gotten = RiotAPI.store.get(Champion.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { champions.set(id, gotten.get(count++)); } return Collections.unmodifiableList(champions); } /** * @param IDs * the IDs of the champions to get * @return the champions */ public static List<Champion> getChampionsByID(final long... IDs) { return getChampionsByID(Utils.convert(IDs)); } /** * @param names * the names of the champions to get * @return the champions */ public static List<Champion> getChampionsByName(final List<String> names) { final Map<String, Integer> indices = new HashMap<>(); final List<Champion> result = new ArrayList<>(names.size()); int i = 0; for(final String name : names) { indices.put(name, i++); result.add(null); } final List<Champion> champions = getChampions(); for(final Champion champ : champions) { final Integer index = indices.get(champ.getName()); if(index != null) { result.set(index, champ); } } return result; } /** * @param names * the names of the champions to get * @return the champions */ public static List<Champion> getChampionsByName(final String... names) { return getChampionsByName(Arrays.asList(names)); } /** * @param ID * the ID of the item to get * @return the item */ public synchronized static Item getItem(long ID) { if(IGNORE_ITEMS.contains(ID)) { return null; } final Long newID = REMAPPED_ITEMS.get(ID); if(newID != null) { ID = newID.longValue(); } Item item = RiotAPI.store.get(Item.class, (int)ID); if(item != null) { return item; } final com.robrua.orianna.type.dto.staticdata.Item it = BaseRiotAPI.getItem(ID); item = new Item(it); RiotAPI.store.store(item, (int)ID); return item; } /** * @return all the items */ public synchronized static List<Item> getItems() { if(RiotAPI.store.hasAll(Item.class)) { return RiotAPI.store.getAll(Item.class); } final ItemList its = BaseRiotAPI.getItems(); final List<Item> items = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(items.size()); for(final com.robrua.orianna.type.dto.staticdata.Item item : its.getData().values()) { items.add(new Item(item)); IDs.add(item.getId().longValue()); } RiotAPI.store.store(items, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(items); } /** * @param IDs * the IDs of the items to get * @return the items */ public synchronized static List<Item> getItems(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Item> items = RiotAPI.store.get(Item.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { Long ID = IDs.get(i); if(items.get(i) == null && !IGNORE_ITEMS.contains(ID)) { final Long newID = REMAPPED_ITEMS.get(ID); if(newID != null) { ID = newID.longValue(); } toGet.add(ID); index.add(i); } } if(toGet.isEmpty()) { return items; } if(toGet.size() == 1) { items.set(index.get(0), getItem(toGet.get(0))); return items; } getItems(); final List<Item> gotten = RiotAPI.store.get(Item.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { items.add(id, gotten.get(count++)); } return Collections.unmodifiableList(items); } /** * @param IDs * the IDs of the items to get * @return the items */ public static List<Item> getItems(final long... IDs) { return getItems(Utils.convert(IDs)); } /** * @return the languages */ public static List<String> getLanguages() { return BaseRiotAPI.getLanguages(); } /** * @return the language strings */ public static Map<String, String> getLanguageStrings() { final com.robrua.orianna.type.dto.staticdata.LanguageStrings str = BaseRiotAPI.getLanguageStrings(); return str.getData(); } /** * @return information for the maps */ public synchronized static List<MapDetails> getMapInformation() { if(RiotAPI.store.hasAll(MapDetails.class)) { return RiotAPI.store.getAll(MapDetails.class); } final MapData inf = BaseRiotAPI.getMapInformation(); final List<MapDetails> info = new ArrayList<>(inf.getData().size()); final List<Long> IDs = new ArrayList<>(info.size()); for(final com.robrua.orianna.type.dto.staticdata.MapDetails map : inf.getData().values()) { info.add(new MapDetails(map)); IDs.add(map.getMapId().longValue()); } RiotAPI.store.store(info, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(info); } /** * @return all the masteries */ public synchronized static List<Mastery> getMasteries() { if(RiotAPI.store.hasAll(Mastery.class)) { return RiotAPI.store.getAll(Mastery.class); } final MasteryList its = BaseRiotAPI.getMasteries(); final List<Mastery> masteries = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(masteries.size()); for(final com.robrua.orianna.type.dto.staticdata.Mastery mastery : its.getData().values()) { masteries.add(new Mastery(mastery)); IDs.add(mastery.getId().longValue()); } RiotAPI.store.store(masteries, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(masteries); } /** * @param IDs * the IDs of the masteries to get * @return the masteries */ public synchronized static List<Mastery> getMasteries(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Mastery> masteries = RiotAPI.store.get(Mastery.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(masteries.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return masteries; } if(toGet.size() == 1) { masteries.set(index.get(0), getMastery(toGet.get(0))); return masteries; } getMasteries(); final List<Mastery> gotten = RiotAPI.store.get(Mastery.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { masteries.set(id, gotten.get(count++)); } return Collections.unmodifiableList(masteries); } /** * @param IDs * the IDs of the masteries to get * @return the masteries */ public static List<Mastery> getMasteries(final long... IDs) { return getMasteries(Utils.convert(IDs)); } /** * @param ID * the ID of the mastery to get * @return the mastery */ public synchronized static Mastery getMastery(final long ID) { Mastery mastery = RiotAPI.store.get(Mastery.class, (int)ID); if(mastery != null) { return mastery; } final com.robrua.orianna.type.dto.staticdata.Mastery mast = BaseRiotAPI.getMastery(ID); mastery = new Mastery(mast); RiotAPI.store.store(mastery, (int)ID); return mastery; } /** * @return the realm */ public synchronized static Realm getRealm() { Realm realm = RiotAPI.store.get(Realm.class, 0L); if(realm != null) { return realm; } realm = new Realm(BaseRiotAPI.getRealm()); RiotAPI.store.store(realm, 0); return realm; } /** * @param ID * the ID of the rune to get * @return the rune */ public synchronized static Rune getRune(final long ID) { if(IGNORE_RUNES.contains(ID)) { return null; } Rune rune = RiotAPI.store.get(Rune.class, (int)ID); if(rune != null) { return rune; } final com.robrua.orianna.type.dto.staticdata.Rune run = BaseRiotAPI.getRune(ID); rune = new Rune(run); RiotAPI.store.store(rune, (int)ID); return rune; } /** * @return all the runes */ public synchronized static List<Rune> getRunes() { if(RiotAPI.store.hasAll(Rune.class)) { return RiotAPI.store.getAll(Rune.class); } final RuneList its = BaseRiotAPI.getRunes(); final List<Rune> runes = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(runes.size()); for(final com.robrua.orianna.type.dto.staticdata.Rune rune : its.getData().values()) { runes.add(new Rune(rune)); IDs.add(rune.getId().longValue()); } RiotAPI.store.store(runes, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(runes); } /** * @param IDs * the IDs of the runes to get * @return the runes */ public synchronized static List<Rune> getRunes(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Rune> runes = RiotAPI.store.get(Rune.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(runes.get(i) == null && !IGNORE_RUNES.contains(IDs.get(i))) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return runes; } if(toGet.size() == 1) { runes.set(index.get(0), getRune(toGet.get(0))); return runes; } getRunes(); final List<Rune> gotten = RiotAPI.store.get(Rune.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { runes.set(id, gotten.get(count++)); } return Collections.unmodifiableList(runes); } /** * @param IDs * the IDs of the runes to get * @return the runes */ public static List<Rune> getRunes(final long... IDs) { return getRunes(Utils.convert(IDs)); } /** * @param ID * the ID of the summoner spell to get * @return the summoner spell */ public synchronized static SummonerSpell getSummonerSpell(final long ID) { if(IGNORE_SPELLS.contains(ID)) { return null; } SummonerSpell spell = RiotAPI.store.get(SummonerSpell.class, (int)ID); if(spell != null) { return spell; } final com.robrua.orianna.type.dto.staticdata.SummonerSpell spl = BaseRiotAPI.getSummonerSpell(ID); spell = new SummonerSpell(spl); RiotAPI.store.store(spell, (int)ID); return spell; } /** * @return all the summoner spells */ public synchronized static List<SummonerSpell> getSummonerSpells() { if(RiotAPI.store.hasAll(SummonerSpell.class)) { return RiotAPI.store.getAll(SummonerSpell.class); } final SummonerSpellList its = BaseRiotAPI.getSummonerSpells(); final List<SummonerSpell> spells = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(spells.size()); for(final com.robrua.orianna.type.dto.staticdata.SummonerSpell spell : its.getData().values()) { spells.add(new SummonerSpell(spell)); IDs.add(spell.getId().longValue()); } RiotAPI.store.store(spells, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(spells); } /** * @param IDs * the IDs of the summoner spells to get * @return the summoner spells */ public synchronized static List<SummonerSpell> getSummonerSpells(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<SummonerSpell> spells = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(spells.get(i) == null && !IGNORE_SPELLS.contains(IDs.get(i))) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return spells; } if(toGet.size() == 1) { spells.set(index.get(0), getSummonerSpell(toGet.get(0))); return spells; } getSummonerSpells(); final List<SummonerSpell> gotten = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { spells.set(id, gotten.get(count++)); } return Collections.unmodifiableList(spells); } /** * @param IDs * the IDs of the summoner spells to get * @return the summoner spells */ public static List<SummonerSpell> getSummonerSpells(final long... IDs) { return getSummonerSpells(Utils.convert(IDs)); } /** * @return the versions */ public static List<String> getVersions() { return BaseRiotAPI.getVersions(); } /* * a Fix for remapped boot enchants (and any others that crop up) */ private static Map<Long, Long> remappedItems() { final Map<Long, Long> map = new HashMap<>(); map.put(3280L, 1309L); map.put(3282L, 1305L); map.put(3281L, 1307L); map.put(3284L, 1306L); map.put(3283L, 1308L); map.put(3278L, 1333L); map.put(3279L, 1331L); map.put(3250L, 1304L); map.put(3251L, 1302L); map.put(3254L, 1301L); map.put(3255L, 1314L); map.put(3252L, 1300L); map.put(3253L, 1303L); map.put(3263L, 1318L); map.put(3264L, 1316L); map.put(3265L, 1324L); map.put(3266L, 1322L); map.put(3260L, 1319L); map.put(3261L, 1317L); map.put(3262L, 1315L); map.put(3257L, 1310L); map.put(3256L, 1312L); map.put(3259L, 1311L); map.put(3258L, 1313L); map.put(3276L, 1332L); map.put(3277L, 1330L); map.put(3274L, 1326L); map.put(3275L, 1334L); map.put(3272L, 1325L); map.put(3273L, 1328L); map.put(3270L, 1329L); map.put(3271L, 1327L); map.put(3269L, 1321L); map.put(3268L, 1323L); map.put(3267L, 1320L); return map; } }
package com.robrua.orianna.api.core; 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.Map; import java.util.Set; import com.robrua.orianna.api.Utils; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.api.LoadPolicy; import com.robrua.orianna.type.core.staticdata.Champion; import com.robrua.orianna.type.core.staticdata.Item; import com.robrua.orianna.type.core.staticdata.MapDetails; import com.robrua.orianna.type.core.staticdata.Mastery; import com.robrua.orianna.type.core.staticdata.Realm; import com.robrua.orianna.type.core.staticdata.Rune; import com.robrua.orianna.type.core.staticdata.SummonerSpell; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.ItemList; import com.robrua.orianna.type.dto.staticdata.MapData; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; public abstract class StaticDataAPI { private static Set<Long> IGNORE_ITEMS = new HashSet<>(Arrays.asList(new Long[] {0L, 1080L, 2037L, 2039L, 2040L, 3005L, 3039L, 3123L, 3128L, 3131L, 3160L, 3166L, 3167L, 3168L, 3169L, 3175L, 3176L, 3171L, 3186L, 3188L, 3205L, 3206L, 3207L, 3209L, 3210L, 3405L, 3406L, 3407L, 3408L, 3409L, 3410L, 3413L, 3414L, 3415L, 3417L, 3419L, 3420L})); /** * @param ID * the ID of the champion to get * @return the champion */ public synchronized static Champion getChampionByID(final long ID) { Champion champion = RiotAPI.store.get(Champion.class, (int)ID); if(champion != null) { return champion; } final com.robrua.orianna.type.dto.staticdata.Champion champ = BaseRiotAPI.getChampion(ID); if(champ == null) { return null; } champion = new Champion(champ); if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getItems(new ArrayList<>(champ.getItemIDs())); } RiotAPI.store.store(champion, (int)ID); return champion; } /** * @param name * the name of the champion to get * @return the champion */ public static Champion getChampionByName(final String name) { final List<Champion> champions = getChampions(); for(final Champion champion : champions) { if(champion.getName().equals(name)) { return champion; } } return null; } /** * @return all the champions */ public synchronized static List<Champion> getChampions() { if(RiotAPI.store.hasAll(Champion.class)) { return RiotAPI.store.getAll(Champion.class); } final ChampionList champs = BaseRiotAPI.getChampions(); final List<Champion> champions = new ArrayList<>(champs.getData().size()); final List<Long> IDs = new ArrayList<>(champions.size()); for(final com.robrua.orianna.type.dto.staticdata.Champion champ : champs.getData().values()) { champions.add(new Champion(champ)); IDs.add(champ.getId().longValue()); } if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getItems(new ArrayList<>(champs.getItemIDs())); } RiotAPI.store.store(champions, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(champions); } /** * @param IDs * the IDs of the champions to get * @return the champions */ public synchronized static List<Champion> getChampionsByID(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Champion> champions = RiotAPI.store.get(Champion.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(champions.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return champions; } if(toGet.size() == 1) { champions.set(index.get(0), getChampionByID(toGet.get(0))); return champions; } getChampions(); final List<Champion> gotten = RiotAPI.store.get(Champion.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { champions.set(id, gotten.get(count++)); } return Collections.unmodifiableList(champions); } /** * @param IDs * the IDs of the champions to get * @return the champions */ public static List<Champion> getChampionsByID(final long... IDs) { return getChampionsByID(Utils.convert(IDs)); } /** * @param names * the names of the champions to get * @return the champions */ public static List<Champion> getChampionsByName(final List<String> names) { final Map<String, Integer> indices = new HashMap<>(); final List<Champion> result = new ArrayList<>(names.size()); int i = 0; for(final String name : names) { indices.put(name, i++); result.add(null); } final List<Champion> champions = getChampions(); for(final Champion champ : champions) { final Integer index = indices.get(champ.getName()); if(index != null) { result.set(index, champ); } } return result; } /** * @param names * the names of the champions to get * @return the champions */ public static List<Champion> getChampionsByName(final String... names) { return getChampionsByName(Arrays.asList(names)); } /** * @param ID * the ID of the item to get * @return the item */ public synchronized static Item getItem(final long ID) { if(IGNORE_ITEMS.contains(ID)) { return null; } Item item = RiotAPI.store.get(Item.class, (int)ID); if(item != null) { return item; } final com.robrua.orianna.type.dto.staticdata.Item it = BaseRiotAPI.getItem(ID); item = new Item(it); RiotAPI.store.store(item, (int)ID); return item; } /** * @return all the items */ public synchronized static List<Item> getItems() { if(RiotAPI.store.hasAll(Item.class)) { return RiotAPI.store.getAll(Item.class); } final ItemList its = BaseRiotAPI.getItems(); final List<Item> items = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(items.size()); for(final com.robrua.orianna.type.dto.staticdata.Item item : its.getData().values()) { items.add(new Item(item)); IDs.add(item.getId().longValue()); } RiotAPI.store.store(items, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(items); } /** * @param IDs * the IDs of the items to get * @return the items */ public synchronized static List<Item> getItems(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Item> items = RiotAPI.store.get(Item.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(items.get(i) == null && !IGNORE_ITEMS.contains(IDs.get(i))) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return items; } if(toGet.size() == 1) { items.set(index.get(0), getItem(toGet.get(0))); return items; } getItems(); final List<Item> gotten = RiotAPI.store.get(Item.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { items.add(id, gotten.get(count++)); } return Collections.unmodifiableList(items); } /** * @param IDs * the IDs of the items to get * @return the items */ public static List<Item> getItems(final long... IDs) { return getItems(Utils.convert(IDs)); } /** * @return the languages */ public static List<String> getLanguages() { return BaseRiotAPI.getLanguages(); } /** * @return the language strings */ public static Map<String, String> getLanguageStrings() { final com.robrua.orianna.type.dto.staticdata.LanguageStrings str = BaseRiotAPI.getLanguageStrings(); return str.getData(); } /** * @return information for the maps */ public synchronized static List<MapDetails> getMapInformation() { if(RiotAPI.store.hasAll(MapDetails.class)) { return RiotAPI.store.getAll(MapDetails.class); } final MapData inf = BaseRiotAPI.getMapInformation(); final List<MapDetails> info = new ArrayList<>(inf.getData().size()); final List<Long> IDs = new ArrayList<>(info.size()); for(final com.robrua.orianna.type.dto.staticdata.MapDetails map : inf.getData().values()) { info.add(new MapDetails(map)); IDs.add(map.getMapId().longValue()); } RiotAPI.store.store(info, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(info); } /** * @return all the masteries */ public synchronized static List<Mastery> getMasteries() { if(RiotAPI.store.hasAll(Mastery.class)) { return RiotAPI.store.getAll(Mastery.class); } final MasteryList its = BaseRiotAPI.getMasteries(); final List<Mastery> masteries = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(masteries.size()); for(final com.robrua.orianna.type.dto.staticdata.Mastery mastery : its.getData().values()) { masteries.add(new Mastery(mastery)); IDs.add(mastery.getId().longValue()); } RiotAPI.store.store(masteries, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(masteries); } /** * @param IDs * the IDs of the masteries to get * @return the masteries */ public synchronized static List<Mastery> getMasteries(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Mastery> masteries = RiotAPI.store.get(Mastery.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(masteries.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return masteries; } if(toGet.size() == 1) { masteries.set(index.get(0), getMastery(toGet.get(0))); return masteries; } getMasteries(); final List<Mastery> gotten = RiotAPI.store.get(Mastery.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { masteries.set(id, gotten.get(count++)); } return Collections.unmodifiableList(masteries); } /** * @param IDs * the IDs of the masteries to get * @return the masteries */ public static List<Mastery> getMasteries(final long... IDs) { return getMasteries(Utils.convert(IDs)); } /** * @param ID * the ID of the mastery to get * @return the mastery */ public synchronized static Mastery getMastery(final long ID) { Mastery mastery = RiotAPI.store.get(Mastery.class, (int)ID); if(mastery != null) { return mastery; } final com.robrua.orianna.type.dto.staticdata.Mastery mast = BaseRiotAPI.getMastery(ID); mastery = new Mastery(mast); RiotAPI.store.store(mastery, (int)ID); return mastery; } /** * @return the realm */ public synchronized static Realm getRealm() { Realm realm = RiotAPI.store.get(Realm.class, 0L); if(realm != null) { return realm; } realm = new Realm(BaseRiotAPI.getRealm()); RiotAPI.store.store(realm, 0); return realm; } /** * @param ID * the ID of the rune to get * @return the rune */ public synchronized static Rune getRune(final long ID) { Rune rune = RiotAPI.store.get(Rune.class, (int)ID); if(rune != null) { return rune; } final com.robrua.orianna.type.dto.staticdata.Rune run = BaseRiotAPI.getRune(ID); rune = new Rune(run); RiotAPI.store.store(rune, (int)ID); return rune; } /** * @return all the runes */ public synchronized static List<Rune> getRunes() { if(RiotAPI.store.hasAll(Rune.class)) { return RiotAPI.store.getAll(Rune.class); } final RuneList its = BaseRiotAPI.getRunes(); final List<Rune> runes = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(runes.size()); for(final com.robrua.orianna.type.dto.staticdata.Rune rune : its.getData().values()) { runes.add(new Rune(rune)); IDs.add(rune.getId().longValue()); } RiotAPI.store.store(runes, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(runes); } /** * @param IDs * the IDs of the runes to get * @return the runes */ public synchronized static List<Rune> getRunes(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Rune> runes = RiotAPI.store.get(Rune.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(runes.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return runes; } if(toGet.size() == 1) { runes.set(index.get(0), getRune(toGet.get(0))); return runes; } getRunes(); final List<Rune> gotten = RiotAPI.store.get(Rune.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { runes.set(id, gotten.get(count++)); } return Collections.unmodifiableList(runes); } /** * @param IDs * the IDs of the runes to get * @return the runes */ public static List<Rune> getRunes(final long... IDs) { return getRunes(Utils.convert(IDs)); } /** * @param ID * the ID of the summoner spell to get * @return the summoner spell */ public synchronized static SummonerSpell getSummonerSpell(final long ID) { SummonerSpell spell = RiotAPI.store.get(SummonerSpell.class, (int)ID); if(spell != null) { return spell; } final com.robrua.orianna.type.dto.staticdata.SummonerSpell spl = BaseRiotAPI.getSummonerSpell(ID); spell = new SummonerSpell(spl); RiotAPI.store.store(spell, (int)ID); return spell; } /** * @return all the summoner spells */ public synchronized static List<SummonerSpell> getSummonerSpells() { if(RiotAPI.store.hasAll(SummonerSpell.class)) { return RiotAPI.store.getAll(SummonerSpell.class); } final SummonerSpellList its = BaseRiotAPI.getSummonerSpells(); final List<SummonerSpell> spells = new ArrayList<>(its.getData().size()); final List<Long> IDs = new ArrayList<>(spells.size()); for(final com.robrua.orianna.type.dto.staticdata.SummonerSpell spell : its.getData().values()) { spells.add(new SummonerSpell(spell)); IDs.add(spell.getId().longValue()); } RiotAPI.store.store(spells, Utils.toIntegers(IDs), true); return Collections.unmodifiableList(spells); } /** * @param IDs * the IDs of the summoner spells to get * @return the summoner spells */ public synchronized static List<SummonerSpell> getSummonerSpells(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<SummonerSpell> spells = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(IDs)); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(spells.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return spells; } if(toGet.size() == 1) { spells.set(index.get(0), getSummonerSpell(toGet.get(0))); return spells; } getSummonerSpells(); final List<SummonerSpell> gotten = RiotAPI.store.get(SummonerSpell.class, Utils.toIntegers(toGet)); int count = 0; for(final Integer id : index) { spells.set(id, gotten.get(count++)); } return Collections.unmodifiableList(spells); } /** * @param IDs * the IDs of the summoner spells to get * @return the summoner spells */ public static List<SummonerSpell> getSummonerSpells(final long... IDs) { return getSummonerSpells(Utils.convert(IDs)); } /** * @return the versions */ public static List<String> getVersions() { return BaseRiotAPI.getVersions(); } }
package com.tech.frontier.models; import com.tech.frontier.entities.Article; import com.tech.frontier.listeners.DataListener; import java.util.LinkedList; import java.util.List; /** * * * @author mrsimple */ public class ArticleModelImpl implements ArticleModel { List<Article> mCachedArticles = new LinkedList<Article>(); @Override public void saveArticles(List<Article> articles) { mCachedArticles.addAll(articles); } @Override public void loadArticlesFromCache(DataListener<List<Article>> listener) { listener.onComplete(mCachedArticles); } }
package com.topologi.diffx.algorithm; import com.topologi.diffx.event.AttributeEvent; import com.topologi.diffx.event.DiffXEvent; import com.topologi.diffx.event.CloseElementEvent; import com.topologi.diffx.event.OpenElementEvent; /** * Maintains the state of open and closed elements during the processing the Diff-X * algorithm. * * <p>This class has two purposes, firstly to provide an object that is more specialised * than the generic lists and stack for use by the DiffX algorithms. Second, to delegate * some of the complexity of algorithm. * * <p>This class has several methods that are similar to <code>List</code> interface * but does not implement it. * * <p>This class is not synchronised and is not meant to be serializable. * * @author Christophe Lauret * @version 12 May 2005 */ public final class ElementState { /** * The stack of open elements. */ private transient OpenElementEvent[] openElements; /** * The stack open elements changes. */ private transient char[] openChanges; /** * The size of both lists (the number of elements they contains). */ private transient int size; public ElementState(int initialCapacity) throws IllegalArgumentException { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity); this.openElements = new OpenElementEvent[initialCapacity]; this.openChanges = new char[initialCapacity]; } /** * Constructs an empty stack with an initial capacity of 12. */ public ElementState() { this(12); } /** * Increases the capacity of this class instance, if necessary, to ensure * that it can hold at least the number of elements specified by the * minimum capacity argument. * * @param minCapacity The desired minimum capacity. */ public void ensureCapacity(int minCapacity) { int oldCapacity = openElements.length; if (minCapacity > oldCapacity) { // make a copy of the old arrays. OpenElementEvent[] oldElements = this.openElements; char[] oldChanges = this.openChanges; int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // create new arrays this.openElements = new OpenElementEvent[newCapacity]; this.openChanges = new char[newCapacity]; // copy the values of the old arrays into the new ones System.arraycopy(oldElements, 0, this.openElements, 0, this.size); System.arraycopy(oldChanges, 0, this.openChanges, 0, this.size); } } /** * Returns the number of elements in this stack. * * @return the number of elements in this stack. */ public int size() { return this.size; } /** * Tests if this list has no elements. * * @return <code>true</code> if this list has no elements; * <code>false</code> otherwise. */ public boolean isEmpty() { return size == 0; } /** * Returns <code>true</code> if this list contains the specified element. * * @param element Element whose presence is to be tested. * * @return <code>true</code> if the specified element is present; * <code>false</code> otherwise. */ public boolean contains(OpenElementEvent element) { return indexOf(element) >= 0; } /** * Searches for the first occurrence of the given argument, testing * for equality using the <code>equals</code> method. * * @param element The open elemnt to find. * * @return The index of the first occurrence of the argument in this list; * returns <code>-1</code if the object is not found. * * @see com.topologi.diffx.event.DiffXEvent#equals(DiffXEvent) */ public int indexOf(OpenElementEvent element) { if (element == null) { for (int i = 0; i < size; i++) if (openElements[i] == null) return i; } else { for (int i = 0; i < size; i++) if (element.equals(openElements[i])) return i; } return -1; } /** * Returns the index of the last occurrence of the specified object in * this list. * * @param element The desired element. * * @return The index of the last occurrence of the specified open element; * or -1 if not found. */ public int lastIndexOf(OpenElementEvent element) { if (element == null) { for (int i = this.size - 1; i >= 0; i if (this.openElements[i] == null) return i; } else { for (int i = this.size - 1; i >= 0; i if (element.equals(this.openElements[i])) return i; } return -1; } /** * Returns the current open element. * * @return The current open element; or <code>null</code> if none. */ public OpenElementEvent current() { if (!isEmpty()) return this.openElements[size - 1]; else return null; } /** * Returns the change of the current open element. * * @return The change of the current open element; or ' ' if none. */ public char currentChange() { if (!isEmpty()) return this.openChanges[size - 1]; else return ' '; } /** * Indicates whether the specified event is a close element that * matches the name and URI of the current open element. * * @param e The event to check. * * @return <code>true</code> if it matches the current element; * <code>false</code> otherwise. */ public boolean matchCurrent(DiffXEvent e) { // cannot match if empty if (isEmpty()) return false; // cannot match if not a close element event if (!(e instanceof CloseElementEvent)) return false; // check if they match return ((CloseElementEvent)e).match(current()); } /** * Updates the state from the inserted event. * * @param e The inserted event. */ public void insert(DiffXEvent e) { if (e instanceof OpenElementEvent) push((OpenElementEvent)e, '+'); else if (e instanceof CloseElementEvent) pop(); } /** * Updates the state from the formatted event. * * @param e The formatted event. */ public void format(DiffXEvent e) { if (e instanceof OpenElementEvent) push((OpenElementEvent)e, '='); else if (e instanceof CloseElementEvent) pop(); } /** * Updates the state from the deleted event. * * @param e The deleted event. */ public void delete(DiffXEvent e) { if (e instanceof OpenElementEvent) push((OpenElementEvent)e, '-'); else if (e instanceof CloseElementEvent) pop(); } /** * Indicates whether the specified event is a close element that * matches the name and URI of the current open element. * * @param e The event to check. * * @return <code>true</code> if it matches the current element; * <code>false</code> otherwise. */ public boolean okFormat(DiffXEvent e) { // cannot match if not a close element event if (!(e instanceof CloseElementEvent)) return true; // cannot match if empty if (isEmpty()) return false; // check if they match return ((CloseElementEvent)e).match(current()) && openChanges[size - 1] == '='; } /** * Indicates whether the specified event is a close element that * matches the name and URI of the current open element. * * @param e The event to check. * * @return <code>true</code> if it matches the current element; * <code>false</code> otherwise. */ public boolean okInsert(DiffXEvent e) { // cannot match if not a close element event if (!(e instanceof CloseElementEvent)) return true; // cannot match if empty if (isEmpty()) return false; // check if they match return ((CloseElementEvent)e).match(current()) && openChanges[size - 1] == '+'; } /** * Indicates whether the specified event is a close element that * matches the name and URI of the current open element. * * @param e The event to check. * * @return <code>true</code> if it matches the current element; * <code>false</code> otherwise. */ public boolean okDelete(DiffXEvent e) { // cannot match if not a close element event if (!(e instanceof CloseElementEvent)) return true; // cannot match if empty if (isEmpty()) return false; // check if they match return ((CloseElementEvent)e).match(current()) && openChanges[size - 1] == '-'; } /** * Indicates whether the first specified event has priority over the second element. * * It only seem to be the case when the algorithm has the choice between an attribute and another * element. * * @param e1 The element assumed to have priority. * @param e2 The other element. * * @return <code>true</code> if first specified event has priority over the second element; * <code>false</code> otherwise. */ public boolean hasPriorityOver(DiffXEvent e1, DiffXEvent e2) { if (e1 instanceof AttributeEvent && !(e2 instanceof AttributeEvent) && !isEmpty()) return true; return false; } /** * Push the specified open element and flags it with the specified change. * * @param e The open element to push. * @param c The character corresponding to change. */ private void push(OpenElementEvent e, char c) { ensureCapacity(size + 1); this.openElements[size] = e; this.openChanges[size] = c; size++; } /** * Removes the last element from the top of the stack. * * @return The last element from the top of the stack. */ public OpenElementEvent pop() { if (size > 0) { this.size return this.openElements[size]; } return null; } /** * Returns the open element at the specified position in this list. * * @param index index of element to return. * * @return The element at the specified position in this list. * * @throws IndexOutOfBoundsException if index is out of range * <code>(index &lt; 0 || index &gt;= size())</code>. */ public OpenElementEvent get(int index) throws IndexOutOfBoundsException { checkRange(index); return openElements[index]; } /** * Appends the specified element to the end of this list. * * @param o element to be appended to this list. * @return <tt>true</tt> (as per the general contract of Collection.add). */ private boolean add(OpenElementEvent o) { ensureCapacity(size + 1); openElements[size++] = o; return true; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index The index of the element to removed. * * @return The element that was removed from the list. * * @throws IndexOutOfBoundsException if index is out of range * <code>(index &lt; 0 || index &gt;= size())</code>. */ public OpenElementEvent remove(int index) throws IndexOutOfBoundsException { checkRange(index); OpenElementEvent oldValue = this.openElements[index]; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(this.openElements, index+1, this.openElements, index, numMoved); this.openElements[--size] = null; // Let gc do its work return oldValue; } /** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { // Let gc do its work for (int i = 0; i < size; i++) openElements[i] = null; size = 0; } /** * Checks if the given index is in range. If not, throw an appropriate * runtime exception. This method does *not* check if the index is * negative: It is always used immediately prior to an array access, * which throws an ArrayIndexOutOfBoundsException if index is negative. * * @param index The index to check. * * @throws IndexOutOfBoundsException if index is out of range * <code>(index &lt; 0 || index &gt;= size())</code>. */ private void checkRange(int index) throws IndexOutOfBoundsException { if (index >= this.size) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); } }
package com.twinone.locker; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; public class ChangePasswordActivity extends LockActivityBase { private static final String TAG = "Locker"; /** * Value of the first password */ private String mPassword; /** * Whether the user is entering the first or the second password. */ private boolean isFirstPassword = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.locker); initLayout(); // Hide because we're just changing the password ivAppIcon.setVisibility(View.GONE); tvHeader.setText("Change password"); setupFirst(); } private void setupFirst() { mPassword = null; tvFooter.setText("Enter the new password\n4 or more numbers is recommended"); tvPassword.setText(""); isFirstPassword = true; } private void setupSecond() { mPassword = tvPassword.getText().toString(); tvFooter.setText("Confirmation\nEnter the same password again"); tvPassword.setText(""); isFirstPassword = false; } @Override protected void onOkButton() { if (isFirstPassword) { if (tvPassword.getText().toString().isEmpty()) { Toast.makeText(this, "No password entered", Toast.LENGTH_SHORT); } else { setupSecond(); } } else { if (tvPassword.getText().toString().equals(mPassword)) { onPasswordConfirm(); } else { setupFirst(); Toast.makeText(this, "Passwords do not match", Toast.LENGTH_SHORT).show(); Log.d(TAG, "Passwords do not match"); } } } private void onPasswordConfirm() { Log.d(TAG, "Changing password to " + mPassword); boolean isSet = ObserverService.setPassword(this, mPassword); Toast.makeText( this, isSet ? "Password successfully changed" : "Error changing password", Toast.LENGTH_SHORT).show(); if (!isSet) Log.w(TAG, "Password could not be changed!!!"); finish(); } }
package com.xtuple.packworkflow.main; import com.google.android.glass.app.Card; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; //import android.view.GestureDetector; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import com.google.android.glass.touchpad.GestureDetector; import com.google.android.glass.touchpad.Gesture; import com.loopj.android.http.*; import org.json.*; public class MainActivity extends Activity { // create variable instances private GestureDetector mGestureDetector; private static final int SCANDIT_CODE_REQUEST =2; protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //keeps the camera on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Card card1 = new Card(this); card1.setText("Welcome to PackWorkflow!!"); card1.setFootnote("xTuple"); View card1View = card1.getView(); setContentView(card1View); //javascript that final Activity that = this; makeRequest(that); mGestureDetector = createGestureDetector(this); } private void makeRequest(final Activity that){ WebRequest.getOrders(new AsyncHttpResponseHandler() { @Override public void onStart() { // Initiated the request } @Override public void onSuccess(String response) { // Successfully got a response } @Override public void onFailure(Throwable e, String response) { // Response failed :( } @Override public void onFinish() { // Completed the request (either success or failure)\ } }); }; /** * Boiler plate google code */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA) { // Stop the preview and release the camera. // Execute your logic as quickly as possible // so the capture happens quickly. return false; } else { return super.onKeyDown(keyCode, event); } } @Override protected void onResume() { super.onResume(); // Re-acquire the camera and start the preview. } public void scanBarcode(){ Intent i = new Intent(getApplicationContext(), ScanditSDKDemoSimple.class); i.putExtra("VariableParameter","Value"); startActivityForResult(i, SCANDIT_CODE_REQUEST); Log.d("@@@@", "Asking for Barcode"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SCANDIT_CODE_REQUEST && resultCode == RESULT_OK){ Log.d("before","SCANDIT_CODE_REQUEST"); String contents = data.getStringExtra("SCAN_RESULT"); Log.d("after","SCANDIT_CODE_REQUEST"); Card newCard = new Card(this); newCard.setImageLayout(Card.ImageLayout.FULL); newCard.setText(contents); newCard.setFootnote("xTuple"); View card1View1 = newCard.getView(); setContentView(card1View1); } super.onActivityResult(requestCode, resultCode, data); } /* * end of boiler plate */ private GestureDetector createGestureDetector(Context context) { GestureDetector gestureDetector = new GestureDetector(context); //Create a base listener for generic gestures gestureDetector.setBaseListener( new GestureDetector.BaseListener() { @Override public boolean onGesture(Gesture gesture) { if (gesture == Gesture.TAP) { Log.d("@@@@", "TAP"); scanBarcode(); // do something on tap return true; } else if (gesture == Gesture.TWO_TAP) { // do something on two finger tap Log.d("@@@@", "2-TAP"); return true; } else if (gesture == Gesture.SWIPE_RIGHT) { // do something on right (forward) swipe Log.d("@@@@", "SWIPE_RIGHT"); return true; } else if (gesture == Gesture.SWIPE_LEFT) { // do something on left (backwards) swipe Log.d("@@@@", "SWIPE_LEFT"); return true; } return false; } }); gestureDetector.setFingerListener(new GestureDetector.FingerListener() { @Override public void onFingerCountChanged(int previousCount, int currentCount) { // do something on finger count changes } }); gestureDetector.setScrollListener(new GestureDetector.ScrollListener() { @Override public boolean onScroll(float displacement, float delta, float velocity) { return true; // do something on scrolling } }); return gestureDetector; } /* * Send generic motion events to the gesture detector */ @Override public boolean onGenericMotionEvent(MotionEvent event) { if (mGestureDetector != null) { return mGestureDetector.onMotionEvent(event); } return false; } }
package com.yeyaxi.android.sensorfun; import java.util.List; import com.yeyaxi.android.sensorfun.util.SensorDataUtility; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Bundle; import android.os.IBinder; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.TableRow; import android.widget.TextView; public class MainActivity extends Activity { private SensorManager mSensorManager; private List<Sensor> deviceSensors; private static final String TAG = MainActivity.class.getSimpleName(); private TextView accValX; private TextView accValY; private TextView accValZ; private TextView ambTempVal; private TextView gyroValX; private TextView gyroValY; private TextView gyroValZ; private TextView gravityX; private TextView gravityY; private TextView gravityZ; private TextView lightVal; private TextView magValX; private TextView magValY; private TextView magValZ; private TextView linearAccX; private TextView linearAccY; private TextView linearAccZ; private TextView pressureVal; private TextView proxiVal; private TextView relatHumidVal; private TextView rotVecValX; private TextView rotVecValY; private TextView rotVecValZ; // For table rows private TableRow accelRow; private TableRow gyroRow; private TableRow gravityRow; private TableRow linAccRow; private TableRow magRow; private TableRow rotVecRow; private TableRow tempRow; private TableRow lightRow; private TableRow pressureRow; private TableRow proxiRow; private TableRow relaHumidRow; private SensorService mBoundService; private boolean isBind = false; private BroadcastReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); accValX = (TextView) findViewById(R.id.accValX); accValY = (TextView) findViewById(R.id.accValY); accValZ = (TextView) findViewById(R.id.accValZ); ambTempVal = (TextView) findViewById(R.id.tempVal); gyroValX = (TextView) findViewById(R.id.gyroValX); gyroValY = (TextView) findViewById(R.id.gyroValY); gyroValZ = (TextView) findViewById(R.id.gyroValZ); gravityX = (TextView) findViewById(R.id.gravityValX); gravityY = (TextView) findViewById(R.id.gravityValY); gravityZ = (TextView) findViewById(R.id.gravityValZ); lightVal = (TextView) findViewById(R.id.lightVal); magValX = (TextView) findViewById(R.id.magValX); magValY = (TextView) findViewById(R.id.magValY); magValZ = (TextView) findViewById(R.id.magValZ); linearAccX = (TextView) findViewById(R.id.linAccValX); linearAccY = (TextView) findViewById(R.id.linAccValY); linearAccZ = (TextView) findViewById(R.id.linAccValZ); pressureVal = (TextView) findViewById(R.id.pressureVal); proxiVal = (TextView) findViewById(R.id.proxiVal); relatHumidVal = (TextView) findViewById(R.id.relaHumidVal); rotVecValX = (TextView) findViewById(R.id.rotValX); rotVecValY = (TextView) findViewById(R.id.rotValY); rotVecValZ = (TextView) findViewById(R.id.rotValZ); // Init for table rows accelRow = (TableRow) findViewById(R.id.tableRowAccel); gyroRow = (TableRow) findViewById(R.id.tableRowGyro); gravityRow = (TableRow) findViewById(R.id.tableRowGravity); linAccRow = (TableRow) findViewById(R.id.tableRowLinearAcc); magRow = (TableRow) findViewById(R.id.tableRowMagField); rotVecRow = (TableRow) findViewById(R.id.tableRowRotVec); tempRow = (TableRow) findViewById(R.id.tableRowAmbientTemp); lightRow = (TableRow) findViewById(R.id.tableRowLight); pressureRow = (TableRow) findViewById(R.id.tableRowPressure); proxiRow = (TableRow) findViewById(R.id.tableRowProximity); relaHumidRow = (TableRow) findViewById(R.id.tableRowRelaHumid); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getFloatArrayExtra("accelerometer") != null) { float[] accFloats = intent.getFloatArrayExtra("accelerometer"); accValX.setText(SensorDataUtility.roundData(accFloats[0])); accValY.setText(SensorDataUtility.roundData(accFloats[1])); accValZ.setText(SensorDataUtility.roundData(accFloats[2])); } if (intent.getFloatArrayExtra("magnetic_field") != null) { float[] magFloats = intent.getFloatArrayExtra("magnetic_field"); magValX.setText(SensorDataUtility.roundData(magFloats[0])); magValY.setText(SensorDataUtility.roundData(magFloats[1])); magValZ.setText(SensorDataUtility.roundData(magFloats[2])); } if (intent.getFloatArrayExtra("gyroscope") != null) { float[] gyroFloats = intent.getFloatArrayExtra("gyroscope"); gyroValX.setText(SensorDataUtility.roundData(gyroFloats[0])); gyroValY.setText(SensorDataUtility.roundData(gyroFloats[1])); gyroValZ.setText(SensorDataUtility.roundData(gyroFloats[2])); } if (intent.getFloatArrayExtra("light") != null) { float[] lightFloats = intent.getFloatArrayExtra("light"); lightVal.setText(SensorDataUtility.roundData(lightFloats[0])); } if (intent.getFloatArrayExtra("pressure") != null) { float[] pressureFloats = intent.getFloatArrayExtra("pressure"); pressureVal.setText(SensorDataUtility.roundData(pressureFloats[0])); } if (intent.getFloatArrayExtra("proximity") != null) { float[] proxiFloats = intent.getFloatArrayExtra("proximity"); proxiVal.setText(SensorDataUtility.roundData(proxiFloats[0])); } if (intent.getFloatArrayExtra("gravity") != null) { float[] gravityFloats = intent.getFloatArrayExtra("gravity"); gravityX.setText(SensorDataUtility.roundData(gravityFloats[0])); gravityY.setText(SensorDataUtility.roundData(gravityFloats[1])); gravityZ.setText(SensorDataUtility.roundData(gravityFloats[2])); } if (intent.getFloatArrayExtra("linear_acceleration") != null) { float[] linearAccFloats = intent.getFloatArrayExtra("linear_acceleration"); linearAccX.setText(SensorDataUtility.roundData(linearAccFloats[0])); linearAccY.setText(SensorDataUtility.roundData(linearAccFloats[1])); linearAccZ.setText(SensorDataUtility.roundData(linearAccFloats[2])); } if (intent.getFloatArrayExtra("rotation_vector") != null) { float[] rotVecFloats = intent.getFloatArrayExtra("rotation_vector"); rotVecValX.setText(SensorDataUtility.roundData(rotVecFloats[0])); rotVecValY.setText(SensorDataUtility.roundData(rotVecFloats[1])); rotVecValZ.setText(SensorDataUtility.roundData(rotVecFloats[2])); } if (intent.getFloatArrayExtra("relative_humidity") != null) { float[] relatHumidFloats = intent.getFloatArrayExtra("relative_humidity"); relatHumidVal.setText(SensorDataUtility.roundData(relatHumidFloats[0])); } if (intent.getFloatArrayExtra("ambient_temperature") != null) { float[] ambTempFloats = intent.getFloatArrayExtra("ambient_temperature"); ambTempVal.setText(SensorDataUtility.roundData(ambTempFloats[0])); } } }; // bind the service doBindService(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("SensorData")); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); } @Override protected void onDestroy() { doUnbindService(); super.onDestroy(); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub isBind = false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub mBoundService = ((SensorService.SensorBinder) service).getService(); // mBoundService.getMsg(); mSensorManager = mBoundService.getSensorManager(); isBind = true; detectSensors(); } }; private void doBindService() { bindService(new Intent(this, SensorService.class), mConnection, Context.BIND_AUTO_CREATE); } private void doUnbindService() { unbindService(mConnection); } private void detectSensors() { deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL); Log.d(TAG, "" + deviceSensors); if (mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null) { // Log.i(TAG, "Accelerometer"); accelRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) == null) { // Log.i(TAG, "Ambient Temperature"); tempRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) == null) { // Log.i(TAG, "Gravity"); gravityRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) == null) { // Log.i(TAG, "Gyroscope"); gyroRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) == null) { // Log.i(TAG, "Light"); lightRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION) == null) { // Log.i(TAG, "Linear Acceleration"); linAccRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) == null) { // Log.i(TAG, "Magnetic Field"); magRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); } // if (mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION) == null) // Log.i(TAG, "Orientation"); if (mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) == null) { // Log.i(TAG, "Pressure"); pressureRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) == null) { // Log.i(TAG, "Proximity"); proxiRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY) == null) { // Log.i(TAG, "Relative Humidity"); relaHumidRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY), SensorManager.SENSOR_DELAY_NORMAL); } if (mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) == null) { // Log.i(TAG, "Rotation Vector"); rotVecRow.setVisibility(View.GONE); // mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_NORMAL); } } }
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); LOGGER.trace("Location({})", pathname); try { url = new URL(scifio().location().getMappedId(pathname)); } catch (MalformedURLException e) { LOGGER.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); LOGGER.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) { LOGGER.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) { LOGGER.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) { LOGGER.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) { LOGGER.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 whelk.importer; import io.prometheus.client.Counter; import se.kb.libris.util.marc.Datafield; import se.kb.libris.util.marc.Field; import se.kb.libris.util.marc.MarcRecord; import whelk.Document; import whelk.IdGenerator; import whelk.JsonLd; import whelk.Whelk; import whelk.component.ElasticSearch; import whelk.component.PostgreSQLComponent; import whelk.converter.MarcJSONConverter; import whelk.converter.marc.MarcFrameConverter; import whelk.exception.TooHighEncodingLevelException; import whelk.filter.LinkFinder; import whelk.util.LegacyIntegrationTools; import whelk.util.PropertyLoader; import whelk.triples.*; import java.io.IOException; import java.io.UncheckedIOException; import java.sql.*; import java.util.*; class XL { private static final String ENC_PRELIMINARY_STATUS = "marc:PartialPreliminaryLevel"; private static final String ENC_PREPUBLICATION_STATUS = "marc:PrepublicationLevel"; private static final String ENC_ABBREVIVATED_STATUS = "marc:AbbreviatedLevel"; private static final String ENC_MINMAL_STATUS = "marc:MinimalLevel"; private Whelk m_whelk; private LinkFinder m_linkfinder; private Parameters m_parameters; private Properties m_properties; private MarcFrameConverter m_marcFrameConverter; private static boolean verbose = false; // The predicates listed here are those that must always be represented as lists in jsonld, even if the list // has only a single member. private Set<String> m_repeatableTerms; private final static String IMPORT_SYSTEM_CODE = "batch import"; XL(Parameters parameters) throws IOException { m_parameters = parameters; verbose = m_parameters.getVerbose(); m_properties = PropertyLoader.loadProperties("secret"); m_whelk = Whelk.createLoadedSearchWhelk(m_properties); m_repeatableTerms = m_whelk.getJsonld().getRepeatableTerms(); m_marcFrameConverter = m_whelk.createMarcFrameConverter(); m_linkfinder = new LinkFinder(m_whelk.getStorage()); } /** * Write a ISO2709 MarcRecord to LibrisXL. returns a resource ID if the resulting document (merged or new) was in "bib". * This ID should then be passed (as 'relatedWithBibResourceId') when importing any subsequent related holdings post. * Returns null when supplied a hold post. */ String importISO2709(MarcRecord incomingMarcRecord, String relatedWithBibResourceId, Counter importedBibRecords, Counter importedHoldRecords, Counter enrichedBibRecords, Counter enrichedHoldRecords, Counter encounteredMulBibs) throws Exception { String collection = "bib"; // assumption if (incomingMarcRecord.getLeader(6) == 'u' || incomingMarcRecord.getLeader(6) == 'v' || incomingMarcRecord.getLeader(6) == 'x' || incomingMarcRecord.getLeader(6) == 'y') collection = "hold"; Set<String> duplicateIDs = getDuplicates(incomingMarcRecord, collection, relatedWithBibResourceId); String resultingResourceId = null; //System.err.println("Incoming [" + collection + "] document had: " + duplicateIDs.size() + " existing duplicates:\n" + duplicateIDs); // If an incoming holding record is marked deleted, attempt to find any duplicates for it in Libris and delete them. if (collection.equals("hold") && incomingMarcRecord.getLeader(5) == 'd') { for (String id : duplicateIDs) m_whelk.remove(id, IMPORT_SYSTEM_CODE, null); return null; } if (duplicateIDs.size() == 0) // No coinciding documents, simple import { resultingResourceId = importNewRecord(incomingMarcRecord, collection, relatedWithBibResourceId, null); if (collection.equals("bib")) importedBibRecords.inc(); else importedHoldRecords.inc(); } else if (duplicateIDs.size() == 1) // Enrich ("merge") or replace { if (collection.equals("bib")) { if ( m_parameters.getReplaceBib() ) { String idToReplace = duplicateIDs.iterator().next(); resultingResourceId = importNewRecord(incomingMarcRecord, collection, relatedWithBibResourceId, idToReplace); importedBibRecords.inc(); } else // Merge bib { resultingResourceId = enrichRecord((String) duplicateIDs.toArray()[0], incomingMarcRecord, collection, relatedWithBibResourceId); enrichedBibRecords.inc(); } } else // collection = hold { if ( m_parameters.getReplaceHold() ) // Replace hold { String idToReplace = duplicateIDs.iterator().next(); resultingResourceId = importNewRecord(incomingMarcRecord, collection, relatedWithBibResourceId, idToReplace); importedHoldRecords.inc(); } else // Merge hold { resultingResourceId = enrichRecord((String) duplicateIDs.toArray()[0], incomingMarcRecord, collection, relatedWithBibResourceId); enrichedHoldRecords.inc(); } } } else { // Multiple coinciding documents. encounteredMulBibs.inc(); if (m_parameters.getEnrichMulDup()) { for (String id : duplicateIDs) { enrichRecord( id, incomingMarcRecord, collection, relatedWithBibResourceId ); } } if (collection.equals("bib")) { // In order to keep the program deterministic, the bib post to which subsequent holdings should attach // when there are multiple duplicates is defined as the one with the "lowest" alpha numeric id. List<String> duplicateList = new ArrayList<>(duplicateIDs); Collections.sort(duplicateList); String selectedDuplicateId = duplicateList.get(0); if (!selectedDuplicateId.startsWith(Document.getBASE_URI().toString())) selectedDuplicateId = Document.getBASE_URI().toString() + selectedDuplicateId; resultingResourceId = m_whelk.getStorage().getThingId(selectedDuplicateId); } else resultingResourceId = null; } return resultingResourceId; } private String importNewRecord(MarcRecord marcRecord, String collection, String relatedWithBibResourceId, String replaceSystemId) { String incomingId = IdGenerator.generate(); if (replaceSystemId != null) incomingId = replaceSystemId; Document rdfDoc = convertToRDF(marcRecord, incomingId); if (collection.equals("hold")) rdfDoc.setHoldingFor(relatedWithBibResourceId); if (!m_parameters.getReadOnly()) { rdfDoc.setRecordStatus(ENC_PRELIMINARY_STATUS); // Doing a replace (but preserving old IDs) if (replaceSystemId != null) { try { m_whelk.getStorage().storeAtomicUpdate(replaceSystemId, false, IMPORT_SYSTEM_CODE, null, (Document doc) -> { String existingEncodingLevel = doc.getEncodingLevel(); String newEncodingLevel = rdfDoc.getEncodingLevel(); if (existingEncodingLevel == null || !mayOverwriteExistingEncodingLevel(existingEncodingLevel, newEncodingLevel)) throw new TooHighEncodingLevelException(); List<String> recordIDs = doc.getRecordIdentifiers(); List<String> thingIDs = doc.getThingIdentifiers(); String controlNumber = doc.getControlNumber(); doc.data = rdfDoc.data; // The mainID must remain unaffected. doc.deepPromoteId(recordIDs.get(0)); for (String recordID : recordIDs) doc.addRecordIdentifier(recordID); for (String thingID : thingIDs) doc.addThingIdentifier(thingID); if (controlNumber != null) doc.setControlNumber(controlNumber); }); } catch (TooHighEncodingLevelException e) { if ( verbose ) { System.out.println("info: Not replacing id: " + replaceSystemId + ", because it no longer has encoding level marc:PartialPreliminaryLevel"); } } } else { // Doing simple "new" m_whelk.createDocument(rdfDoc, IMPORT_SYSTEM_CODE, null, collection, false); } } else { if ( verbose ) { System.out.println("info: Would now (if --live had been specified) have written the following json-ld to whelk as a new record:\n" + rdfDoc.getDataAsString()); } } if (collection.equals("bib")) return rdfDoc.getThingIdentifiers().get(0); return null; } private String enrichRecord(String ourId, MarcRecord incomingMarcRecord, String collection, String relatedWithBibResourceId) throws IOException { Document rdfDoc = convertToRDF(incomingMarcRecord, ourId); if (collection.equals("hold")) rdfDoc.setHoldingFor(relatedWithBibResourceId); if (!m_parameters.getReadOnly()) { try { m_whelk.storeAtomicUpdate(ourId, false, IMPORT_SYSTEM_CODE, null, (Document doc) -> { if (collection.equals("bib")) { String existingEncodingLevel = doc.getEncodingLevel(); String newEncodingLevel = rdfDoc.getEncodingLevel(); if (existingEncodingLevel == null || !mayOverwriteExistingEncodingLevel(existingEncodingLevel, newEncodingLevel)) throw new TooHighEncodingLevelException(); } enrich( doc, rdfDoc ); }); } catch (TooHighEncodingLevelException e) { if ( verbose ) { System.out.println("info: Not enriching id: " + ourId + ", because it no longer has encoding level marc:PartialPreliminaryLevel"); } } } else { Document doc = m_whelk.getStorage().load( ourId ); enrich( doc, rdfDoc ); if ( verbose ) { System.out.println("info: Would now (if --live had been specified) have written the following (merged) json-ld to whelk:\n"); System.out.println("id:\n" + doc.getShortId()); System.out.println("data:\n" + doc.getDataAsString()); } } if (collection.equals("bib")) return rdfDoc.getThingIdentifiers().get(0); return null; } private boolean mayOverwriteExistingEncodingLevel(String existingEncodingLevel, String newEncodingLevel) { if (newEncodingLevel == null || existingEncodingLevel == null) return false; switch (newEncodingLevel) { case ENC_PRELIMINARY_STATUS: if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS)) return true; break; case ENC_PREPUBLICATION_STATUS: if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS) || existingEncodingLevel.equals(ENC_PREPUBLICATION_STATUS)) // 5 || 8 return true; break; case ENC_ABBREVIVATED_STATUS: if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS) || existingEncodingLevel.equals(ENC_PREPUBLICATION_STATUS)) // 5 || 8 return true; break; case ENC_MINMAL_STATUS: if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS) || existingEncodingLevel.equals(ENC_PREPUBLICATION_STATUS)) // 5 || 8 return true; break; } return false; } private void enrich(Document mutableDocument, Document withDocument) { JsonldSerializer serializer = new JsonldSerializer(); List<String[]> withTriples = serializer.deserialize(withDocument.data); List<String[]> originalTriples = serializer.deserialize(mutableDocument.data); Graph originalGraph = new Graph(originalTriples); Graph withGraph = new Graph(withTriples); // This is temporary, these special rules should not be hardcoded here, but rather obtained from (presumably) // whelk-core's marcframe.json. Map<String, Graph.PREDICATE_RULES> specialRules = new HashMap<>(); for (String term : m_repeatableTerms) specialRules.put(term, Graph.PREDICATE_RULES.RULE_AGGREGATE); specialRules.put("created", Graph.PREDICATE_RULES.RULE_PREFER_ORIGINAL); specialRules.put("controlNumber", Graph.PREDICATE_RULES.RULE_PREFER_ORIGINAL); specialRules.put("modified", Graph.PREDICATE_RULES.RULE_PREFER_INCOMING); specialRules.put("marc:encLevel", Graph.PREDICATE_RULES.RULE_PREFER_ORIGINAL); originalGraph.enrichWith(withGraph, specialRules); Map enrichedData = JsonldSerializer.serialize(originalGraph.getTriples(), m_repeatableTerms); boolean deleteUnreferencedData = true; JsonldSerializer.normalize(enrichedData, mutableDocument.getShortId(), deleteUnreferencedData); mutableDocument.data = enrichedData; } private Document convertToRDF(MarcRecord marcRecord, String id) { while (marcRecord.getControlfields("001").size() > 0) marcRecord.getFields().remove(marcRecord.getControlfields("001").get(0)); marcRecord.addField(marcRecord.createControlfield("001", id)); Map convertedData = m_marcFrameConverter.convert(MarcJSONConverter.toJSONMap(marcRecord), id); Document convertedDocument = new Document(convertedData); convertedDocument.deepReplaceId(Document.getBASE_URI().toString()+id); m_linkfinder.normalizeIdentifiers(convertedDocument); return convertedDocument; } private Set<String> getDuplicates(MarcRecord marcRecord, String collection, String relatedWithBibResourceId) throws SQLException { switch (collection) { case "bib": return getBibDuplicates(marcRecord); case "hold": return getHoldDuplicates(marcRecord, relatedWithBibResourceId); default: return new HashSet<>(); } } private Set<String> getHoldDuplicates(MarcRecord marcRecord, String relatedWithBibResourceId) throws SQLException { Set<String> duplicateIDs = new HashSet<>(); // Assumes the post being imported carries a valid libris id in 001, and "SE-LIBR" or "LIBRIS" in 003 duplicateIDs.addAll(getDuplicatesOnLibrisID(marcRecord, "hold")); duplicateIDs.addAll(getDuplicatesOnHeldByHoldingFor(marcRecord, relatedWithBibResourceId)); return duplicateIDs; } private Set<String> getBibDuplicates(MarcRecord marcRecord) throws SQLException { Set<String> duplicateIDs = new HashSet<>(); for (Parameters.DUPLICATION_TYPE dupType : m_parameters.getDuplicationTypes()) { switch (dupType) { case DUPTYPE_ISBNA: // International Standard Book Number (only from subfield A) for (Field field : marcRecord.getFields("020")) { String isbn = DigId.grepIsbna( (Datafield) field ); if (isbn != null) { duplicateIDs.addAll(getDuplicatesOnISBN( isbn.toUpperCase() )); } } break; case DUPTYPE_ISBNZ: // International Standard Book Number (only from subfield Z) for (Field field : marcRecord.getFields("020")) { String isbn = DigId.grepIsbnz( (Datafield) field ); if (isbn != null) { duplicateIDs.addAll(getDuplicatesOnISBN( isbn.toUpperCase() )); } } break; case DUPTYPE_ISSNA: // International Standard Serial Number (only from marc 022_A) for (Field field : marcRecord.getFields("022")) { String issn = DigId.grepIssn( (Datafield) field, 'a' ); if (issn != null) { duplicateIDs.addAll(getDuplicatesOnISSN( issn.toUpperCase() )); } } break; case DUPTYPE_ISSNZ: // International Standard Serial Number (only from marc 022_Z) for (Field field : marcRecord.getFields("022")) { String issn = DigId.grepIssn( (Datafield) field, 'z' ); if (issn != null) { duplicateIDs.addAll(getDuplicatesOnISSN( issn.toUpperCase() )); } } break; case DUPTYPE_035A: // Unique id number in another system. duplicateIDs.addAll(getDuplicatesOn035a(marcRecord)); break; case DUPTYPE_LIBRISID: // Assumes the post being imported carries a valid libris id in 001, and "SE-LIBR" or "LIBRIS" in 003 duplicateIDs.addAll(getDuplicatesOnLibrisID(marcRecord, "bib")); break; } } return duplicateIDs; } private List<String> getDuplicatesOnLibrisID(MarcRecord marcRecord, String collection) throws SQLException { String librisId = DigId.grepLibrisId(marcRecord); if (librisId == null) return new ArrayList<>(); // completely numeric? = classic voyager id. // In theory an xl id could (though insanely unlikely) also be numeric :( if (librisId.matches("[0-9]+")) { librisId = "http://libris.kb.se/"+collection+"/"+librisId; } else if ( ! librisId.startsWith(Document.getBASE_URI().toString())) { librisId = Document.getBASE_URI().toString() + librisId; } try(Connection connection = m_whelk.getStorage().getConnection(); PreparedStatement statement = getOnId_ps(connection, librisId); ResultSet resultSet = statement.executeQuery()) { return collectIDs(resultSet); } } private List<String> getDuplicatesOn035a(MarcRecord marcRecord) throws SQLException { List<String> results = new ArrayList<>(); for (Field field : marcRecord.getFields("035")) { String systemNumber = DigId.grep035a( (Datafield) field ); try(Connection connection = m_whelk.getStorage().getConnection(); PreparedStatement statement = getOnSystemNumber_ps(connection, systemNumber); ResultSet resultSet = statement.executeQuery()) { results.addAll( collectIDs(resultSet) ); } } return results; } private List<String> getDuplicatesOnISBN(String isbn) throws SQLException { if (isbn == null) return new ArrayList<>(); String numericIsbn = isbn.replaceAll("-", ""); try(Connection connection = m_whelk.getStorage().getConnection(); PreparedStatement statement = getOnISBN_ps(connection, numericIsbn); ResultSet resultSet = statement.executeQuery()) { return collectIDs(resultSet); } } private List<String> getDuplicatesOnISSN(String issn) throws SQLException { if (issn == null) return new ArrayList<>(); try(Connection connection = m_whelk.getStorage().getConnection(); PreparedStatement statement = getOnISSN_ps(connection, issn); ResultSet resultSet = statement.executeQuery()) { return collectIDs(resultSet); } } private List<String> getDuplicatesOnHeldByHoldingFor(MarcRecord marcRecord, String relatedWithBibResourceId) throws SQLException { if (marcRecord.getFields("852").size() < 1) return new ArrayList<>(); Datafield df = (Datafield) marcRecord.getFields("852").get(0); if (df.getSubfields("b").size() < 1) return new ArrayList<>(); String sigel = df.getSubfields("b").get(0).getData(); String library = LegacyIntegrationTools.legacySigelToUri(sigel); try(Connection connection = m_whelk.getStorage().getConnection(); PreparedStatement statement = getOnHeldByHoldingFor_ps(connection, library, relatedWithBibResourceId); ResultSet resultSet = statement.executeQuery()) { return collectIDs(resultSet); } } private PreparedStatement getOnId_ps(Connection connection, String id) throws SQLException { String query = "SELECT id FROM lddb__identifiers WHERE iri = ?"; PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, id); return statement; } /** * "System number" is our ld equivalent of marc's 035a */ private PreparedStatement getOnSystemNumber_ps(Connection connection, String systemNumber) throws SQLException { String query = "SELECT id FROM lddb WHERE data#>'{@graph,0,identifiedBy}' @> ?"; PreparedStatement statement = connection.prepareStatement(query); statement.setObject(1, "[{\"@type\": \"SystemNumber\", \"value\": \"" + systemNumber + "\"}]", java.sql.Types.OTHER); return statement; } private PreparedStatement getOnISBN_ps(Connection connection, String isbn) throws SQLException { // required to be completely numeric (base 11, 0-9+x). if (!isbn.matches("[\\dxX]+")) isbn = "0"; String query = "SELECT id FROM lddb WHERE data#>'{@graph,1,identifiedBy}' @> ?"; PreparedStatement statement = connection.prepareStatement(query); statement.setObject(1, "[{\"@type\": \"ISBN\", \"value\": \"" + isbn + "\"}]", java.sql.Types.OTHER); return statement; } private PreparedStatement getOnISSN_ps(Connection connection, String issn) throws SQLException { // (base 11, 0-9+x and SINGLE hyphens only). if (!issn.matches("^(-[xX\\d]|[xX\\d])+$")) issn = "0"; String query = "SELECT id FROM lddb WHERE data#>'{@graph,1,identifiedBy}' @> ?"; PreparedStatement statement = connection.prepareStatement(query); statement.setObject(1, "[{\"@type\": \"ISSN\", \"value\": \"" + issn + "\"}]", java.sql.Types.OTHER); return statement; } private PreparedStatement getOnHeldByHoldingFor_ps(Connection connection, String heldBy, String holdingForId) throws SQLException { String libraryUri = LegacyIntegrationTools.legacySigelToUri(heldBy); // Here be dragons. The always-works query is this: /*String query = "SELECT lddb.id from lddb " + "INNER JOIN lddb__identifiers id1 ON lddb.data#>>'{@graph,1,itemOf,@id}' = id1.iri " + "INNER JOIN lddb__identifiers id2 ON id1.id = id2.id " + "WHERE " + "data#>>'{@graph,1,heldBy,@id}' = ? " + "AND " + "id2.iri = ?";*/ // This query REQUIRES that links be on the primary ID only. This works beacuse of link-finding step2, but if // that should ever change this query would break. String query = "SELECT id from lddb WHERE data#>>'{@graph,1,heldBy,@id}' = ? AND data#>>'{@graph,1,itemOf,@id}' = ? AND deleted = false"; PreparedStatement statement = connection.prepareStatement(query); statement.setString(1, libraryUri); statement.setString(2, holdingForId); return statement; } private List<String> collectIDs(ResultSet resultSet) throws SQLException { List<String> ids = new ArrayList<>(); while (resultSet.next()) { ids.add(resultSet.getString("id")); } return ids; } //private class TooHighEncodingLevelException extends RuntimeException {} }
package com.awhittle.rainbowtheremin; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Handler; public class Tone { // Modified further by awhittle3. private final static float duration = 0.05f; // seconds private final static int sampleRate = 8000; private final static int numSamples = (int) (duration * sampleRate); private final static double sample[] = new double[numSamples]; private static double freqOfTone = 440; private final static byte generatedSnd[] = new byte[2 * numSamples]; static Handler handler = new Handler(); protected static void playTone() { // Use a new thread as this can take a while final Thread thread = new Thread(new Runnable() { public void run() { genTone(); handler.post(new Runnable() { public void run() { playSound(); } }); } }); thread.start(); } static void genTone(){ // fill out the array for (int i = 0; i < numSamples; ++i) { sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone)); } // convert to 16 bit pcm sound array // assumes the sample buffer is normalised. int idx = 0; for (final double dVal : sample) { // scale to maximum amplitude final short val = (short) ((dVal * 32767)); // in 16 bit wav PCM, first byte is the low order byte generatedSnd[idx++] = (byte) (val & 0x00ff); generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8); } } static void playSound(){ final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length, AudioTrack.MODE_STATIC); audioTrack.write(generatedSnd, 0, generatedSnd.length); audioTrack.play(); int x = 0; // Montior playback to find when done do { if (audioTrack != null) x = audioTrack.getPlaybackHeadPosition(); else x = numSamples; } while (x<numSamples); // Track play done. Release track. if (audioTrack != null) audioTrack.release(); } public static void getTone(float x){ freqOfTone = (double)(400 + 13000 * x); } }
package org.rakam.ui; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.rakam.plugin.ProjectItem; import org.rakam.server.http.annotations.ApiParam; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class Report implements ProjectItem { public final String project; public final String slug; public final String category; public final String name; public final String query; public final Map<String, Object> options; @JsonCreator public Report(@ApiParam(name = "project", required = true) String project, @ApiParam(name = "slug", value="Short name of the report") String slug, @ApiParam(name = "category", value="Category of the report", required = false) String category, @ApiParam(name = "name", value="The name of the report") String name, @ApiParam(name = "query", value="The sql query that will be executed") @JsonProperty("query") String query, @ApiParam(name = "options", value="Additional information about the materialized view", required = false) Map<String, Object> options) { this.project = checkNotNull(project, "project is required"); this.name = checkNotNull(name, "name is required"); this.slug = checkNotNull(slug, "slug is required"); this.query = checkNotNull(query, "query is required"); this.options = options; this.category = category; checkArgument(this.slug.matches("^[A-Za-z]+[A-Za-z0-9_]*"), "slug must only contain alphanumeric characters and _"); } @Override public String project() { return project; } }
// of patent rights can be found in the PATENTS file in the same directory. package org.rocksdb.test; import org.rocksdb.*; public class StatisticsCollectorTest { static final String db_path = "/tmp/backupablejni_db"; static { RocksDB.loadLibrary(); } public static void main(String[] args) throws InterruptedException, RocksDBException { Options opt = new Options().createStatistics().setCreateIfMissing(true); Statistics stats = opt.statisticsPtr(); RocksDB db = RocksDB.open(db_path); StatsCallbackMock callback = new StatsCallbackMock(); StatisticsCollector statsCollector = new StatisticsCollector(stats, 100, callback); statsCollector.start(); Thread.sleep(1000); assert(callback.tickerCallbackCount > 0); assert(callback.histCallbackCount > 0); statsCollector.shutDown(); db.close(); opt.dispose(); System.out.println("Stats collector test passed.!"); } }
package org.jpos.util; import java.io.*; import java.util.*; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; /** * Rotates logs * @author <a href="mailto:apr@cs.com.uy">Alejandro P. Revilla</a> * @version $Revision$ $Date$ * @see org.jpos.core.Configurable * @since jPOS 1.2 */ public class RotateLogListener extends SimpleLogListener implements Configurable, Destroyable { FileOutputStream f; String logName; int maxCopies; long sleepTime; long maxSize; int msgCount; Rotate rotate; public static final int CHECK_INTERVAL = 100; public static final long DEFAULT_MAXSIZE = 10000000; /** * @param name base log filename * @param sleepTime switch logs every t seconds * @param maxCopies number of old logs * @param maxSize in bytes */ public RotateLogListener (String logName, int sleepTime, int maxCopies, long maxSize) throws IOException { super(); this.logName = logName; this.maxCopies = maxCopies; this.sleepTime = sleepTime * 1000; this.maxSize = maxSize; f = null; openLogFile (); Timer timer = DefaultTimer.getTimer(); if (sleepTime != 0) { timer.schedule (rotate = new Rotate(), sleepTime, sleepTime); } } public RotateLogListener (String logName, int sleepTime, int maxCopies) throws IOException { this (logName, sleepTime, maxCopies, DEFAULT_MAXSIZE); } public RotateLogListener () { super(); } /** * Configure this RotateLogListener<br> * Properties:<br> * <ul> * <li>file base log filename * <li>[window] in seconds (default 0 - never rotate) * <li>[count] number of copies (default 0 == single copy) * <li>[maxsize] max log size in bytes (aprox) * </ul> * @param cfg Configuration * @throws ConfigurationException */ public void setConfiguration (Configuration cfg) throws ConfigurationException { maxCopies = cfg.getInt ("copies"); sleepTime = cfg.getInt ("window") * 1000; logName = cfg.get ("file"); maxSize = cfg.getLong ("maxsize"); maxSize = maxSize <= 0 ? DEFAULT_MAXSIZE : maxSize; try { openLogFile(); } catch (IOException e) { throw new ConfigurationException (e); } Timer timer = DefaultTimer.getTimer(); if (sleepTime != 0) timer.schedule (rotate = new Rotate(), sleepTime, sleepTime); } public synchronized void log (LogEvent ev) { if (msgCount++ > CHECK_INTERVAL) { checkSize(); msgCount = 0; } super.log (ev); } private synchronized void openLogFile() throws IOException { if (f != null) f.close(); f = new FileOutputStream (logName, true); setPrintStream (new PrintStream(f)); } private synchronized void closeLogFile() throws IOException { if (f != null) f.close(); f = null; } public synchronized void logRotate () throws IOException { setPrintStream (null); closeLogFile (); super.close(); for (int i=maxCopies; i>0; ) { File dest = new File (logName + "." + i); File source = new File (logName + ((--i > 0) ? ("." + i) : "")); dest.delete(); source.renameTo(dest); } openLogFile(); } protected void logDebug (String msg) { if (p != null) { p.println ("<log realm=\"rotate-log-listener\" at=\""+new Date().toString() +"\">"); p.println (" "+msg); p.println ("</log-debug>"); } } private void checkSize() { File logFile = new File (logName); if (logFile.length() > maxSize) { try { logDebug ("maxSize ("+maxSize+") threshold reached"); logRotate(); } catch (IOException e) { e.printStackTrace (System.err); } } } public class Rotate extends TimerTask { public void run() { try { logDebug ("time exceeded - log rotated"); logRotate(); } catch (IOException e) { e.printStackTrace (System.err); } } } public void destroy () { if (rotate != null) rotate.cancel (); try { closeLogFile (); } catch (IOException e) { // nothing we can do. } } }
package dr.evomodel.MSSD; import dr.evolution.alignment.PatternList; import dr.evolution.tree.NodeRef; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.Parameter; public class AnyTipObservationProcess extends AbstractObservationProcess { protected double[] u0; protected double[] p; public AnyTipObservationProcess(String modelName, TreeModel treeModel, PatternList patterns, SiteModel siteModel, BranchRateModel branchRateModel, Parameter mu, Parameter lam) { super(modelName, treeModel, patterns, siteModel, branchRateModel, mu, lam); } public double calculateLogTreeWeight() { int L = treeModel.getNodeCount(); if (u0 == null || p == null) { u0 = new double[L]; // probability that the trait at node i survives to no leaf p = new double[L]; // probability of survival on the branch ancestral to i } int i, j, childNumber; NodeRef node; double logWeight = 0.0; for (i = 0; i < L; ++i) { p[i] = 1.0 - getNodeSurvivalProbability(i); } for (i = 0; i < treeModel.getExternalNodeCount(); ++i) { u0[i] = 0.0; logWeight += 1.0 - p[i]; } // TODO There is a bug here; the code below assumes nodes are numbered in post-order for (i = treeModel.getExternalNodeCount(); i < L; ++i) { u0[i] = 1.0; node = treeModel.getNode(i); for (j = 0; j < treeModel.getChildCount(node); ++j) { //childNode = treeModel.getChild(node,j); childNumber = treeModel.getChild(node, j).getNumber(); u0[i] *= 1.0 - p[childNumber] * (1.0 - u0[childNumber]); } logWeight += (1.0 - u0[i]) * (1.0 - p[i]); } return -logWeight * lam.getParameterValue(0) / (getAverageRate() * mu.getParameterValue(0)); } private void setTipNodePatternInclusion() { // These values never change for (int i = 0; i < treeModel.getNodeCount(); i++) { NodeRef node = treeModel.getNode(i); final int nChildren = treeModel.getChildCount(node); if (nChildren == 0) { for (int patternIndex = 0; patternIndex < patternCount; patternIndex++) { extantInTipsBelow[i][patternIndex] = 1; int taxonIndex = patterns.getTaxonIndex(treeModel.getNodeTaxon(node)); int[] states = dataType.getStates(patterns.getPatternState(taxonIndex, patternIndex)); for (int state : states) { if (state == deathState) { extantInTipsBelow[i][patternIndex] = 0; } } extantInTips[patternIndex] += extantInTipsBelow[i][patternIndex]; } } } } void setNodePatternInclusion() { int patternIndex, i, j; if (nodePatternInclusion == null) { nodePatternInclusion = new boolean[nodeCount][patternCount]; } if (this.extantInTips == null) { extantInTips = new int[patternCount]; extantInTipsBelow = new int[nodeCount][patternCount]; setTipNodePatternInclusion(); } for (patternIndex = 0; patternIndex < patternCount; ++patternIndex) { for (i = 0; i < treeModel.getNodeCount(); ++i) { NodeRef node = treeModel.getNode(i); int nChildren = treeModel.getChildCount(node); // TODO There is a bug here; the code below assumes nodes are numbered in post-order if (nChildren > 0) { extantInTipsBelow[i][patternIndex] = 0; for (j = 0; j < nChildren; ++j) { int childIndex = treeModel.getChild(node, j).getNumber(); extantInTipsBelow[i][patternIndex] += extantInTipsBelow[childIndex][patternIndex]; } } } for (i = 0; i < treeModel.getNodeCount(); ++i) { nodePatternInclusion[i][patternIndex] = (extantInTipsBelow[i][patternIndex] >= this.extantInTips[patternIndex]); } } nodePatternInclusionKnown = true; } private int[] extantInTips; private int[][] extantInTipsBelow; }
package dr.inference.operators; import dr.inference.model.Bounds; import dr.inference.model.Parameter; import dr.inferencexml.operators.RandomWalkOperatorParser; import dr.math.MathUtils; import java.util.ArrayList; import java.util.List; /** * A generic random walk operator for use with a multi-dimensional parameters. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: RandomWalkOperator.java,v 1.16 2005/06/14 10:40:34 rambaut Exp $ */ public class RandomWalkOperator extends AbstractCoercableOperator { public enum BoundaryCondition { reflecting, absorbing } public RandomWalkOperator(Parameter parameter, double windowSize, BoundaryCondition bc, double weight, CoercionMode mode) { this(parameter, null, windowSize, bc, weight, mode); } public RandomWalkOperator(Parameter parameter, Parameter updateIndex, double windowSize, BoundaryCondition bc, double weight, CoercionMode mode) { this(parameter, updateIndex, windowSize, bc, weight, mode, null, null); } public RandomWalkOperator(Parameter parameter, Parameter updateIndex, double windowSize, BoundaryCondition bc, double weight, CoercionMode mode, Double lowerOperatorBound, Double upperOperatorBound) { super(mode); this.parameter = parameter; this.windowSize = windowSize; this.condition = bc; setWeight(weight); if (updateIndex != null) { updateMap = new ArrayList<Integer>(); for (int i = 0; i < updateIndex.getDimension(); i++) { if (updateIndex.getParameterValue(i) == 1.0) updateMap.add(i); } } this.lowerOperatorBound = lowerOperatorBound; this.upperOperatorBound = upperOperatorBound; } /** * @return the parameter this operator acts on. */ public Parameter getParameter() { return parameter; } public final double getWindowSize() { return windowSize; } /** * change the parameter and return the hastings ratio. */ public final double doOperation() throws OperatorFailedException { // a random dimension to perturb int index; if (updateMap == null) { index = MathUtils.nextInt(parameter.getDimension()); } else { index = updateMap.get(MathUtils.nextInt(updateMap.size())); } // a random point around old value within windowSize * 2 double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize; double newValue = parameter.getParameterValue(index) + draw; final Bounds<Double> bounds = parameter.getBounds(); final double lower = (lowerOperatorBound == null ? bounds.getLowerLimit(index) : Math.max(bounds.getLowerLimit(index), lowerOperatorBound)); final double upper = (upperOperatorBound == null ? bounds.getUpperLimit(index) : Math.min(bounds.getUpperLimit(index), upperOperatorBound)); if (condition == BoundaryCondition.reflecting) { newValue = reflectValue(newValue, lower, upper); } else if (newValue < lower || newValue > upper) { throw new OperatorFailedException("proposed value outside boundaries"); } parameter.setParameterValue(index, newValue); return 0.0; } public double reflectValue(double value, double lower, double upper) { double newValue = value; if (value < lower) { if (Double.isInfinite(upper)) { // we are only going to reflect once as the upper bound is at infinity... newValue = lower + (lower - value); } else { double remainder = lower - value; double widths = Math.floor(remainder / (upper - lower)); remainder -= (upper - lower) * widths; // even reflections if (widths % 2 == 0) { newValue = lower + remainder; // odd reflections } else { newValue = upper - remainder; } } } else if (value > upper) { if (Double.isInfinite(lower)) { // we are only going to reflect once as the lower bound is at -infinity... newValue = upper - (newValue - upper); } else { double remainder = value - upper; double widths = Math.floor(remainder / (upper - lower)); remainder -= (upper - lower) * widths; // even reflections if (widths % 2 == 0) { newValue = upper - remainder; // odd reflections } else { newValue = lower + remainder; } } } return newValue; } public double reflectValueLoop(double value, double lower, double upper) { double newValue = value; while (newValue < lower || newValue > upper) { if (newValue < lower) { newValue = lower + (lower - newValue); } if (newValue > upper) { newValue = upper - (newValue - upper); } } return newValue; } //MCMCOperator INTERFACE public final String getOperatorName() { return parameter.getParameterName(); } public double getCoercableParameter() { return Math.log(windowSize); } public void setCoercableParameter(double value) { windowSize = Math.exp(value); } public double getRawParameter() { return windowSize; } public double getTargetAcceptanceProbability() { return 0.234; } public double getMinimumAcceptanceLevel() { return 0.1; } public double getMaximumAcceptanceLevel() { return 0.4; } public double getMinimumGoodAcceptanceLevel() { return 0.20; } public double getMaximumGoodAcceptanceLevel() { return 0.30; } public final String getPerformanceSuggestion() { double prob = MCMCOperator.Utils.getAcceptanceProbability(this); double targetProb = getTargetAcceptanceProbability(); double ws = OperatorUtils.optimizeWindowSize(windowSize, parameter.getParameterValue(0) * 2.0, prob, targetProb); if (prob < getMinimumGoodAcceptanceLevel()) { return "Try decreasing windowSize to about " + ws; } else if (prob > getMaximumGoodAcceptanceLevel()) { return "Try increasing windowSize to about " + ws; } else return ""; } public String toString() { return RandomWalkOperatorParser.RANDOM_WALK_OPERATOR + "(" + parameter.getParameterName() + ", " + windowSize + ", " + getWeight() + ")"; } //PRIVATE STUFF private Parameter parameter = null; private double windowSize = 0.01; private List<Integer> updateMap = null; private final BoundaryCondition condition; private final Double lowerOperatorBound; private final Double upperOperatorBound; }
package edu.afs.subsystems.autoranger; import java.util.Timer; import java.util.TimerTask; /** * Class to drive indicator lights on bot to aid drivers when setting up for * a shot on the 10-point goal. * * @author RAmato */ public class RangeBeacon { // Set up three analog outputs to drive red, yellow, and green lights // mounted on the bot. // Red - auto-ranging is disabled. // Yellow - auto-ranging is in progress. Bot moving to shooting range. // Green - bot at shooting range. The green indicator is latched by a timer // to keep it lit for five seconds after public static long GREEN_INDICATOR_TIMEOUT = 5000; //Time in milliseconds. private Timer m_greenTimer; // Implement Singleton design pattern. There // can be only one instance of this class. private static RangeBeacon instance = null; public static RangeBeacon getInstance () { if (instance == null) { instance = new RangeBeacon(); } return instance; } // Constructor is private to enforce Singelton. private RangeBeacon(){ //TODO: Initialize the outputs - RED ON, YELLOW, GREEN - OFF Timer m_greenTimer = new Timer(); } class GreenTimerTask extends TimerTask { public void run() { //TODO: GREEN-OFF. m_greenTimer.cancel(); //Terminate the timer thread } } public void SetAtShotRangeIndicator(boolean atShotRange){ if(atShotRange== true){ //TODO: GREEN-ON } else { //TODO: GREEN-OFF } } public void setRangeBeaconState (RangeBeaconState state){ if(state.equals(RangeBeaconState.AUTO_RANGE_DISABLED)){ //TODO: Set outputs: //RED - ON //YELLOW - OFF } else if (state.equals(RangeBeaconState.AUTO_RANGE_ENABLED)){ //TODO: Set outputs: //RED - OFF //YELLOW - ON //GREEN - OFF } else { // state.equals(RangeBeaconState.AUTO_RANGE_COMPLETE) //TODO: Set outputs: //GREEN - ON for five seconds. m_greenTimer.schedule(new GreenTimerTask(), GREEN_INDICATOR_TIMEOUT); } } }
package edu.wpi.first.wpilibj.technobots; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { //Jugars public static final int lowerRight = 1, lowerLeft = 2, upperRight = 3, upperLeft = 4; //Victors public static final int shooterRight = 5, shooterLeft = 6, sweeper = 7, elbow = 8; //Sensors public static final int pot = 1, rangeFinder = 2; //Solenoid public static final int ballStopper = 1; }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Talon; /** * * @author Steven */ public class Constants { // PWMs public static final int PWM_DRIVE_FRONT_LEFT = 1; public static final int PWM_DRIVE_REAR_LEFT = 2; public static final int PWM_DRIVE_FRONT_RIGHT = 3; public static final int PWM_DRIVE_REAR_RIGHT = 4; public static final int PWM_THROWER_RIGHT = 5; public static final int PWM_THROWER_LEFT = 6; public static final int PWM_TAIL_BASE = 7; public static final int PWM_TAIL_STINGER = 8; // DIOs public static final int DIO_THROWER_ENCODER_A = 1; public static final int DIO_THROWER_ENCODER_B = 2; public static final int DIO_SONIC_LEFT_ENABLE = 3; public static final int DIO_SONIC_RIGHT_ENABLE = 4; // Analog Inputs public static final int ANA_SONIC_RIGHT = 1; public static final int ANA_SONIC_LEFT = 2; public static final int ANA_TAIL_POT = 3; // Relays // Drive Motors static Talon frontLeft = new Talon(PWM_DRIVE_FRONT_LEFT); static Talon rearLeft = new Talon(PWM_DRIVE_REAR_LEFT); static Talon frontRight = new Talon(PWM_DRIVE_FRONT_RIGHT); static Talon rearRight = new Talon(PWM_DRIVE_REAR_RIGHT); // Joysticks // rightstick public static final int JB_THROW_SAFETY = 1; //Throw enable public static final int JB_THROW_AUTO_DIST = 2; //Throw based on sonar public static final int JB_THROW_TRUSS_TOSS = 3; //Throw a truss toss public static final int JB_THROW_ROBOT_PASS = 4; //Lob to another robot public static final int JB_THROW_MANUAL = 5 //Throw static params, no sonar public static final int JB_THROW_ANALOG = 7 //Throw using analog inputs // leftstick public static final int JB_TAIL_EXTEND = 1; //Extend tail-eject ball public static final int JB_TAIL_RETRACT = 2; //Retract tail-pickup ball //public static final int JB_TAIL_EJECT = 1; // Miscellaneous public static final double TELEOP_LOOP_DELAY_SECS = .05; //Main loop speed (.05 = 20hz) // Thrower parameters static double[] throwerSpeedVals = new double[10]; static int[] throwerArcVals = new int[10]; int[] throwerDistanceVals = new int[10]; public static final int THROWER_STATUS_HOME = 0; public static final int THROWER_STATUS_THROW = 1; public static final int THROWER_STATUS_STOW = 2; public static final int THROWER_STATUS_INIT = 3; public static final int THROWER_STATUS_BRAKE = 4; public static final double THROWER_BRAKE_TIME = 5; //Sonic constants public static final int SONIC_BALANCE_EQUAL = 0; public static final int SONIC_BALANCE_RIGHT = 1; public static final int SONIC_BALANCE_LEFT = 2; public static final double SONIC_ALT_LOOP_DELAY = .2; //delay time between sonar pings //Scorpion Tail public static final int TAIL_STATUS_INIT = 0; public static final int TAIL_STATUS_EXTENDED = 1; public static final int TAIL_STATUS_RETRACTED = 2; public static final int TAIL_STATUS_EXTENDING = 3; public static final int TAIL_STATUS_RETRACTING = 4; public static final int TAIL_STATUS_EJECTING = 5; //Autonomous public static final int AUTO_STATUS_INIT = 0; public static final int AUTO_STATUS_MOVING = 1; public static final int AUTO_STATUS_LOOKING = 2; public static final int AUTO_STATUS_THROWCHECK = 3; public static final int AUTO_STATUS_THROW = 4; public static final int AUTO_STATUS_THROWING = 5; public static final int AUTO_STATUS_DONE = 6; }
package com.kylantraynor.civilizations; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.World; import org.bukkit.advancement.Advancement; import org.bukkit.block.Block; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import org.eclipse.jetty.server.Server; import com.kylantraynor.civilizations.commands.CommandAnswer; import com.kylantraynor.civilizations.commands.CommandBlueprint; import com.kylantraynor.civilizations.commands.CommandCamp; import com.kylantraynor.civilizations.commands.CommandCivilizations; import com.kylantraynor.civilizations.commands.CommandGroup; import com.kylantraynor.civilizations.commands.CommandHouse; import com.kylantraynor.civilizations.commands.CommandPlot; import com.kylantraynor.civilizations.commands.CommandRegion; import com.kylantraynor.civilizations.commands.CommandSelection; import com.kylantraynor.civilizations.commands.CommandStall; import com.kylantraynor.civilizations.database.Database; import com.kylantraynor.civilizations.database.SQLite; import com.kylantraynor.civilizations.groups.settlements.Camp; import com.kylantraynor.civilizations.groups.settlements.Settlement; import com.kylantraynor.civilizations.groups.settlements.forts.SmallOutpost; import com.kylantraynor.civilizations.groups.settlements.plots.Plot; import com.kylantraynor.civilizations.hook.HookManager; import com.kylantraynor.civilizations.hook.draggyrpg.DraggyRPGHook; import com.kylantraynor.civilizations.hook.dynmap.DynmapHook; import com.kylantraynor.civilizations.hook.lwc.LWCHook; import com.kylantraynor.civilizations.hook.titlemanager.TitleManagerHook; import com.kylantraynor.civilizations.hook.towny.CommandTownyTown; import com.kylantraynor.civilizations.hook.towny.TownyHook; import com.kylantraynor.civilizations.hook.towny.TownyListener; import com.kylantraynor.civilizations.hook.towny.TownyTown; import com.kylantraynor.civilizations.listeners.ChatListener; import com.kylantraynor.civilizations.listeners.CivilizationsListener; import com.kylantraynor.civilizations.listeners.MenuListener; import com.kylantraynor.civilizations.listeners.ProtectionListener; import com.kylantraynor.civilizations.listeners.TerritoryListener; import com.kylantraynor.civilizations.listeners.VehiclesListener; import com.kylantraynor.civilizations.listeners.WebListener; import com.kylantraynor.civilizations.managers.CacheManager; import com.kylantraynor.civilizations.managers.GroupManager; import com.kylantraynor.civilizations.managers.LockManager; import com.kylantraynor.civilizations.managers.SelectionManager; import com.kylantraynor.civilizations.protection.Protection; import com.kylantraynor.civilizations.settings.CivilizationsSettings; import com.kylantraynor.civilizations.territories.InfluenceMap; import com.kylantraynor.civilizations.util.MaterialAndData; import com.kylantraynor.civilizations.util.Util; import com.kylantraynor.draggydata.AdvancementAPI; import com.kylantraynor.draggydata.AdvancementAPI.FrameType; import com.kylantraynor.draggydata.AdvancementAPI.TriggerType; import fr.rhaz.webservers.WebServers.API; public class Civilizations extends JavaPlugin{ /** * Plugin Constants */ public static final String MC_SERVER_VERSION = org.bukkit.Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; public static final String PLUGIN_NAME = "Civilizations"; /** * Currently running instance of Civilizations */ public static Civilizations currentInstance; /** * Header displayed in chat */ public static String messageHeader = ChatColor.GOLD + "[" + ChatColor.GOLD + ChatColor.BOLD + "Civilizations" + ChatColor.GOLD + "] "; private boolean clearBuildProjectsOnRestart = true; private boolean clearing = false; private boolean DEBUG = false; private ArrayList<Player> playersInProtectionMode = new ArrayList<Player>(); private Database database; static private HashMap<Player, Protection> selectedProtections = new HashMap<Player, Protection>(); static private CivilizationsSettings settings; public static HashMap<Player, Protection> getSelectedProtections(){ return selectedProtections; } private static List<BukkitRunnable> processes = new ArrayList<BukkitRunnable>(); /* * Listeners */ private static CivilizationsListener mainListener = new CivilizationsListener(); private static MenuListener menuListener = new MenuListener(); private static TerritoryListener territoryListener = new TerritoryListener(); private static ProtectionListener protectionListener = new ProtectionListener(); private static WebListener webListener = new WebListener(); private static ChatListener chatListener = new ChatListener(); private static VehiclesListener vehiclesListener = new VehiclesListener(); /* * InfluenceMaps */ private static Map<World, InfluenceMap> influenceMaps = new HashMap<World, InfluenceMap>(); /** * Returns the main listener of Civilizations. * @return CivilizationsListener */ public static CivilizationsListener getMainListener(){ return mainListener; } /** * Returns the FileConfiguration of the current running instance. * @return FileConfiguration */ public static FileConfiguration getInstanceConfig(){ return currentInstance.getConfig(); } private static Server webServer; public static boolean useChat = false; public static boolean useDatabase = false; public static Server getWebServer(){ return webServer; } /** * Sends a message to the console with the specified level. * @param level of the message. * @param message to send. * @see Level */ public static void log(String level, String message){ if(level != null){ Level lvl = Level.parse(level); Bukkit.getServer().getLogger().log(lvl, message); } else { Bukkit.getServer().getLogger().log(Level.ALL, "["+level+"] " + message); } } public static CivilizationsSettings getSettings(){ return settings; } /** * Function called when the plugin is enabled. */ @Override public void onEnable(){ currentInstance = this; saveDefaultConfig(); File f = new File(this.getDataFolder(), "config.yml"); settings = new CivilizationsSettings(); try { settings.load(f); } catch (Exception e){ e.printStackTrace(); } MaterialAndData.reloadFromConfig(settings); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(getMainListener(), this); pm.registerEvents(getMenuListener(), this); pm.registerEvents(getTerritoryListener(), this); pm.registerEvents(getProtectionListener(), this); pm.registerEvents(getChatListener(), this); pm.registerEvents(getVehiclesListener(), this); registerAdvancements(); GroupManager.loadAll(); HookManager.loadHooks(); GroupManager.ensurePlotsAreLinked(); loadInfluenceMaps(); startGroupUpdater(20L * 60 * 5); startProtectionUpdater(40L); startEconomyUpdater(20L * 60); startBuilderUpdater(20L * 2); initManagers(); registerRecipes(); if(useDatabase) initDatabase(); setupCommands(); /*int port = 8120; try { startWebServer(port); log("INFO", "Successfully started webserver on port " + port); } catch (Exception e) { log("WARNING", "Could not start webserver on port " + port + ". This port is probably already in use."); e.printStackTrace(); }*/ } private void registerRecipes(){ ItemStack is = new ItemStack(getSelectionToolMaterial()); ItemMeta im = is.getItemMeta(); im.setDisplayName(getSelectionToolName()); im.setLore(getSelectionToolLore()); is.setItemMeta(im); ShapelessRecipe r = new ShapelessRecipe(new NamespacedKey(this, "urbanist_tool"), is); r.addIngredient(getSelectionToolMaterial()); Bukkit.addRecipe(r); } private void initDatabase() { this.database = new SQLite(this); this.database.load(); } private void loadInfluenceMaps() { List<String> enabledWorlds = getConfig().getStringList("EnabledWorlds"); for(World w : Bukkit.getServer().getWorlds()){ if(enabledWorlds.contains(w.getName())) influenceMaps.put(w, new InfluenceMap(w)); } for(InfluenceMap map : influenceMaps.values()){ log("INFO", "Generating influence map for " + map.getWorld().getName() + "."); map.generateFull(); log("INFO", "Map was generated with " + map.getCells().length + " cells."); } } private void initManagers() { LockManager.init(); SelectionManager.init(); CacheManager.init(); } private void freesManagers(){ SelectionManager.free(); } public List<World> getColonizableWorlds(){ List<World> worlds = new ArrayList<World>(); for(String s : getSettings().getColonizableWorlds()){ worlds.add(Bukkit.getWorld(s)); } return worlds; } private void registerAdvancements() { Map<String, TriggerType> crit = new HashMap<String, TriggerType>(); crit.put("trigger1", TriggerType.IMPOSSIBLE); AdvancementAPI civs = new AdvancementAPI(new NamespacedKey(this, "root")) .withTitle("Civilizations") .withDescription("Establish your own civilization!") .withIcon(new ItemStack(Material.BANNER)) .withBackground("minecraft:textures/blocks/stone.png") .withCriterias(crit) .withAnnouncement(true) .withToast(true) .withFrame(FrameType.GOAL); Advancement civsAdv = civs.load(); /*for(World w : getColonizableWorlds()){ civs.save(w); }*/ crit.clear(); crit.put("trigger1", TriggerType.IMPOSSIBLE); AdvancementAPI camp = new AdvancementAPI(new NamespacedKey(this, "setup_camp")) .withTitle("Setup Camp!") .withDescription("Create a temporary camp to protect an area.") .withIcon(new ItemStack(Material.BED)) .withCriterias(crit) .withAnnouncement(true) .withToast(true) .withFrame(FrameType.TASK) .withParent(civs.getID()); Advancement campAdv = camp.load(); /*for(World w : getColonizableWorlds()){ camp.save(w); }*/ /*Achievement createCamp = new Achievement("create_camp", "Setting up Camp", null, new ArrayList<String>()); createCamp.getDescription().add("Create a camp."); AchievementManager.registerAchievement(createCamp);*/ } private void startWebServer(int port) throws Exception { createServerViews(); webServer = API.createServer(port, "Civilizations", ""); webServer.start(); getServer().getPluginManager().registerEvents(getWebListener(), this); } private void createServerViews() { } private Listener getMenuListener() { return Civilizations.menuListener; } /** * Loads all the hooks allowing the interaction with other plugins. * @param pm PluginManager */ /* private void loadHooks(PluginManager pm) { if(DynmapHook.load(pm)){ log("INFO", "Hook to Dynmap: OK"); } else { log("WARNING", "Hook to Dynmap: NO, " + PLUGIN_NAME + " will not be displayed."); } if(TitleManagerHook.load(pm)){ log("INFO", "Hook to TitleManager: OK"); } else { log("WARNING", "Hook to Titlemanager: NO"); } if(TownyHook.isActive()){ log("INFO", "Side by side with Towny: OK"); } else { log("INFO", "Side by side with Towny: NO"); } if(Economy.load(pm)){ log("INFO", "Economy: OK"); } else { log("WARNING", "Economy: NO, " + PLUGIN_NAME + " will not be working properly."); } if(LWCHook.isActive()) {log("INFO", "LWC: OK"); } else {log("INFO", "LWC: NO"); } if(DynmapHook.isEnabled()) DynmapHook.activateDynmap(); if(TownyHook.isActive()){ TownyHook.loadTownyTowns(); pm.registerEvents(getTownyListener(), this); } if(DraggyRPGHook.isActive()) { log("INFO", "DraggyRPG: OK"); DraggyRPGHook.loadLevelCenters(); } else {log("INFO", "DraggyRPG: NO");} } */ /** * Setups all the commands for Civilizations. */ private void setupCommands() { this.getCommand("Civilizations").setExecutor(new CommandCivilizations()); this.getCommand("CivilizationsAnswer").setExecutor(new CommandAnswer()); this.getCommand("Blueprint").setExecutor(new CommandBlueprint()); this.getCommand("Group").setExecutor(new CommandGroup()); this.getCommand("House").setExecutor(new CommandHouse()); this.getCommand("Camp").setExecutor(new CommandCamp()); this.getCommand("Region").setExecutor(new CommandRegion()); this.getCommand("Selection").setExecutor(new CommandSelection()); this.getCommand("Plot").setExecutor(new CommandPlot()); this.getCommand("Stall").setExecutor(new CommandStall()); if(TownyHook.isActive()){ this.getCommand("TownyTown").setExecutor(new CommandTownyTown()); } } /** * Starts the process updating the group. * @param interval in ticks between updates. */ private void startGroupUpdater(long interval) { BukkitRunnable br = new BukkitRunnable(){ @Override public void run() { GroupManager.updateAllGroups(); } }; br.runTaskTimer(this, (long) (Math.random() * 20), interval); } /** * Starts the process of updating the economy. * @param interval in ticks between updates. */ private void startEconomyUpdater(long interval) { BukkitRunnable br = new BukkitRunnable(){ @Override public void run() { if(settings.hasChanged()){ try { settings.save(new File(Civilizations.currentInstance.getDataFolder(), "config.yml")); } catch (IOException e) { e.printStackTrace(); } } if(Instant.now().isAfter(settings.getTaxationDate())){ settings.setTaxationDate(Instant.now().plus(1, ChronoUnit.DAYS)); GroupManager.updateForEconomy(); } } }; br.runTaskTimer(this, (long) (Math.random() * 20), interval); } /** * Starts process updating protection visibility in an asynchronous thread. * @param interval in ticks between updates. */ private void startProtectionUpdater(long interval) { BukkitRunnable pr = new BukkitRunnable(){ @Override public void run() { BukkitRunnable[] prcs = Civilizations.getProcesses().toArray(new BukkitRunnable[Civilizations.getProcesses().size()]); for(BukkitRunnable r : prcs){ if(Civilizations.getProcesses().contains(r)){ Civilizations.getProcesses().remove(r); } r.runTask(Civilizations.currentInstance); } } }; pr.runTaskTimerAsynchronously(this, (long) (Math.random() * interval), interval); } /** * Starts process updating the builders. * @param interval in ticks between updates. */ private void startBuilderUpdater(long interval) { BukkitRunnable br = new BukkitRunnable(){ @Override public void run() { GroupManager.updateAllBuilders(); } }; br.runTaskTimer(this, (long) (Math.random() * 20), interval); } /** * Updates the given protection's visibility for the given player. * @param player to display the change to. * @param protection to update. */ protected static void updateProtectionVisibility(Player player, Protection protection) { if(getPlayersInProtectionMode().contains(player)){ if(Civilizations.getSelectedProtections().get(player).equals(protection)){ protection.highlight(player); } else { protection.hide(player); } } else { protection.hide(player); } } @Override public void onDisable(){ if(clearBuildProjectsOnRestart) GroupManager.cancelAllBuilds(); GroupManager.updateAllGroups(); if(DynmapHook.isEnabled()){ DynmapHook.disable(); } freesManagers(); MaterialAndData.saveToConfig(getConfig()); saveConfig(); try { settings.save(new File(Civilizations.currentInstance.getDataFolder(), "config.yml")); } catch (IOException e) { e.printStackTrace(); } } /** * Select the protection the given player is targeting. * @param player */ public static void selectTargetProtection(Player player) { Location l = null; for(Block b : player.getLineOfSight((Set<Material>) null, 100)){ if(b.getType() != Material.AIR){ if(Settlement.isProtected(b.getLocation())){ l = b.getLocation(); } break; } } if(l != null){ //Try getting a plot Plot plot = null; Protection newProt = null; for(Plot p : CacheManager.getPlotList()){ if(p.protects(l)){ plot = p; newProt = p.getProtection(); } } Settlement s = null; if(newProt == null){ s = Settlement.getAt(l); if(s != null){ newProt = s.getProtection(); } } else { s = plot.getSettlement(); } Protection old = Civilizations.getSelectedProtections().get(player); if(newProt.equals(old)){ player.sendMessage(messageHeader + ChatColor.RED + "Protection already selected."); return; } Civilizations.getSelectedProtections().put(player, newProt); String plotName = " Settlement"; if(plot != null) plotName = " " + plot.getName(); player.sendMessage(messageHeader + ChatColor.GREEN + "Protection selected: " + (s != null ? s.getName() : "") + plotName + "."); if(old != null) updateProtectionVisibility(player, old); updateProtectionVisibility(player, newProt); } else { if(Civilizations.getSelectedProtections().containsKey(player)){ Protection old = Civilizations.getSelectedProtections().get(player); Civilizations.getSelectedProtections().remove(player); updateProtectionVisibility(player, old); } player.sendMessage(messageHeader + ChatColor.RED + "No protection selected."); } } /** * Displays a message to a player when they move from one area to another. * @param fromL * @param toL * @param player */ public static void displayProtectionStatus(Location fromL, Location toL, Player player) { if(fromL.getBlock().equals(toL.getBlock())) return; Settlement from = Settlement.getAt(fromL.getBlock().getLocation()); Settlement to = Settlement.getAt(toL.getBlock().getLocation()); if((from != null && to != null) || (from == null && to != null)){ if(!to.equals(from)){ if(to instanceof Camp){ TitleManagerHook.sendTitle("", ChatColor.GRAY + to.getName(), 10, 40, 10, player); if(!to.isMember(player)){ if(to.getMembers().size() > 0){ TitleManagerHook.sendActionBar("Protected Area", player, false); } else { TitleManagerHook.sendActionBar("Abandonned Camp, do " + ChatColor.GOLD + "/camp claim" + ChatColor.RESET + " to claim it for yourself!", player, false); } } } else if(to instanceof SmallOutpost){ TitleManagerHook.sendTitle("", ChatColor.GRAY + to.getName(), 10, 40, 10, player); if(!to.isMember(player)){ TitleManagerHook.sendActionBar("Protected Area", player, false); } } else if(to instanceof Settlement){ TitleManagerHook.sendTitle("", ChatColor.GRAY + to.getName(), 10, 40, 10, player); if(!to.isMember(player)){ TitleManagerHook.sendActionBar("Protected Area", player, false); } } else if(to instanceof TownyTown){ TitleManagerHook.sendTitle("", ChatColor.GRAY + Util.prettifyText(to.getName()), 10, 40, 10, player); if(!to.isMember(player)){ TitleManagerHook.sendActionBar("Protected Area", player, false); } } } else { Plot p = null; for(Plot plot : to.getPlots()){ if(plot.protects(toL.getBlock().getLocation())) p = plot; } if(p == null) return; if(!p.protects(fromL.getBlock().getLocation())){ TitleManagerHook.sendActionBar(p.getName(), player, false); } } } else if(from != null && to == null){ if(from != null){ if(from instanceof Camp){ if(from.isMember(player)){ TitleManagerHook.sendActionBar("Leaving Camp", player, false); } } else if(from instanceof SmallOutpost){ if(from.isMember(player)){ TitleManagerHook.sendActionBar("Leaving Outpost", player, false); } } else if(from instanceof TownyTown){ TitleManagerHook.sendActionBar("Leaving " + from.getName(), player, false); } } } else { } } /** * Get the directory the group files are stored in. * @return File */ public static File getGroupDirectory(){ File f = new File(currentInstance.getDataFolder(), "Groups"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the settlement files are stored in. * @return File */ public static File getSettlementDirectory(){ File f = new File(currentInstance.getDataFolder(), "Settlements"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the camp files are stored in. * @return File */ public static File getCampDirectory(){ File f = new File(currentInstance.getDataFolder(), "Camps"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the house files are stored in. * @return File */ public static File getHouseDirectory() { File f = new File(currentInstance.getDataFolder(), "Houses"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the fort files are stored in. * @return File */ public static File getFortDirectory() { File f = new File(currentInstance.getDataFolder(), "Forts"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the Small Outpost files are stored in. * @return File */ public static File getSmallOutpostDirectory() { File f = new File(getFortDirectory(), "Small Outposts"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the plot files are stored in. * @return File */ public static File getPlotDirectory() { File f = new File(currentInstance.getDataFolder(), "Plots"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the keep files are stored in. * @return File */ public static File getKeepDirectory() { File f = new File(getPlotDirectory(), "Keeps"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the keep files are stored in. * @return File */ public static File getHousePlotDirectory() { File f = new File(getPlotDirectory(), "Houses"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the stall files are stored in. * @return File */ public static File getMarketStallDirectory() { File f = new File(getPlotDirectory(), "Stalls"); if(!f.exists()) f.mkdir(); return f; } /** * Get the directory in which the nation files are stored. * @return File */ public static File getNationDirectory(){ File f = new File(currentInstance.getDataFolder(), "Nations"); if(!f.exists()) f.mkdir(); return f; } public static File getPlayerDataDirectory() { File f = new File(currentInstance.getDataFolder(), "PlayerData"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } public static File getBlueprintDirectory(){ File f = new File(currentInstance.getDataFolder(), "Blueprints"); if(!f.exists()) f.mkdir(); return f; } public static File getWarehousesDirectory() { File f = new File(getPlotDirectory(), "Warehouses"); if(!f.exists()) f.mkdir(); return f; } public static File getWebDirectory() { File f = new File(currentInstance.getDataFolder(), "Web"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } public static File getPrivateWebDirectory(){ File f = new File(getWebDirectory(), "WEB-INF"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Gets the list of processes. * @return List<BukkitRunnable> */ public static List<BukkitRunnable> getProcesses() { return processes; } /** * Sets the list of processes. * @param processes to set. */ public static void setProcesses(List<BukkitRunnable> processes) { Civilizations.processes = processes; } /** * Gets a list of all the players currently in Protection Mode. * @return List<Player> */ public static List<Player> getPlayersInProtectionMode() { return currentInstance.playersInProtectionMode; } /** * Sets the list of the players currently in Protection Mode. * @param playersInProtectionMode */ public static void setPlayersInProtectionMode(ArrayList<Player> playersInProtectionMode) { currentInstance.playersInProtectionMode = playersInProtectionMode; } /** * No description * @return */ public static boolean isClearing() { return currentInstance.clearing; } /** * No description * @param clearing */ public static void setClearing(boolean clearing) { currentInstance.clearing = clearing; } public static TerritoryListener getTerritoryListener() { return territoryListener; } public static ProtectionListener getProtectionListener() { return protectionListener; } public boolean isDEBUG() { return DEBUG; } public void setDEBUG(boolean dEBUG) { DEBUG = dEBUG; } public static void DEBUG(String message){ if(!currentInstance.DEBUG) return; log("INFO", message); } public static WebListener getWebListener() { return webListener; } public static void setWebListener(WebListener webListener) { Civilizations.webListener = webListener; } public static ChatListener getChatListener() { return chatListener; } public static Listener getVehiclesListener() { return vehiclesListener; } public static void callEvent(Event event) { currentInstance.getServer().getPluginManager().callEvent(event); } public static InfluenceMap getInfluenceMap(World w){ return influenceMaps.get(w); } public static File getBuilderDirectory() { File f = new File(currentInstance.getDataFolder(), "Builders"); if(!f.exists()) f.mkdir(); return f; } public static File getTownyTownsDirectory() { File f = new File(currentInstance.getDataFolder(), "Towny"); if(!f.exists()) f.mkdir(); return f; } public static boolean isSelectionTool(ItemStack is){ if(is.getType() != getSelectionToolMaterial()) return false; ItemMeta im = is.getItemMeta(); if(im == null) return false; if(!im.getDisplayName().equals(getSelectionToolName())) return false; return true; } public static Material getSelectionToolMaterial(){ return Material.STICK; } public static String getSelectionToolName(){ return ChatColor.WHITE + "Urban Planner Tool"; } public static List<String> getSelectionToolLore(){ String[] s = new String[]{"Use this tool to select an area.", "Left Click to set the first corner.", "Right Click to set the second cornder.", "", "Use /Selection Start Hull to begin a polygonal", "selection, then Left Click to add a block to the", "point cloud. A Hull will be calculated to fit.", "them all in."}; List<String> result = new ArrayList<String>(); for(String line : s){ result.add(line); } return result; } public Database getDatabase() { return this.database; } }
package com.jtransc; import com.jtransc.annotation.haxe.HaxeMethodBody; import java.util.Arrays; public class JTranscArrays { @HaxeMethodBody("return HaxeArrayByte.fromBytes(p0.getBytes());") static public byte[] copyReinterpret(int[] data) { byte[] out = new byte[data.length * 4]; int m = 0; for (int value : data) { out[m++] = JTranscBits.int0(value); out[m++] = JTranscBits.int1(value); out[m++] = JTranscBits.int2(value); out[m++] = JTranscBits.int3(value); } return out; } static public byte[] copyReinterpretReversed(int[] data) { int[] temp = Arrays.copyOf(data, data.length); swizzle_inplace_reverse(temp); return copyReinterpret(temp); } //@JTranscInline static final public void swizzle_inplace(int[] data, int v3, int v2, int v1, int v0) { int size = data.length; for (int n = 0; n < size; n++) { int v = data[n]; data[n] = JTranscBits.makeInt((v >>> v3), (v >>> v2), (v >>> v1), (v >>> v0)); } } static final public void swizzle_inplace_reverse(int[] data) { //swizzle_inplace(data, 0, 8, 16, 24); int size = data.length; for (int n = 0; n < size; n++) { int v = data[n]; data[n] = Integer.reverseBytes(v); } } @HaxeMethodBody("for (n in 0 ... p0) p1.data[p2 + n] = p3.data[p4 + n] + p5.data[p6 + n];") static public void add(int count, byte[] target, int targetpos, byte[] a, int apos, byte[] b, int bpos) { for (int n = 0; n < count; n++) target[targetpos + n] = (byte) (a[apos + n] + b[bpos + n]); } @HaxeMethodBody("for (n in 0 ... p0) p1.data[p2 + n] = p3.data[p4 + n] - p5.data[p6 + n];") static public void sub(int count, byte[] target, int targetpos, byte[] a, int apos, byte[] b, int bpos) { for (int n = 0; n < count; n++) target[targetpos + n] = (byte) (a[apos + n] - b[bpos + n]); } @HaxeMethodBody("var p8 = 1 - p7; for (n in 0 ... p0) p1.data[p2 + n] = Std.int(p3.data[p4 + n] * p7 + p5.data[p6 + n] * p8);") static public void mixUnsigned(int count, byte[] target, int targetpos, byte[] a, int apos, byte[] b, int bpos, double ratio) { double ratiob = 1.0 - ratio; for (int n = 0; n < count; n++) target[targetpos + n] = (byte) ((a[apos + n] & 0xFF) * ratio + (b[bpos + n] & 0xFF) * ratiob); } // Use clamped array? static public void addUnsignedClamped(int count, byte[] target, int targetpos, byte[] a, int apos, byte[] b, int bpos) { for (int n = 0; n < count; n++) target[targetpos + n] = (byte) clamp255((a[apos + n] & 0xFF) + (b[bpos + n] & 0xFF)); } static private int clamp255(int v) { return Math.min(Math.max(v, 0), 255); } /* static public void swizzle_inplace_abcd_dbca(int[] data) { int size = data.length; for (int n = 0; n < size; n++) { int v = data[n]; data[n] = (v << 24) | (v >>> 24) | (v & 0x00FFFF00); } } static public void swizzle_inplace_abcd_abdc(int[] data) { int size = data.length; for (int n = 0; n < size; n++) { int v = data[n]; data[n] = (v & 0xFFFF0000) | ((v << 8) & 0xFF00) | ((v >> 8) & 0xFF); } } static public void swizzle_inplace_abcd_dcba(int[] data) { int size = data.length; for (int n = 0; n < size; n++) data[n] = Integer.reverseBytes(data[n]); } static public void swizzle_inplace_abcd_bcda(int[] data) { int size = data.length; for (int n = 0; n < size; n++) { int v = data[n]; data[n] = (v << 8) | ((v >>> 24) & 0xFF); } } */ }
package com.kylantraynor.civilizations; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import org.eclipse.jetty.server.Server; import com.kylantraynor.civilizations.commands.CommandAnswer; import com.kylantraynor.civilizations.commands.CommandBlueprint; import com.kylantraynor.civilizations.commands.CommandCamp; import com.kylantraynor.civilizations.commands.CommandCivilizations; import com.kylantraynor.civilizations.commands.CommandGroup; import com.kylantraynor.civilizations.commands.CommandHouse; import com.kylantraynor.civilizations.commands.CommandPlot; import com.kylantraynor.civilizations.commands.CommandRegion; import com.kylantraynor.civilizations.commands.CommandSelection; import com.kylantraynor.civilizations.commands.CommandStall; import com.kylantraynor.civilizations.groups.settlements.Camp; import com.kylantraynor.civilizations.groups.settlements.Settlement; import com.kylantraynor.civilizations.groups.settlements.forts.SmallOutpost; import com.kylantraynor.civilizations.groups.settlements.plots.Plot; import com.kylantraynor.civilizations.hook.draggyrpg.DraggyRPGHook; import com.kylantraynor.civilizations.hook.dynmap.DynmapHook; import com.kylantraynor.civilizations.hook.lwc.LWCHook; import com.kylantraynor.civilizations.hook.titlemanager.TitleManagerHook; import com.kylantraynor.civilizations.hook.towny.CommandTownyTown; import com.kylantraynor.civilizations.hook.towny.TownyHook; import com.kylantraynor.civilizations.hook.towny.TownyListener; import com.kylantraynor.civilizations.hook.towny.TownyTown; import com.kylantraynor.civilizations.listeners.ChatListener; import com.kylantraynor.civilizations.listeners.CivilizationsListener; import com.kylantraynor.civilizations.listeners.MenuListener; import com.kylantraynor.civilizations.listeners.ProtectionListener; import com.kylantraynor.civilizations.listeners.TerritoryListener; import com.kylantraynor.civilizations.listeners.VehiclesListener; import com.kylantraynor.civilizations.listeners.WebListener; import com.kylantraynor.civilizations.managers.CacheManager; import com.kylantraynor.civilizations.managers.GroupManager; import com.kylantraynor.civilizations.managers.LockManager; import com.kylantraynor.civilizations.managers.SelectionManager; import com.kylantraynor.civilizations.protection.Protection; import com.kylantraynor.civilizations.settings.CivilizationsSettings; import com.kylantraynor.civilizations.territories.InfluenceMap; import com.kylantraynor.civilizations.util.MaterialAndData; import fr.rhaz.webservers.WebServers.API; public class Civilizations extends JavaPlugin{ /** * Plugin Constants */ public static final String MC_SERVER_VERSION = org.bukkit.Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; public static final String PLUGIN_NAME = "Civilizations"; public static final int SETTLEMENT_MERGE_RADIUS = 25; /** * Currently running instance of Civilizations */ public static Civilizations currentInstance; /** * Header displayed in chat */ public static String messageHeader = ChatColor.GOLD + "[" + ChatColor.GOLD + ChatColor.BOLD + "Civilizations" + ChatColor.GOLD + "] "; private boolean clearBuildProjectsOnRestart = true; private boolean clearing = false; private boolean DEBUG = false; private ArrayList<Player> playersInProtectionMode = new ArrayList<Player>(); static private HashMap<Player, Protection> selectedProtections = new HashMap<Player, Protection>(); static private FileConfiguration config; public static HashMap<Player, Protection> getSelectedProtections(){ return selectedProtections; } private static List<BukkitRunnable> processes = new ArrayList<BukkitRunnable>(); /* * Listeners */ private static CivilizationsListener mainListener = new CivilizationsListener(); private static MenuListener menuListener = new MenuListener(); private static TerritoryListener territoryListener = new TerritoryListener(); private static ProtectionListener protectionListener = new ProtectionListener(); private static WebListener webListener = new WebListener(); private static ChatListener chatListener = new ChatListener(); private static VehiclesListener vehiclesListener = new VehiclesListener(); private static TownyListener townyListener = new TownyListener(); /* * InfluenceMaps */ private static Map<World, InfluenceMap> influenceMaps = new HashMap<World, InfluenceMap>(); /** * Returns the main listener of Civilizations. * @return CivilizationsListener */ public static CivilizationsListener getMainListener(){ return mainListener; } /** * Returns the FileConfiguration of the current running instance. * @return FileConfiguration */ public static FileConfiguration getInstanceConfig(){ return currentInstance.getConfig(); } private static Server webServer; public static boolean useChat = false; public static Server getWebServer(){ return webServer; } /** * Sends a message to the console with the specified level. * @param level of the message. * @param message to send. * @see Level */ public static void log(String level, String message){ if(level != null){ Level lvl = Level.parse(level); Bukkit.getServer().getLogger().log(lvl, message); } else { Bukkit.getServer().getLogger().log(Level.ALL, "["+level+"] " + message); } } /** * Function called when the plugin is enabled. */ @Override public void onEnable(){ currentInstance = this; saveDefaultConfig(); File f = new File(this.getDataFolder(), "config.yml"); CivilizationsSettings settings = new CivilizationsSettings(); try { settings.load(f); } catch (Exception e){ e.printStackTrace(); } config = this.getConfig(); MaterialAndData.reloadFromConfig(config); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(getMainListener(), this); pm.registerEvents(getMenuListener(), this); pm.registerEvents(getTerritoryListener(), this); pm.registerEvents(getProtectionListener(), this); pm.registerEvents(getChatListener(), this); pm.registerEvents(getVehiclesListener(), this); registerAchievements(); GroupManager.loadAll(); loadHooks(pm); GroupManager.ensurePlotsAreLinked(); loadInfluenceMaps(); startGroupUpdater(20L * 60 * 5); startProtectionUpdater(40L); startEconomyUpdater(20L * 60); startBuilderUpdater(20L * 2); initManagers(); setupCommands(); /*int port = 8120; try { startWebServer(port); log("INFO", "Successfully started webserver on port " + port); } catch (Exception e) { log("WARNING", "Could not start webserver on port " + port + ". This port is probably already in use."); e.printStackTrace(); }*/ } private void loadInfluenceMaps() { List<String> enabledWorlds = getConfig().getStringList("EnabledWorlds"); for(World w : Bukkit.getServer().getWorlds()){ if(enabledWorlds.contains(w.getName())) influenceMaps.put(w, new InfluenceMap(w)); } for(InfluenceMap map : influenceMaps.values()){ log("INFO", "Generating influence map for " + map.getWorld().getName() + "."); map.generateFull(); log("INFO", "Map was generated with " + map.getCells().length + " cells."); } } private void initManagers() { LockManager.init(); SelectionManager.init(); CacheManager.init(); } private void freesManagers(){ SelectionManager.free(); } private void registerAchievements() { /*Achievement createCamp = new Achievement("create_camp", "Setting up Camp", null, new ArrayList<String>()); createCamp.getDescription().add("Create a camp."); AchievementManager.registerAchievement(createCamp);*/ } private void startWebServer(int port) throws Exception { createServerViews(); webServer = API.createServer(port, "Civilizations", ""); webServer.start(); getServer().getPluginManager().registerEvents(getWebListener(), this); } private void createServerViews() { } private Listener getMenuListener() { return Civilizations.menuListener; } /** * Loads all the hooks allowing the interaction with other plugins. * @param pm PluginManager */ private void loadHooks(PluginManager pm) { if(DynmapHook.load(pm)){ log("INFO", "Hook to Dynmap: OK"); } else { log("WARNING", "Hook to Dynmap: NO, " + PLUGIN_NAME + " will not be displayed."); } if(TitleManagerHook.load(pm)){ log("INFO", "Hook to TitleManager: OK"); } else { log("WARNING", "Hook to Titlemanager: NO"); } if(TownyHook.isActive()){ log("INFO", "Side by side with Towny: OK"); } else { log("INFO", "Side by side with Towny: NO"); } if(Economy.load(pm)){ log("INFO", "Economy: OK"); } else { log("WARNING", "Economy: NO, " + PLUGIN_NAME + " will not be working properly."); } if(LWCHook.isActive()) {log("INFO", "LWC: OK"); } else {log("INFO", "LWC: NO"); } if(DynmapHook.isEnabled()) DynmapHook.activateDynmap(); if(TownyHook.isActive()){ TownyHook.loadTownyTowns(); pm.registerEvents(getTownyListener(), this); } if(DraggyRPGHook.isActive()) { log("INFO", "DraggyRPG: OK"); DraggyRPGHook.loadLevelCenters(); } else {log("INFO", "DraggyRPG: NO");} } /** * Setups all the commands for Civilizations. */ private void setupCommands() { this.getCommand("Civilizations").setExecutor(new CommandCivilizations()); this.getCommand("CivilizationsAnswer").setExecutor(new CommandAnswer()); this.getCommand("Blueprint").setExecutor(new CommandBlueprint()); this.getCommand("Group").setExecutor(new CommandGroup()); this.getCommand("House").setExecutor(new CommandHouse()); this.getCommand("Camp").setExecutor(new CommandCamp()); this.getCommand("Region").setExecutor(new CommandRegion()); this.getCommand("Selection").setExecutor(new CommandSelection()); this.getCommand("Plot").setExecutor(new CommandPlot()); this.getCommand("Stall").setExecutor(new CommandStall()); if(TownyHook.isActive()){ this.getCommand("TownyTown").setExecutor(new CommandTownyTown()); } } /** * Starts the process updating the group. * @param interval in ticks between updates. */ private void startGroupUpdater(long interval) { BukkitRunnable br = new BukkitRunnable(){ @Override public void run() { GroupManager.updateAllGroups(); } }; br.runTaskTimer(this, (long) (Math.random() * 20), interval); } /** * Starts the process of updating the economy. * @param interval in ticks between updates. */ private void startEconomyUpdater(long interval) { BukkitRunnable br = new BukkitRunnable(){ @Override public void run() { } }; br.runTaskTimer(this, (long) (Math.random() * 20), interval); } /** * Starts process updating protection visibility in an asynchronous thread. * @param interval in ticks between updates. */ private void startProtectionUpdater(long interval) { BukkitRunnable pr = new BukkitRunnable(){ @Override public void run() { BukkitRunnable[] prcs = Civilizations.getProcesses().toArray(new BukkitRunnable[Civilizations.getProcesses().size()]); for(BukkitRunnable r : prcs){ if(Civilizations.getProcesses().contains(r)){ Civilizations.getProcesses().remove(r); } r.runTask(Civilizations.currentInstance); } } }; pr.runTaskTimerAsynchronously(this, (long) (Math.random() * interval), interval); } /** * Starts process updating the builders. * @param interval in ticks between updates. */ private void startBuilderUpdater(long interval) { BukkitRunnable br = new BukkitRunnable(){ @Override public void run() { GroupManager.updateAllBuilders(); } }; br.runTaskTimer(this, (long) (Math.random() * 20), interval); } /** * Updates the given protection's visibility for the given player. * @param player to display the change to. * @param protection to update. */ protected static void updateProtectionVisibility(Player player, Protection protection) { if(getPlayersInProtectionMode().contains(player)){ if(Civilizations.getSelectedProtections().get(player).equals(protection)){ protection.highlight(player); } else { protection.hide(player); } } else { protection.hide(player); } } @Override public void onDisable(){ if(clearBuildProjectsOnRestart) GroupManager.cancelAllBuilds(); GroupManager.updateAllGroups(); if(DynmapHook.isEnabled()){ DynmapHook.disable(); } freesManagers(); MaterialAndData.saveToConfig(getConfig()); saveConfig(); } /** * Select the protection the given player is targeting. * @param player */ public static void selectTargetProtection(Player player) { Location l = null; for(Block b : player.getLineOfSight((Set<Material>) null, 100)){ if(b.getType() != Material.AIR){ if(Settlement.isProtected(b.getLocation())){ l = b.getLocation(); } break; } } if(l != null){ //Try getting a plot Plot plot = null; Protection newProt = null; for(Plot p : CacheManager.getPlotList()){ if(p.protects(l)){ plot = p; newProt = p.getProtection(); } } Settlement s = null; if(newProt == null){ s = Settlement.getAt(l); if(s != null){ newProt = s.getProtection(); } } else { s = plot.getSettlement(); } Protection old = Civilizations.getSelectedProtections().get(player); if(newProt.equals(old)){ player.sendMessage(messageHeader + ChatColor.RED + "Protection already selected."); return; } Civilizations.getSelectedProtections().put(player, newProt); String plotName = " Settlement"; if(plot != null) plotName = " " + plot.getName(); player.sendMessage(messageHeader + ChatColor.GREEN + "Protection selected: " + (s != null ? s.getName() : "") + plotName + "."); if(old != null) updateProtectionVisibility(player, old); updateProtectionVisibility(player, newProt); } else { if(Civilizations.getSelectedProtections().containsKey(player)){ Protection old = Civilizations.getSelectedProtections().get(player); Civilizations.getSelectedProtections().remove(player); updateProtectionVisibility(player, old); } player.sendMessage(messageHeader + ChatColor.RED + "No protection selected."); } } /** * Displays a message to a player when they move from one area to another. * @param fromL * @param toL * @param player */ public static void displayProtectionStatus(Location fromL, Location toL, Player player) { boolean fromProtected = Settlement.isProtected(fromL); boolean toProtected = Settlement.isProtected(toL); if((fromProtected && toProtected) || (!fromProtected && toProtected)){ Settlement from = Settlement.getAt(fromL); Settlement to = Settlement.getAt(toL); if(!to.equals(from)){ if(to instanceof Camp){ TitleManagerHook.sendTitle("", ChatColor.GRAY + to.getName(), 10, 40, 10, player); if(!to.isMember(player)){ TitleManagerHook.sendActionBar("Protected Area", player, false); } } else if(to instanceof SmallOutpost){ TitleManagerHook.sendTitle("", ChatColor.GRAY + to.getName(), 10, 40, 10, player); if(!to.isMember(player)){ TitleManagerHook.sendActionBar("Protected Area", player, false); } } else if(to instanceof TownyTown){ TitleManagerHook.sendTitle("", ChatColor.GRAY + to.getName(), 10, 40, 10, player); if(!to.isMember(player)){ TitleManagerHook.sendActionBar("Protected Area", player, false); } } } else { Plot p = null; for(Plot plot : CacheManager.getPlotList()){ if(plot.protects(toL)) p = plot; } if(p == null) return; if(!p.protects(fromL)){ TitleManagerHook.sendActionBar(p.getName(), player, false); } } } else if( fromProtected && !toProtected){ Settlement from = Settlement.getAt(fromL); if(from != null){ if(from instanceof Camp){ if(from.isMember(player)){ TitleManagerHook.sendActionBar("Leaving Camp", player, false); } } else if(from instanceof SmallOutpost){ if(from.isMember(player)){ TitleManagerHook.sendActionBar("Leaving Outpost", player, false); } } else if(from instanceof TownyTown){ TitleManagerHook.sendActionBar("Leaving " + from.getName(), player, false); } } } else { } } /** * Get the directory the group files are stored in. * @return File */ public static File getGroupDirectory(){ File f = new File(currentInstance.getDataFolder(), "Groups"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the camp files are stored in. * @return File */ public static File getCampDirectory(){ File f = new File(currentInstance.getDataFolder(), "Camps"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the house files are stored in. * @return File */ public static File getHouseDirectory() { File f = new File(currentInstance.getDataFolder(), "Houses"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the fort files are stored in. * @return File */ public static File getFortDirectory() { File f = new File(currentInstance.getDataFolder(), "Forts"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the Small Outpost files are stored in. * @return File */ public static File getSmallOutpostDirectory() { File f = new File(getFortDirectory(), "Small Outposts"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the plot files are stored in. * @return File */ public static File getPlotDirectory() { File f = new File(currentInstance.getDataFolder(), "Plots"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the keep files are stored in. * @return File */ public static File getKeepDirectory() { File f = new File(getPlotDirectory(), "Keeps"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the keep files are stored in. * @return File */ public static File getHousePlotDirectory() { File f = new File(getPlotDirectory(), "Houses"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Get the directory the stall files are stored in. * @return File */ public static File getMarketStallDirectory() { File f = new File(getPlotDirectory(), "Stalls"); if(!f.exists()) f.mkdir(); return f; } /** * Get the directory in which the nation files are stored. * @return File */ public static File getNationDirectory(){ File f = new File(currentInstance.getDataFolder(), "Nations"); if(!f.exists()) f.mkdir(); return f; } public static File getPlayerDataDirectory() { File f = new File(currentInstance.getDataFolder(), "PlayerData"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } public static File getBlueprintDirectory(){ File f = new File(currentInstance.getDataFolder(), "Blueprints"); if(!f.exists()) f.mkdir(); return f; } public static File getWarehousesDirectory() { File f = new File(getPlotDirectory(), "Warehouses"); if(!f.exists()) f.mkdir(); return f; } public static File getWebDirectory() { File f = new File(currentInstance.getDataFolder(), "Web"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } public static File getPrivateWebDirectory(){ File f = new File(getWebDirectory(), "WEB-INF"); if(f.exists()){ return f; } else { f.mkdir(); return f; } } /** * Gets the list of processes. * @return List<BukkitRunnable> */ public static List<BukkitRunnable> getProcesses() { return processes; } /** * Sets the list of processes. * @param processes to set. */ public static void setProcesses(List<BukkitRunnable> processes) { Civilizations.processes = processes; } /** * Gets a list of all the players currently in Protection Mode. * @return List<Player> */ public static List<Player> getPlayersInProtectionMode() { return currentInstance.playersInProtectionMode; } /** * Sets the list of the players currently in Protection Mode. * @param playersInProtectionMode */ public static void setPlayersInProtectionMode(ArrayList<Player> playersInProtectionMode) { currentInstance.playersInProtectionMode = playersInProtectionMode; } /** * No description * @return */ public static boolean isClearing() { return currentInstance.clearing; } /** * No description * @param clearing */ public static void setClearing(boolean clearing) { currentInstance.clearing = clearing; } public static TerritoryListener getTerritoryListener() { return territoryListener; } public static ProtectionListener getProtectionListener() { return protectionListener; } public static TownyListener getTownyListener(){ return townyListener; } public boolean isDEBUG() { return DEBUG; } public void setDEBUG(boolean dEBUG) { DEBUG = dEBUG; } public static void DEBUG(String message){ if(!currentInstance.DEBUG) return; log("INFO", message); } public static WebListener getWebListener() { return webListener; } public static void setWebListener(WebListener webListener) { Civilizations.webListener = webListener; } public static ChatListener getChatListener() { return chatListener; } public static Listener getVehiclesListener() { return vehiclesListener; } public static void callEvent(Event event) { currentInstance.getServer().getPluginManager().callEvent(event); } public static InfluenceMap getInfluenceMap(World w){ return influenceMaps.get(w); } public static File getBuilderDirectory() { File f = new File(currentInstance.getDataFolder(), "Builders"); if(!f.exists()) f.mkdir(); return f; } public static File getTownyTownsDirectory() { File f = new File(currentInstance.getDataFolder(), "Towny"); if(!f.exists()) f.mkdir(); return f; } }
package ca.ualberta.cmput301w14t08.geochan.fragments; import java.util.ArrayList; import org.osmdroid.api.IMapController; import org.osmdroid.bonuspack.overlays.Marker; import org.osmdroid.bonuspack.overlays.Polyline; import org.osmdroid.bonuspack.routing.OSRMRoadManager; import org.osmdroid.bonuspack.routing.Road; import org.osmdroid.bonuspack.routing.RoadManager; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import ca.ualberta.cmput301w14t08.geochan.R; import ca.ualberta.cmput301w14t08.geochan.helpers.ErrorDialog; import ca.ualberta.cmput301w14t08.geochan.helpers.LocationListenerService; import ca.ualberta.cmput301w14t08.geochan.models.Comment; import ca.ualberta.cmput301w14t08.geochan.models.GeoLocation; /** * A Fragment class for displaying Maps. A Map View will disp * * @author Brad Simons * */ public class MapViewFragment extends Fragment { final public static double ZOOM_FACTOR = 1.2; private MapView openMapView; private LocationListenerService locationListenerService; private GeoLocation currentLocation; private GeoPoint startGeoPoint; private Polyline roadOverlay; private Comment topComment; private ArrayList<GeoPoint> geoPoints; private ArrayList<Marker> markers; private int maxLat; private int maxLong; private int minLat; private int minLong; /** * Gets the view when inflated, then calls setZoomLevel to display the * correct map area. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(false); geoPoints = new ArrayList<GeoPoint>(); markers = new ArrayList<Marker>(); return inflater.inflate(R.layout.fragment_map_view, container, false); } /** * inflates the menu and adds and add items to action bar if present */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. MenuItem item = menu.findItem(R.id.action_settings); item.setVisible(true); super.onCreateOptionsMenu(menu, inflater); } /** * Initiates a location listener which immediately starts listening for * location updates. Gets the current location as well. Then unpacks the * bundle passed to the fragment. It then gets the map setup and prepares * the min and max latitude and longitude required to display the map * properly for calculation. Then finally sets the zoom level */ @Override public void onStart() { super.onStart(); locationListenerService = new LocationListenerService(getActivity()); locationListenerService.startListening(); currentLocation = new GeoLocation(locationListenerService); Bundle args = getArguments(); topComment = (Comment) args.getParcelable("thread_comment"); // To calculate the max and min latitude and longitude of all // the comments, we set the min's to max integer values and vice versa // then have values of each comment modify these variables minLat = Integer.MAX_VALUE; maxLat = Integer.MIN_VALUE; minLong = Integer.MAX_VALUE; maxLong = Integer.MIN_VALUE; GeoLocation geoLocation = topComment.getLocation(); if (geoLocation.getLocation() == null) { ErrorDialog.show(getActivity(), "Thread has no location"); FragmentManager fm = getFragmentManager(); fm.popBackStackImmediate(); } else { this.setupMap(topComment); this.setMarkers(); this.calculateZoomSpan(); this.setZoomLevel(); } } /** * Calls onStop in the superclass, and tells the locationListener to stop * listening. */ @Override public void onStop() { super.onStop(); locationListenerService.stopListening(); } /** * This sets up the comment location the map. The map is centered at the * location of the comment GeoLocation, and places a pin at this point. It * then calls handleChildComments to place pins for each child comment in * the thread. * * @param topComment */ public void setupMap(Comment topComment) { openMapView = (MapView) getActivity().findViewById(R.id.open_map_view); openMapView.setTileSource(TileSourceFactory.MAPNIK); openMapView.setBuiltInZoomControls(true); openMapView.setMultiTouchControls(true); openMapView.getController().setZoom(5); if (commentLocationIsValid(topComment)) { GeoLocation geoLocation = topComment.getLocation(); startGeoPoint = new GeoPoint(geoLocation.getLatitude(), geoLocation.getLongitude()); geoPoints.add(startGeoPoint); Marker startMarker = createMarker(startGeoPoint); startMarker.setTitle("OP"); if (geoLocation.getLocationDescription() != null) { startMarker.setSubDescription(geoLocation.getLocationDescription()); } else { startMarker.setSubDescription("Unknown Location"); } startMarker.showInfoWindow(); markers.add(startMarker); handleChildComments(topComment); } openMapView.invalidate(); } /** * Sets the default zoom level for the mapview. This takes the max and min * of both lat and long, and zooms to span the area required. It also * animates to the startGeoPoint, which is the location of the topComment. * The values must be padded with a zoom_factor, which is a static class * variable */ public void setZoomLevel() { // get the mapController and set the zoom IMapController mapController = openMapView.getController(); // set the zoom span // mapController.zoomToSpan((int) (Math.abs(maxLat - minLat) * // ZOOM_FACTOR), // (int) (Math.abs(maxLong - minLong) * ZOOM_FACTOR)); // set the zoom center mapController.animateTo(geoPoints.get(0)); } /** * Recursive method for handling all comments in the thread. First checks if * the comment has any children or not. If none, simply return. Otherwise, * call setGeoPointMarker for each child of the comment. Call * checkCommmentLocation to calculate the min and max of the lat and long * for the entire thread. Then finally make a recursive call to check if a * child comment has any children. * * @param comment */ private void handleChildComments(Comment comment) { ArrayList<Comment> children = comment.getChildren(); if (children.size() == 0) { return; } else { for (Comment childComment : children) { GeoLocation commentLocation = childComment.getLocation(); if (commentLocationIsValid(childComment)) { GeoPoint childGeoPoint = new GeoPoint(commentLocation.getLatitude(), commentLocation.getLongitude()); geoPoints.add(childGeoPoint); markers.add(createMarker(childGeoPoint)); handleChildComments(childComment); } } } } /** * Checks to see if a comment in the thread has valid GPS coordinates. Valid * coordinates are -90 < lat < 90, and -180 < longitude < 180. It also does * a null check on location. * * @param comment * @return isValidLocation */ public boolean commentLocationIsValid(Comment comment) { GeoLocation location = comment.getLocation(); if (location.getLocation() == null) { return false; } else { return (location.getLatitude() >= -90.0 || location.getLatitude() <= 90.0 || location.getLongitude() >= -180.0 || location.getLongitude() <= 180.0); } } public void calculateZoomSpan() { for (GeoPoint geoPoint : geoPoints) { int geoLat = geoPoint.getLatitudeE6(); int geoLong = geoPoint.getLongitudeE6(); maxLat = Math.max(geoLat, maxLat); minLat = Math.min(geoLat, minLat); maxLong = Math.max(geoLong, maxLong); minLong = Math.min(geoLong, minLong); } } /** * Creates a marker object, sets its position to the GeoPoint location * passed, and then adds the marker to the map overlays. * * @param geoPoint */ public void setMarkers() { Log.e("size of markers", Integer.toString(markers.size())); for (Marker marker : markers) { openMapView.getOverlays().add(marker); } } public Marker createMarker(GeoPoint geoPoint) { Log.e("creating","a marker"); Marker marker = new Marker(openMapView); marker.setPosition(geoPoint); marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM); return marker; } /** * Called when the get_directions_button is clicked. Displays directions * from the users current location to the comment location. Uses an Async * task to get map overlay. If the users current location cannot be * obtained, an error is shown to the screen and the async task is not * called */ public void getDirections() { if (currentLocation.getLocation() == null) { ErrorDialog.show(getActivity(), "Could not retrieve your location"); } else { new MapAsyncTask().execute(); setMarkers(); } openMapView.invalidate(); } /** * Async task class. This task is designed to retrieve directions from the * users current location to the location of the original post of the * thread. It displays a ProgressDialog while the location is being * retrieved. * * @author bradsimons */ class MapAsyncTask extends AsyncTask<Void, Void, Void> { ProgressDialog directionsLoadingDialog = new ProgressDialog(getActivity()); /** * Displays a ProgessDialog while the task is executing */ @Override protected void onPreExecute() { super.onPreExecute(); directionsLoadingDialog.setMessage("Getting Directions"); directionsLoadingDialog.show(); } /** * Calculating the directions from the current to the location of the * topComment. Builds a road overlay and adds it to the openMapView * objects overlays */ @Override protected Void doInBackground(Void... params) { RoadManager roadManager = new OSRMRoadManager(); ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(); waypoints.add(new GeoPoint(currentLocation.getLatitude(), currentLocation .getLongitude())); waypoints.add(startGeoPoint); Road road = roadManager.getRoad(waypoints); roadOverlay = RoadManager.buildRoadOverlay(road, getActivity()); openMapView.getOverlays().add(roadOverlay); return null; } /** * Task is now finished, dismiss the ProgressDialog and refresh the map */ @Override protected void onPostExecute(Void result) { super.onPostExecute(result); directionsLoadingDialog.dismiss(); openMapView.invalidate(); } } }
package org.slf4j.ext; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.slf4j.helpers.MessageFormatter; import org.slf4j.spi.LocationAwareLogger; /** * A utility that provides standard mechanisms for logging certain kinds of * activities. * * @author Ralph Goers * @author Ceki Gulcu */ public class XLogger extends LoggerWrapper implements Logger { private static final String FQCN = XLogger.class.getName(); static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW"); static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY"); static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT"); static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION"); static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING"); static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING"); static String EXIT_MESSAGE_0 = "exit"; static String EXIT_MESSAGE_1 = "exit with ({})"; static String ENTRY_MESSAGE_0 = "entry"; static String ENTRY_MESSAGE_1 = "entry with ({})"; static String ENTRY_MESSAGE_2 = "entry with ({}, {})"; static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})"; static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})"; static int ENTRY_MESSAGE_ARRAY_LEN = 5; static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN]; static { ENTRY_MARKER.add(FLOW_MARKER); EXIT_MARKER.add(FLOW_MARKER); THROWING_MARKER.add(EXCEPTION_MARKER); CATCHING_MARKER.add(EXCEPTION_MARKER); ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0; ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1; ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2; ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3; ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4; } /** * Given an underlying logger, constuct an XLogger * * @param logger * underlying logger */ public XLogger(Logger logger) { super(logger, FQCN); } /** * Log method entry. * * @param argArray * supplied parameters */ public void entry(Object... argArray) { if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { String messagePattern = null; if (argArray.length <= ENTRY_MESSAGE_ARRAY_LEN) { messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length]; } else { messagePattern = buildMessagePattern(argArray.length); } String formattedMessage = MessageFormatter.arrayFormat(messagePattern, argArray); ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, formattedMessage, null); } } /** * Log method exit */ public void exit() { if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, EXIT_MESSAGE_0, null); } } /** * Log method exit * * @param result * The result of the method being exited */ public void exit(Object result) { if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { String formattedMessage = MessageFormatter.format(EXIT_MESSAGE_1, result); ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, formattedMessage, null); } } /** * Log an exception being thrown * * @param throwable * the exception being caught. */ public void throwing(Throwable throwable) { if (instanceofLAL) { ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", throwable); } } /** * Log an exception being caught * * @param throwable * the exception being caught. */ public void catching(Throwable throwable) { if (instanceofLAL) { ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", throwable); } } private static String buildMessagePattern(int len) { StringBuilder sb = new StringBuilder(); sb.append(" entry with ("); for (int i = 0; i < len; i++) { sb.append("{}"); if (i != len - 1) sb.append(", "); } sb.append(')'); return sb.toString(); } }
package org.voltdb; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.KeeperException.NoNodeException; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.apache.zookeeper_voltpatches.data.Stat; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.DBBPool; import org.voltcore.utils.DBBPool.BBContainer; import org.voltcore.utils.Pair; import org.voltdb.catalog.Database; import org.voltdb.catalog.Table; import org.voltdb.iv2.SiteTaskerQueue; import org.voltdb.iv2.SnapshotTask; import org.voltdb.sysprocs.saverestore.SnapshotPredicates; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.CompressionService; import org.voltdb.utils.MiscUtils; import com.google.common.collect.ListMultimap; import com.google.common.collect.Maps; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; /** * Encapsulates the state needed to manage an ongoing snapshot at the * per-execution site level. Also contains some static global snapshot * counters. This class requires callers to maintain thread safety; * generally (exclusively?) it is driven by ExecutionSite, each of * which has a SnapshotSiteProcessor. */ public class SnapshotSiteProcessor { private static final VoltLogger SNAP_LOG = new VoltLogger("SNAPSHOT"); /** Global count of execution sites on this node performing snapshot */ public static final Set<Object> ExecutionSitesCurrentlySnapshotting = Collections.synchronizedSet(new HashSet<Object>()); /** * Ensure only one thread running the setup fragment does the creation * of the targets and the distribution of the work. */ public static final Object m_snapshotCreateLock = new Object(); public static CyclicBarrier m_snapshotCreateSetupBarrier = null; public static CyclicBarrier m_snapshotCreateFinishBarrier = null; public static final Runnable m_snapshotCreateSetupBarrierAction = new Runnable() { @Override public void run() { Runnable r = SnapshotSiteProcessor.m_snapshotCreateSetupBarrierActualAction.getAndSet(null); if (r != null) { r.run(); } } }; public static AtomicReference<Runnable> m_snapshotCreateSetupBarrierActualAction = new AtomicReference<Runnable>(); public static void readySnapshotSetupBarriers(int numSites) { synchronized (SnapshotSiteProcessor.m_snapshotCreateLock) { if (SnapshotSiteProcessor.m_snapshotCreateSetupBarrier == null) { SnapshotSiteProcessor.m_snapshotCreateFinishBarrier = new CyclicBarrier(numSites); SnapshotSiteProcessor.m_snapshotCreateSetupBarrier = new CyclicBarrier(numSites, SnapshotSiteProcessor.m_snapshotCreateSetupBarrierAction); } else if (SnapshotSiteProcessor.m_snapshotCreateSetupBarrier.isBroken()) { SnapshotSiteProcessor.m_snapshotCreateSetupBarrier.reset(); SnapshotSiteProcessor.m_snapshotCreateFinishBarrier.reset(); } } } /** * Sequence numbers for export tables. This is repopulated before each snapshot by each execution site * that reaches the snapshot. */ private static final Map<String, Map<Integer, Pair<Long, Long>>> m_exportSequenceNumbers = new HashMap<String, Map<Integer, Pair<Long, Long>>>(); /** * This field is the same values as m_exportSequenceNumbers once they have been extracted * in SnapshotSaveAPI.createSetup and then passed back in to SSS.initiateSnapshots. The only * odd thing is that setting up a snapshot can fail in which case values will have been populated into * m_exportSequenceNumbers and kept until the next snapshot is started in which case they are repopulated. * Decoupling them seems like a good idea in case snapshot code is every re-organized. */ private Map<String, Map<Integer, Pair<Long,Long>>> m_exportSequenceNumbersToLogOnCompletion; /* * Do some random tasks that are deferred to the snapshot termination thread. * The two I know about are syncing/closing the digest file and catalog copy */ public static final ConcurrentLinkedQueue<Runnable> m_tasksOnSnapshotCompletion = new ConcurrentLinkedQueue<Runnable>(); /* * Random tasks performed on each site after the snapshot tasks are finished but * before the snapshot transaction is finished. */ public static final Map<Integer, PostSnapshotTask> m_siteTasksPostSnapshotting = Collections.synchronizedMap(new HashMap<Integer, PostSnapshotTask>()); /** * Pick a buffer length that is big enough to store at least one of the largest size tuple supported * in the system (2 megabytes). Add a fudge factor for metadata. */ public static final int m_snapshotBufferLength = (1024 * 1024 * 2) + Short.MAX_VALUE; public static final int m_snapshotBufferCompressedLen = CompressionService.maxCompressedLength(m_snapshotBufferLength); /** * Limit the number of buffers that are outstanding at any given time */ private static final AtomicInteger m_availableSnapshotBuffers = new AtomicInteger(16); /** * The last EE out has to shut off the lights. Cache a list * of targets in case this EE ends up being the one that needs * to close each target. */ private ArrayList<SnapshotDataTarget> m_snapshotTargets = null; /** * Map of tasks for tables that still need to be snapshotted. * Once a table has finished serializing stuff, it's removed from the map. * Making it a TreeMap so that it works through one table at time, easier to debug. */ private ListMultimap<Integer, SnapshotTableTask> m_snapshotTableTasks = null; private Map<Integer, TableStreamer> m_streamers = null; private long m_lastSnapshotTxnId; private int m_lastSnapshotNumHosts; private final int m_snapshotPriority; private boolean m_lastSnapshotSucceded = true; /** * List of threads to join to block on snapshot completion * when using completeSnapshotWork(). */ private ArrayList<Thread> m_snapshotTargetTerminators = null; /** * When a buffer is returned to the pool a new snapshot task will be offered to the queue * to ensure the EE wakes up and does any potential snapshot work with that buffer */ private final SiteTaskerQueue m_siteTaskerQueue; private final Random m_random = new Random(); /* * Interface that will be checked when scheduling snapshot work in IV2. * Reports whether the site is "idle" for whatever definition that may be. * If the site is idle then work will be scheduled immediately instead of being * throttled */ public interface IdlePredicate { public boolean idle(long now); } private final IdlePredicate m_idlePredicate; /* * Synchronization is handled by SnapshotSaveAPI.startSnapshotting * Store the export sequence numbers for every table and partition. This will * be called by every execution site before the snapshot starts. Then the execution * site that gets the setup permit will use getExportSequenceNumbers to retrieve the full * set and reset the contents. */ public static void populateExportSequenceNumbersForExecutionSite(SystemProcedureExecutionContext context) { Database database = context.getDatabase(); for (Table t : database.getTables()) { if (!CatalogUtil.isTableExportOnly(database, t)) continue; Map<Integer, Pair<Long,Long>> sequenceNumbers = m_exportSequenceNumbers.get(t.getTypeName()); if (sequenceNumbers == null) { sequenceNumbers = new HashMap<Integer, Pair<Long, Long>>(); m_exportSequenceNumbers.put(t.getTypeName(), sequenceNumbers); } long[] ackOffSetAndSequenceNumber = context.getSiteProcedureConnection().getUSOForExportTable(t.getSignature()); sequenceNumbers.put( context.getPartitionId(), Pair.of( ackOffSetAndSequenceNumber[0], ackOffSetAndSequenceNumber[1])); } } public static Map<String, Map<Integer, Pair<Long, Long>>> getExportSequenceNumbers() { HashMap<String, Map<Integer, Pair<Long, Long>>> sequenceNumbers = new HashMap<String, Map<Integer, Pair<Long, Long>>>(m_exportSequenceNumbers); m_exportSequenceNumbers.clear(); return sequenceNumbers; } private long m_quietUntil = 0; public SnapshotSiteProcessor(SiteTaskerQueue siteQueue, int snapshotPriority) { this(siteQueue, snapshotPriority, new IdlePredicate() { @Override public boolean idle(long now) { throw new UnsupportedOperationException(); } }); } public SnapshotSiteProcessor(SiteTaskerQueue siteQueue, int snapshotPriority, IdlePredicate idlePredicate) { m_siteTaskerQueue = siteQueue; m_snapshotPriority = snapshotPriority; m_idlePredicate = idlePredicate; } public void shutdown() throws InterruptedException { m_snapshotCreateSetupBarrier = null; m_snapshotCreateFinishBarrier = null; if (m_snapshotTargetTerminators != null) { for (Thread t : m_snapshotTargetTerminators) { t.join(); } } } private BBContainer createNewBuffer(final BBContainer origin) { return new BBContainer(origin.b, origin.address) { @Override public void discard() { origin.discard(); m_availableSnapshotBuffers.incrementAndGet(); /* * If IV2 is enabled, don't run the potential snapshot work jigger * until the quiet period restrictions have been met. In IV2 doSnapshotWork * is always called with ignoreQuietPeriod and the scheduling is instead done * via the STPE in RealVoltDB. * * The goal of the quiet period is to spread snapshot work out over time and minimize * the impact on latency * * If snapshot priority is 0 then running the jigger immediately is the specified * policy anyways. 10 would be the largest delay */ if (m_snapshotPriority > 0) { final long now = System.currentTimeMillis(); //Ask if the site is idle, and if it is queue the work immediately if (m_idlePredicate.idle(now)) { m_siteTaskerQueue.offer(new SnapshotTask()); return; } //Cache the value locally, the dirty secret is that in edge cases multiple threads //will read/write briefly, but it isn't a big deal since the scheduling can be wrong //briefly. Caching it locally will make the logic here saner because it can't change //as execution progresses final long quietUntil = m_quietUntil; /* * If the current time is > than quietUntil then the quiet period is over * and the snapshot work should be done immediately * * Otherwise it needs to be scheduled in the future and the next quiet period * needs to be calculated */ if (now > quietUntil) { m_siteTaskerQueue.offer(new SnapshotTask()); //Now push the quiet period further into the future, //generally no threads will be racing to do this //since the execution site only interacts with one snapshot data target at a time //except when it is switching tables. It doesn't really matter if it is wrong //it will just result in a little extra snapshot work being done close together m_quietUntil = System.currentTimeMillis() + (5 * m_snapshotPriority) + ((long)(m_random.nextDouble() * 15)); } else { //Schedule it to happen after the quiet period has elapsed VoltDB.instance().schedulePriorityWork( new Runnable() { @Override public void run() { m_siteTaskerQueue.offer(new SnapshotTask()); } }, quietUntil - now, 0, TimeUnit.MILLISECONDS); /* * This is the same calculation as above except the future is not based * on the current time since the quiet period was already in the future * and we need to move further past it since we just scheduled snapshot work * at the end of the current quietUntil value */ m_quietUntil = quietUntil + (5 * m_snapshotPriority) + ((long)(m_random.nextDouble() * 15)); } } else { m_siteTaskerQueue.offer(new SnapshotTask()); } } }; } public void initiateSnapshots( SystemProcedureExecutionContext context, SnapshotFormat format, Deque<SnapshotTableTask> tasks, List<SnapshotDataTarget> targets, long txnId, int numHosts, Map<String, Map<Integer, Pair<Long, Long>>> exportSequenceNumbers) { ExecutionSitesCurrentlySnapshotting.add(this); final long now = System.currentTimeMillis(); m_quietUntil = now + 200; m_lastSnapshotSucceded = true; m_lastSnapshotTxnId = txnId; m_lastSnapshotNumHosts = numHosts; m_snapshotTableTasks = MiscUtils.sortedArrayListMultimap(); m_streamers = Maps.newHashMap(); m_snapshotTargets = new ArrayList<SnapshotDataTarget>(); m_snapshotTargetTerminators = new ArrayList<Thread>(); m_exportSequenceNumbersToLogOnCompletion = exportSequenceNumbers; for (final SnapshotDataTarget target : targets) { if (target.needsFinalClose()) { assert(m_snapshotTargets != null); m_snapshotTargets.add(target); } } // Table doesn't implement hashCode(), so use the table ID as key for (Map.Entry<Integer, byte[]> tablePredicates : makeTablesAndPredicatesToSnapshot(tasks).entrySet()) { int tableId = tablePredicates.getKey(); TableStreamer streamer = new TableStreamer(tableId, format.getStreamType(), m_snapshotTableTasks.get(tableId)); if (!streamer.activate(context, tablePredicates.getValue())) { VoltDB.crashLocalVoltDB("Failed to activate snapshot stream on table " + CatalogUtil.getTableNameFromId(context.getDatabase(), tableId), false, null); } m_streamers.put(tableId, streamer); } /* * Resize the buffer pool to contain enough buffers for the number of tasks. The buffer * pool will be cleaned up at the end of the snapshot. * * For the general case of only one snapshot at a time, this will have the same behavior * as before, 5 buffers per snapshot. * * TODO: This is not a good algorithm for general snapshot coalescing. Rate limiting * won't work as expected with this approach. For general snapshot coalescing, * a better approach like pool per output target should be used. */ int maxTableTaskSize = 0; for (Collection<SnapshotTableTask> perTableTasks : m_snapshotTableTasks.asMap().values()) { maxTableTaskSize = Math.max(maxTableTaskSize, perTableTasks.size()); } // This site has no snapshot work to do, still queue a task to clean up. Otherwise, // the snapshot will never finish. queueInitialSnapshotTasks(now); } private void queueInitialSnapshotTasks(long now) { VoltDB.instance().schedulePriorityWork( new Runnable() { @Override public void run() { m_siteTaskerQueue.offer(new SnapshotTask()); } }, (m_quietUntil + (5 * m_snapshotPriority) - now), 0, TimeUnit.MILLISECONDS); m_quietUntil += 5 * m_snapshotPriority; } private Map<Integer, byte[]> makeTablesAndPredicatesToSnapshot(Collection<SnapshotTableTask> tasks) { Map<Integer, SnapshotPredicates> tablesAndPredicates = Maps.newHashMap(); Map<Integer, byte[]> predicateBytes = Maps.newHashMap(); for (SnapshotTableTask task : tasks) { SNAP_LOG.debug("Examining SnapshotTableTask: " + task); // Add the task to the task list for the given table m_snapshotTableTasks.put(task.m_table.getRelativeIndex(), task); // Make sure there is a predicate object for each table, the predicate could contain // empty expressions. So activateTableStream() doesn't have to do a null check. SnapshotPredicates predicates = tablesAndPredicates.get(task.m_table.getRelativeIndex()); if (predicates == null) { predicates = new SnapshotPredicates(task.m_table.getRelativeIndex()); tablesAndPredicates.put(task.m_table.getRelativeIndex(), predicates); } predicates.addPredicate(task.m_predicate, task.m_deleteTuples); } for (Map.Entry<Integer, SnapshotPredicates> e : tablesAndPredicates.entrySet()) { predicateBytes.put(e.getKey(), e.getValue().toBytes()); } return predicateBytes; } /** * Create an output buffer for each task. * @return null if there aren't enough buffers left in the pool. */ private List<BBContainer> getOutputBuffers(Collection<SnapshotTableTask> tableTasks) { final int desired = tableTasks.size(); int available = m_availableSnapshotBuffers.get(); if (!m_availableSnapshotBuffers.compareAndSet(available, available - desired)) return null; List<BBContainer> outputBuffers = new ArrayList<BBContainer>(tableTasks.size()); for (int ii = 0; ii < tableTasks.size(); ii++) { final BBContainer origin = DBBPool.allocateDirectAndPool(m_snapshotBufferLength); outputBuffers.add(createNewBuffer(origin)); } return outputBuffers; } private void asyncTerminateReplicatedTableTasks(Collection<SnapshotTableTask> tableTasks) { for (final SnapshotTableTask tableTask : tableTasks) { /** * Replicated tables are assigned to a single ES on each site and that ES * is responsible for closing the data target. Done in a separate * thread so the EE can continue working. */ if (tableTask.m_table.getIsreplicated() && tableTask.m_target.getFormat().canCloseEarly()) { final Thread terminatorThread = new Thread("Replicated SnapshotDataTarget terminator ") { @Override public void run() { try { tableTask.m_target.close(); } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } }; m_snapshotTargetTerminators.add(terminatorThread); terminatorThread.start(); } } } public Future<?> doSnapshotWork(SystemProcedureExecutionContext context) { ListenableFuture<?> retval = null; /* * This thread will null out the reference to m_snapshotTableTasks when * a snapshot is finished. If the snapshot buffer is loaned out that means * it is pending I/O somewhere so there is no work to do until it comes back. */ if (m_snapshotTableTasks == null) { return retval; } /* * Try to serialize a block from a table, if the table is finished, * remove the tasks from the task map and move on to the next table. If a block is * successfully serialized, break out of the loop and release the site thread for more * transaction work. */ Iterator<Map.Entry<Integer, Collection<SnapshotTableTask>>> taskIter = m_snapshotTableTasks.asMap().entrySet().iterator(); while (taskIter.hasNext()) { Map.Entry<Integer, Collection<SnapshotTableTask>> taskEntry = taskIter.next(); final int tableId = taskEntry.getKey(); final Collection<SnapshotTableTask> tableTasks = taskEntry.getValue(); final List<BBContainer> outputBuffers = getOutputBuffers(tableTasks); if (outputBuffers == null) { // Not enough buffers available break; } // Stream more and add a listener to handle any failures Pair<ListenableFuture, Boolean> streamResult = m_streamers.get(tableId).streamMore(context, outputBuffers, null); if (streamResult.getFirst() != null) { final ListenableFuture writeFutures = streamResult.getFirst(); writeFutures.addListener(new Runnable() { @Override public void run() { try { writeFutures.get(); } catch (Throwable t) { if (m_lastSnapshotSucceded) { SNAP_LOG.error("Error while attempting to write snapshot data", t); m_lastSnapshotSucceded = false; } } } }, MoreExecutors.sameThreadExecutor()); } /** * The table streamer will return false when there is no more data left to pull from that table. The * enclosing loop ensures that the next table is then addressed. */ if (!streamResult.getSecond()) { asyncTerminateReplicatedTableTasks(tableTasks); // XXX: Guava's multimap will clear the tableTasks collection when the entry is // removed from the containing map, so don't use the collection after removal! taskIter.remove(); SNAP_LOG.debug("Finished snapshot tasks for table " + tableId + ": " + tableTasks); } else { break; } } /** * If there are no more tasks then this particular EE is finished doing snapshot work * Check the AtomicInteger to find out if this is the last one. */ if (m_snapshotTableTasks.isEmpty()) { SNAP_LOG.debug("Finished with tasks"); // In case this is a non-blocking snapshot, do the post-snapshot tasks here. runPostSnapshotTasks(context); final ArrayList<SnapshotDataTarget> snapshotTargets = m_snapshotTargets; m_snapshotTargets = null; m_snapshotTableTasks = null; boolean IamLast = false; synchronized (ExecutionSitesCurrentlySnapshotting) { if (!ExecutionSitesCurrentlySnapshotting.contains(this)) { VoltDB.crashLocalVoltDB( "Currently snapshotting site didn't find itself in set of snapshotting sites", true, null); } IamLast = ExecutionSitesCurrentlySnapshotting.size() == 1; if (!IamLast) { ExecutionSitesCurrentlySnapshotting.remove(this); } } /** * If this is the last one then this EE must close all the SnapshotDataTargets. * Done in a separate thread so the EE can go and do other work. It will * sync every file descriptor and that may block for a while. */ if (IamLast) { SNAP_LOG.debug("I AM LAST!"); final long txnId = m_lastSnapshotTxnId; final int numHosts = m_lastSnapshotNumHosts; final Map<String, Map<Integer, Pair<Long,Long>>> exportSequenceNumbers = m_exportSequenceNumbersToLogOnCompletion; m_exportSequenceNumbersToLogOnCompletion = null; final Thread terminatorThread = new Thread("Snapshot terminator") { @Override public void run() { try { /* * Be absolutely sure the snapshot is finished * and synced to disk before another is started */ for (Thread t : m_snapshotTargetTerminators){ if (t == this) { continue; } try { t.join(); } catch (InterruptedException e) { return; } } for (final SnapshotDataTarget t : snapshotTargets) { try { t.close(); } catch (IOException e) { m_lastSnapshotSucceded = false; throw new RuntimeException(e); } catch (InterruptedException e) { m_lastSnapshotSucceded = false; throw new RuntimeException(e); } } Runnable r = null; while ((r = m_tasksOnSnapshotCompletion.poll()) != null) { try { r.run(); } catch (Exception e) { SNAP_LOG.error("Error running snapshot completion task", e); } } } finally { try { logSnapshotCompleteToZK( txnId, numHosts, m_lastSnapshotSucceded, exportSequenceNumbers); } finally { /** * Remove this last site from the set here after the terminator has run * so that new snapshots won't start until * everything is on disk for the previous snapshot. This prevents a really long * snapshot initiation procedure from occurring because it has to contend for * filesystem resources */ ExecutionSitesCurrentlySnapshotting.remove(SnapshotSiteProcessor.this); } } } }; m_snapshotTargetTerminators.add(terminatorThread); terminatorThread.start(); } } return retval; } public static void runPostSnapshotTasks(SystemProcedureExecutionContext context) { SNAP_LOG.debug("Running post-snapshot tasks"); PostSnapshotTask postSnapshotTask = m_siteTasksPostSnapshotting.remove(context.getPartitionId()); if (postSnapshotTask != null) { postSnapshotTask.run(context); } } private static void logSnapshotCompleteToZK( long txnId, int numHosts, boolean snapshotSuccess, Map<String, Map<Integer, Pair<Long, Long>>> exportSequenceNumbers) { ZooKeeper zk = VoltDB.instance().getHostMessenger().getZK(); final String snapshotPath = VoltZK.completed_snapshots + "/" + txnId; boolean success = false; while (!success) { Stat stat = new Stat(); byte data[] = null; try { data = zk.getData(snapshotPath, false, stat); } catch (Exception e) { VoltDB.crashLocalVoltDB("This ZK get should never fail", true, e); } if (data == null) { VoltDB.crashLocalVoltDB("Data should not be null if the node exists", false, null); } try { JSONObject jsonObj = new JSONObject(new String(data, "UTF-8")); if (jsonObj.getLong("txnId") != txnId) { VoltDB.crashLocalVoltDB("TxnId should match", false, null); } int remainingHosts = jsonObj.getInt("hostCount") - 1; jsonObj.put("hostCount", remainingHosts); if (!snapshotSuccess) { SNAP_LOG.error("Snapshot failed at this node, snapshot will not be viable for log truncation"); jsonObj.put("isTruncation", false); } mergeExportSequenceNumbers(jsonObj, exportSequenceNumbers); zk.setData(snapshotPath, jsonObj.toString(4).getBytes("UTF-8"), stat.getVersion()); } catch (KeeperException.BadVersionException e) { continue; } catch (Exception e) { VoltDB.crashLocalVoltDB("This ZK call should never fail", true, e); } success = true; } /* * If we are running without command logging there will be no consumer for * the completed snapshot messages. Consume them here to bound space usage in ZK. */ try { TreeSet<String> snapshots = new TreeSet<String>(zk.getChildren(VoltZK.completed_snapshots, false)); while (snapshots.size() > 30) { try { zk.delete(VoltZK.completed_snapshots + "/" + snapshots.first(), -1); } catch (NoNodeException e) {} catch (Exception e) { VoltDB.crashLocalVoltDB( "Deleting a snapshot completion record from ZK should only fail with NoNodeException", true, e); } snapshots.remove(snapshots.first()); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Retrieving list of completed snapshots from ZK should never fail", true, e); } try { VoltDB.instance().getHostMessenger().getZK().delete( VoltZK.nodes_currently_snapshotting + "/" + VoltDB.instance().getHostMessenger().getHostId(), -1); } catch (NoNodeException e) { SNAP_LOG.warn("Expect the snapshot node to already exist during deletion", e); } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } } /* * When recording snapshot completion we also record export sequence numbers * as JSON. Need to merge our sequence numbers with existing numbers * since multiple replicas will submit the sequence number */ private static void mergeExportSequenceNumbers(JSONObject jsonObj, Map<String, Map<Integer, Pair<Long,Long>>> exportSequenceNumbers) throws JSONException { JSONObject tableSequenceMap; if (jsonObj.has("exportSequenceNumbers")) { tableSequenceMap = jsonObj.getJSONObject("exportSequenceNumbers"); } else { tableSequenceMap = new JSONObject(); jsonObj.put("exportSequenceNumbers", tableSequenceMap); } for (Map.Entry<String, Map<Integer, Pair<Long, Long>>> tableEntry : exportSequenceNumbers.entrySet()) { JSONObject sequenceNumbers; final String tableName = tableEntry.getKey(); if (tableSequenceMap.has(tableName)) { sequenceNumbers = tableSequenceMap.getJSONObject(tableName); } else { sequenceNumbers = new JSONObject(); tableSequenceMap.put(tableName, sequenceNumbers); } for (Map.Entry<Integer, Pair<Long, Long>> partitionEntry : tableEntry.getValue().entrySet()) { final Integer partitionId = partitionEntry.getKey(); final String partitionIdString = partitionId.toString(); final Long ackOffset = partitionEntry.getValue().getFirst(); final Long partitionSequenceNumber = partitionEntry.getValue().getSecond(); /* * Check that the sequence number is the same everywhere and log if it isn't. * Not going to crash because we are worried about poison pill transactions. */ if (sequenceNumbers.has(partitionIdString)) { JSONObject existingEntry = sequenceNumbers.getJSONObject(partitionIdString); Long existingSequenceNumber = existingEntry.getLong("sequenceNumber"); if (!existingSequenceNumber.equals(partitionSequenceNumber)) { SNAP_LOG.error("Found a mismatch in export sequence numbers while recording snapshot metadata " + " for partition " + partitionId + " the sequence number should be the same at all replicas, but one had " + existingSequenceNumber + " and another had " + partitionSequenceNumber); } existingEntry.put(partitionIdString, Math.max(existingSequenceNumber, partitionSequenceNumber)); Long existingAckOffset = existingEntry.getLong("ackOffset"); existingEntry.put("ackOffset", Math.max(ackOffset, existingAckOffset)); } else { JSONObject newObj = new JSONObject(); newObj.put("sequenceNumber", partitionSequenceNumber); newObj.put("ackOffset", ackOffset); sequenceNumbers.put(partitionIdString, newObj); } } } } /** * Is the EE associated with this SnapshotSiteProcessor currently * snapshotting? * * No thread safety here, but assuming single-threaded access from * the IV2 site. */ public boolean isEESnapshotting() { return m_snapshotTableTasks != null; } /** * Do snapshot work exclusively until there is no more. Also blocks * until the fsync() and close() of snapshot data targets has completed. */ public HashSet<Exception> completeSnapshotWork(SystemProcedureExecutionContext context) throws InterruptedException { HashSet<Exception> retval = new HashSet<Exception>(); while (m_snapshotTableTasks != null) { Future<?> result = doSnapshotWork(context); if (result != null) { try { result.get(); } catch (ExecutionException e) { final boolean added = retval.add((Exception)e.getCause()); assert(added); } catch (Exception e) { final boolean added = retval.add((Exception)e.getCause()); assert(added); } } } /** * Block until the sync has actually occurred in the forked threads. * The threads are spawned even in the blocking case to keep it simple. */ if (m_snapshotTargetTerminators != null) { for (final Thread t : m_snapshotTargetTerminators) { t.join(); } m_snapshotTargetTerminators = null; } return retval; } }
package mjava.io; import mjava.lang.MString; public class SimpleInputStream { static { System.loadLibrary("SimpleInputStream"); } public native boolean hasnextLine(); public native char[] readLine(); public static void run() { SimpleInputStream sis = new SimpleInputStream(); SimpleOutputStream sos = new SimpleOutputStream(); while (sis.hasnextLine()) { char s[] = sis.readLine(); sos.write(new MString(s)); } } }
package org.unitime.timetable.dataexchange; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.dom4j.Element; import org.unitime.timetable.model.CourseOffering; import org.unitime.timetable.model.LastLikeCourseDemand; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.Student; import org.unitime.timetable.model.SubjectArea; import org.unitime.timetable.model.dao.SubjectAreaDAO; /** * * @author Timothy Almon * */ public class LastLikeCourseDemandImport extends BaseImport { private HashMap<String, SubjectArea> subjectAreas = new HashMap<String, SubjectArea>(); private HashMap<String, String> courseOfferings = new HashMap<String, String>(); public LastLikeCourseDemandImport() { super(); } public void loadXml(Element root) throws Exception { try { String campus = root.attributeValue("campus"); String year = root.attributeValue("year"); String term = root.attributeValue("term"); Session session = Session.getSessionUsingInitiativeYearTerm(campus, year, term); if(session == null) { throw new Exception("No session found for the given campus, year, and term."); } loadSubjectAreas(session.getSessionId()); loadCourseOfferings(session.getSessionId()); beginTransaction(); getHibSession().createQuery("delete LastLikeCourseDemand ll where ll.subjectArea.uniqueId in " + "(select s.uniqueId from SubjectArea s where s.session.uniqueId=:sessionId)"). setLong("sessionId", session.getUniqueId()).executeUpdate(); flush(true); for ( Iterator it = root.elementIterator(); it.hasNext(); ) { Element element = (Element) it.next(); String externalId = element.attributeValue("externalId"); Student student = fetchStudent(externalId, session.getSessionId()); if(student == null) continue; loadCourses(element, student, session); flushIfNeeded(true); } flush(true); getHibSession().createQuery("update CourseOffering c set c.demand="+ "(select count(distinct d.student) from LastLikeCourseDemand d where "+ "(c.subjectArea=d.subjectArea and c.courseNbr=d.courseNbr)) where "+ "c.permId is null and c.subjectArea.uniqueId in (select sa.uniqueId from SubjectArea sa where sa.session.uniqueId=:sessionId)"). setLong("sessionId", session.getUniqueId()).executeUpdate(); getHibSession().createQuery("update CourseOffering c set c.demand="+ "(select count(distinct d.student) from LastLikeCourseDemand d where "+ "d.student.session=c.subjectArea.session and c.permId=d.coursePermId) where "+ "c.permId is not null and c.subjectArea.uniqueId in (select sa.uniqueId from SubjectArea sa where sa.session.uniqueId=:sessionId)"). setLong("sessionId", session.getUniqueId()).executeUpdate(); commitTransaction(); } catch (Exception e) { fatal("Exception: " + e.getMessage(), e); rollbackTransaction(); throw e; } } Student fetchStudent(String externalId, Long sessionId) { return (Student) this. getHibSession(). createQuery("select distinct a from Student as a where a.externalUniqueId=:externalId and a.session.uniqueId=:sessionId"). setLong("sessionId", sessionId.longValue()). setString("externalId", externalId). setCacheable(true). uniqueResult(); } private void loadCourses(Element studentEl, Student student, Session session) throws Exception { for (Iterator it = studentEl.elementIterator(); it.hasNext();) { Element el = (Element) it.next(); String subject = el.attributeValue("subject"); if(subject == null) { throw new Exception("Subject is required."); } String courseNumber = el.attributeValue("courseNumber"); if(courseNumber == null) { throw new Exception("Course Number is required."); } SubjectArea area = subjectAreas.get(subject); if(area == null) { System.out.println("Subject area " + subject + " not found"); continue; } LastLikeCourseDemand demand = new LastLikeCourseDemand(); demand.setCoursePermId(courseOfferings.get(courseNumber + area.getUniqueId().toString())); demand.setCourseNbr(courseNumber); demand.setStudent(student); demand.setSubjectArea(area); demand.setPriority(Integer.decode(el.attributeValue("priority"))); getHibSession().save(demand); } } private void loadSubjectAreas(Long sessionId) { List areas = new ArrayList(); areas = new SubjectAreaDAO(). getSession(). createQuery("select distinct a from SubjectArea as a where a.session.uniqueId=:sessionId"). setLong("sessionId", sessionId.longValue()). setCacheable(true). list(); for (Iterator it = areas.iterator(); it.hasNext();) { SubjectArea area = (SubjectArea) it.next(); subjectAreas.put(area.getSubjectAreaAbbreviation(), area); } } private void loadCourseOfferings(Long sessionId) { for (Iterator it = CourseOffering.findAll(sessionId).iterator(); it.hasNext();) { CourseOffering offer = (CourseOffering) it.next(); if (offer.getPermId()!=null) courseOfferings.put(offer.getCourseNbr() + offer.getSubjectArea().getUniqueId().toString(), offer.getPermId()); } } }
package com.jme.math; import java.io.IOException; import java.io.Serializable; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; /** * <code>Ray</code> defines a line segment which has an origin and a direction. * That is, a point and an infinite ray is cast from this point. The ray is * defined by the following equation: R(t) = origin + t*direction for t >= 0. * @author Mark Powell * @version $Id: Ray.java,v 1.22 2006-08-07 13:53:16 nca Exp $ */ public class Ray implements Serializable, Savable { //todo: merge with Line? private static final long serialVersionUID = 1L; /** The ray's begining point. */ public Vector3f origin; /** The direction of the ray. */ public Vector3f direction; protected static final Vector3f tempVa=new Vector3f(); protected static final Vector3f tempVb=new Vector3f(); protected static final Vector3f tempVc=new Vector3f(); protected static final Vector3f tempVd=new Vector3f(); /** * Constructor instantiates a new <code>Ray</code> object. As default, the * origin is (0,0,0) and the direction is (0,0,0). * */ public Ray() { origin = new Vector3f(); direction = new Vector3f(); } /** * Constructor instantiates a new <code>Ray</code> object. The origin and * direction are given. * @param origin the origin of the ray. * @param direction the direction the ray travels in. */ public Ray(Vector3f origin, Vector3f direction) { this.origin = origin; this.direction = direction; } /** * <code>intersect</code> determines if the Ray intersects a triangle. * @param t the Triangle to test against. * @return true if the ray collides. */ public boolean intersect(Triangle t) { return intersect(t.get(0), t.get(1), t.get(2)); } /** * <code>intersect</code> determines if the Ray intersects a triangle * defined by the specified points. * * @param v0 * first point of the triangle. * @param v1 * second point of the triangle. * @param v2 * third point of the triangle. * @return true if the ray collides. */ public boolean intersect(Vector3f v0,Vector3f v1,Vector3f v2){ return intersectWhere(v0, v1, v2, null); } /** * <code>intersectWhere</code> determines if the Ray intersects a triangle. It then * stores the point of intersection in the given loc vector * @param t the Triangle to test against. * @param loc * storage vector to save the collision point in (if the ray * collides) * @return true if the ray collides. */ public boolean intersectWhere(Triangle t, Vector3f loc) { return intersectWhere(t.get(0), t.get(1), t.get(2), loc); } /** * <code>intersectWhere</code> determines if the Ray intersects a triangle * defined by the specified points and if so it stores the point of * intersection in the given loc vector. * * @param v0 * first point of the triangle. * @param v1 * second point of the triangle. * @param v2 * third point of the triangle. * @param loc * storage vector to save the collision point in (if the ray * collides) if null, only boolean is calculated. * @return true if the ray collides. */ public boolean intersectWhere(Vector3f v0, Vector3f v1, Vector3f v2, Vector3f loc) { return intersects(v0, v1, v2, loc, false, false ); } /** * <code>intersectWherePlanar</code> determines if the Ray intersects a * triangle and if so it stores the point of * intersection in the given loc vector as t, u, v where t is the distance * from the origin to the point of intersection and u,v is the intersection * point in terms of the triangle plane. * * @param t the Triangle to test against. * @param loc * storage vector to save the collision point in (if the ray * collides) as t, u, v * @return true if the ray collides. */ public boolean intersectWherePlanar(Triangle t, Vector3f loc) { return intersectWherePlanar(t.get(0), t.get(1), t.get(2), loc); } /** * <code>intersectWherePlanar</code> determines if the Ray intersects a * triangle defined by the specified points and if so it stores the point of * intersection in the given loc vector as t, u, v where t is the distance * from the origin to the point of intersection and u,v is the intersection * point in terms of the triangle plane. * * @param v0 * first point of the triangle. * @param v1 * second point of the triangle. * @param v2 * third point of the triangle. * @param loc * storage vector to save the collision point in (if the ray * collides) as t, u, v * @return true if the ray collides. */ public boolean intersectWherePlanar(Vector3f v0, Vector3f v1, Vector3f v2, Vector3f loc) { return intersects(v0, v1, v2, loc, true, false ); } /** * <code>intersects</code> does the actual intersection work. * * @param v0 * first point of the triangle. * @param v1 * second point of the triangle. * @param v2 * third point of the triangle. * @param store * storage vector - if null, no intersection is calc'd * @param doPlanar * true if we are calcing planar results. * @param quad * @return true if ray intersects triangle */ private boolean intersects( Vector3f v0, Vector3f v1, Vector3f v2, Vector3f store, boolean doPlanar, boolean quad ) { Vector3f diff = origin.subtract(v0, tempVa); Vector3f edge1 = v1.subtract(v0, tempVb); Vector3f edge2 = v2.subtract(v0, tempVc); Vector3f norm = edge1.cross(edge2, tempVd); float dirDotNorm = direction.dot(norm); float sign; if (dirDotNorm > FastMath.FLT_EPSILON) { sign = 1; } else if (dirDotNorm < -FastMath.FLT_EPSILON) { sign = -1f; dirDotNorm = -dirDotNorm; } else { // ray and triangle/quad are parallel return false; } float dirDotDiffxEdge2 = sign * direction.dot(diff.cross(edge2, edge2)); if (dirDotDiffxEdge2 > 0.0f) { float dirDotEdge1xDiff = sign * direction.dot(edge1.crossLocal(diff)); if (dirDotEdge1xDiff >= 0.0f) { if ( !quad ? dirDotDiffxEdge2 + dirDotEdge1xDiff <= dirDotNorm : dirDotEdge1xDiff <= dirDotNorm ) { float diffDotNorm = -sign * diff.dot(norm); if (diffDotNorm >= 0.0f) { // ray intersects triangle // if storage vector is null, just return true, if (store == null) return true; // else fill in. float inv = 1f / dirDotNorm; float t = diffDotNorm * inv; if (!doPlanar) { store.set(origin).addLocal(direction.x * t, direction.y * t, direction.z * t); } else { // these weights can be used to determine // interpolated values, such as texture coord. // eg. texcoord s,t at intersection point: // s = w0*s0 + w1*s1 + w2*s2; // t = w0*t0 + w1*t1 + w2*t2; float w1 = dirDotDiffxEdge2 * inv; float w2 = dirDotEdge1xDiff * inv; //float w0 = 1.0f - w1 - w2; store.set(t, w1, w2); } return true; } } } } return false; } /** * <code>intersectWherePlanar</code> determines if the Ray intersects a * quad defined by the specified points and if so it stores the point of * intersection in the given loc vector as t, u, v where t is the distance * from the origin to the point of intersection and u,v is the intersection * point in terms of the quad plane. * One edge of the quad is [v0,v1], another one [v0,v2]. The behaviour thus is like * {@link #intersectWherePlanar(Vector3f, Vector3f, Vector3f, Vector3f)} except for * the extended area, which is equivalent to the union of the triangles [v0,v1,v2] * and [-v0+v1+v2,v1,v2]. * * @param v0 * top left point of the quad. * @param v1 * top right point of the quad. * @param v2 * bottom left point of the quad. * @param loc * storage vector to save the collision point in (if the ray * collides) as t, u, v * @return true if the ray collides with the quad. */ public boolean intersectWherePlanarQuad(Vector3f v0, Vector3f v1, Vector3f v2, Vector3f loc) { return intersects( v0, v1, v2, loc, true, true ); } /** * * @param p * @param loc * @return true if the ray collides with the given Plane */ public boolean intersectsWherePlane(Plane p, Vector3f loc) { float denominator = p.getNormal().dot(direction); if (denominator > -FastMath.FLT_EPSILON && denominator < FastMath.FLT_EPSILON) return false; // coplanar float numerator = -(p.getNormal().dot(origin) + p.getConstant()); float ratio = numerator / denominator; if (ratio < FastMath.FLT_EPSILON) return false; // intersects behind origin loc.set(direction).multLocal(ratio).addLocal(origin); return true; } /** * * <code>getOrigin</code> retrieves the origin point of the ray. * @return the origin of the ray. */ public Vector3f getOrigin() { return origin; } /** * * <code>setOrigin</code> sets the origin of the ray. * @param origin the origin of the ray. */ public void setOrigin(Vector3f origin) { this.origin = origin; } /** * * <code>getDirection</code> retrieves the direction vector of the ray. * @return the direction of the ray. */ public Vector3f getDirection() { return direction; } /** * * <code>setDirection</code> sets the direction vector of the ray. * @param direction the direction of the ray. */ public void setDirection(Vector3f direction) { this.direction = direction; } /** * Copies information from a source ray into this ray. * * @param source * the ray to copy information from */ public void set(Ray source) { origin.set(source.getOrigin()); direction.set(source.getDirection()); } public void write(JMEExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(origin, "origin", Vector3f.ZERO); capsule.write(direction, "direction", Vector3f.ZERO); } public void read(JMEImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); origin = (Vector3f)capsule.readSavable("origin", new Vector3f(Vector3f.ZERO)); direction = (Vector3f)capsule.readSavable("direction", new Vector3f(Vector3f.ZERO)); } public Class getClassTag() { return this.getClass(); } }
package es.logongas.fpempresa.util; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import javax.imageio.ImageIO; import org.apache.commons.io.output.NullOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Utilidades para el tratamiento de imagenes. * * @author logongas */ public class ImageUtil { static final Logger log = LogManager.getLogger(ImageUtil.class); public static boolean isValid(byte[] rawImage) { BufferedImage bufferedImage=readImage(rawImage); if (canWriteImageToJPEG(bufferedImage)) { return true; } else { BufferedImage bufferedImageWhiteBackground=getBufferedImageToWhiteBackground(bufferedImage); if (canWriteImageToJPEG(bufferedImageWhiteBackground)) { return true; } else { return false; } } } public static Image getImageLogFail(byte[] rawImage,String msgFail) { Image image; BufferedImage bufferedImage=readImage(rawImage); if (canWriteImageToJPEG(bufferedImage)) { image=bufferedImage; } else { BufferedImage bufferedImageWhiteBackground=getBufferedImageToWhiteBackground(bufferedImage); if (canWriteImageToJPEG(bufferedImageWhiteBackground)) { image=bufferedImageWhiteBackground; } else { log.warn("Fail Image to JPEG-msgFail="+msgFail); image=bufferedImageWhiteBackground; } } return image; } private static BufferedImage readImage(byte[] rawImage) { try { BufferedImage bufferedImage=ImageIO.read(new ByteArrayInputStream(rawImage)); return bufferedImage; } catch (Exception ex) { throw new RuntimeException(ex); } } private static boolean canWriteImageToJPEG(BufferedImage image) { try { ImageIO.write(image,"jpeg",new NullOutputStream()); return true; } catch (Exception ex) { return false; } } private static BufferedImage getBufferedImageToWhiteBackground(BufferedImage bufferedImage) { try { BufferedImage bufferedImageWhite = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = bufferedImageWhite.createGraphics(); graphics2D.setColor(Color.WHITE); graphics2D.fillRect(0, 0, bufferedImageWhite.getWidth(), bufferedImageWhite.getHeight()); graphics2D.drawImage(bufferedImage, 0, 0, bufferedImageWhite.getWidth(), bufferedImageWhite.getHeight(), null); graphics2D.dispose(); return bufferedImageWhite; } catch (Exception ex) { throw new RuntimeException(ex); } } }
package org.apache.commons.cli; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * A formatter of help messages for the current command line options * * @author Slawek Zachcial * @author John Keyes (john at integralsource.com) **/ public class HelpFormatter { public static final int DEFAULT_WIDTH = 74; public static final int DEFAULT_LEFT_PAD = 1; public static final int DEFAULT_DESC_PAD = 3; public static final String DEFAULT_SYNTAX_PREFIX = "usage: "; public static final String DEFAULT_OPT_PREFIX = "-"; public static final String DEFAULT_LONG_OPT_PREFIX = " public static final String DEFAULT_ARG_NAME = "arg"; public int defaultWidth; public int defaultLeftPad; public int defaultDescPad; public String defaultSyntaxPrefix; public String defaultNewLine; public String defaultOptPrefix; public String defaultLongOptPrefix; public String defaultArgName; public HelpFormatter() { defaultWidth = DEFAULT_WIDTH; defaultLeftPad = DEFAULT_LEFT_PAD; defaultDescPad = DEFAULT_DESC_PAD; defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX; defaultNewLine = System.getProperty("line.separator"); defaultOptPrefix = DEFAULT_OPT_PREFIX; defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX; defaultArgName = DEFAULT_ARG_NAME; } public void printHelp( String cmdLineSyntax, Options options ) { printHelp( defaultWidth, cmdLineSyntax, null, options, null, false ); } public void printHelp( String cmdLineSyntax, Options options, boolean autoUsage ) { printHelp( defaultWidth, cmdLineSyntax, null, options, null, autoUsage ); } public void printHelp( String cmdLineSyntax, String header, Options options, String footer ) { printHelp( cmdLineSyntax, header, options, footer, false ); } public void printHelp( String cmdLineSyntax, String header, Options options, String footer, boolean autoUsage ) { printHelp(defaultWidth, cmdLineSyntax, header, options, footer, autoUsage ); } public void printHelp( int width, String cmdLineSyntax, String header, Options options, String footer ) { printHelp( width, cmdLineSyntax, header, options, footer, false ); } public void printHelp( int width, String cmdLineSyntax, String header, Options options, String footer, boolean autoUsage ) { PrintWriter pw = new PrintWriter(System.out); printHelp( pw, width, cmdLineSyntax, header, options, defaultLeftPad, defaultDescPad, footer, autoUsage ); pw.flush(); } public void printHelp( PrintWriter pw, int width, String cmdLineSyntax, String header, Options options, int leftPad, int descPad, String footer ) throws IllegalArgumentException { printHelp( pw, width, cmdLineSyntax, header, options, leftPad, descPad, footer, false ); } public void printHelp( PrintWriter pw, int width, String cmdLineSyntax, String header, Options options, int leftPad, int descPad, String footer, boolean autoUsage ) throws IllegalArgumentException { if ( cmdLineSyntax == null || cmdLineSyntax.length() == 0 ) { throw new IllegalArgumentException("cmdLineSyntax not provided"); } if ( autoUsage ) { printUsage( pw, width, cmdLineSyntax, options ); } else { printUsage( pw, width, cmdLineSyntax ); } if ( header != null && header.trim().length() > 0 ) { printWrapped( pw, width, header ); } printOptions( pw, width, options, leftPad, descPad ); if ( footer != null && footer.trim().length() > 0 ) { printWrapped( pw, width, footer ); } } /** * <p>Prints the usage statement for the specified application.</p> * * @param pw The PrintWriter to print the usage statement * @param width ?? * @param appName The application name * @param options The command line Options * */ public void printUsage( PrintWriter pw, int width, String app, Options options ) { // initialise the string buffer StringBuffer buff = new StringBuffer( defaultSyntaxPrefix ).append( app ).append( " " ); // create a list for processed option groups ArrayList list = new ArrayList(); // temp variable Option option; // iterate over the options for ( Iterator i = options.getOptions().iterator(); i.hasNext(); ) { // get the next Option option = (Option) i.next(); // check if the option is part of an OptionGroup OptionGroup group = options.getOptionGroup( option ); // if the option is part of a group and the group has not already // been processed if( group != null && !list.contains(group)) { // add the group to the processed list list.add( group ); // get the names of the options from the OptionGroup Collection names = group.getNames(); buff.append( "[" ); // for each option in the OptionGroup for( Iterator iter = names.iterator(); iter.hasNext(); ) { buff.append( iter.next() ); if( iter.hasNext() ) { buff.append( " | " ); } } buff.append( "]" ); } // if the Option is not part of an OptionGroup else { // if the Option is not a required option if( !option.isRequired() ) { buff.append( "[" ); } if( !" ".equals( option.getOpt() ) ) { buff.append( "-" ).append( option.getOpt() ); } else { buff.append( "--" ).append( option.getLongOpt() ); } // if the Option has a value if( option.hasArg() && option.getArgName() != null ) { buff.append( " " ).append( option.getArgName() ); } // if the Option is not a required option if( !option.isRequired() ) { buff.append( "]" ); } buff.append( " " ); } } // call printWrapped printWrapped( pw, width, buff.toString().indexOf(' ')+1, buff.toString() ); } public void printUsage( PrintWriter pw, int width, String cmdLineSyntax ) { int argPos = cmdLineSyntax.indexOf(' ') + 1; printWrapped(pw, width, defaultSyntaxPrefix.length() + argPos, defaultSyntaxPrefix + cmdLineSyntax); } public void printOptions( PrintWriter pw, int width, Options options, int leftPad, int descPad ) { StringBuffer sb = new StringBuffer(); renderOptions(sb, width, options, leftPad, descPad); pw.println(sb.toString()); } public void printWrapped( PrintWriter pw, int width, String text ) { printWrapped(pw, width, 0, text); } public void printWrapped( PrintWriter pw, int width, int nextLineTabStop, String text ) { StringBuffer sb = new StringBuffer(text.length()); renderWrappedText(sb, width, nextLineTabStop, text); pw.println(sb.toString()); } protected StringBuffer renderOptions( StringBuffer sb, int width, Options options, int leftPad, int descPad ) { final String lpad = createPadding(leftPad); final String dpad = createPadding(descPad); //first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is //long opt; in parallel look for the longest opt string //this list will be then used to sort options ascending int max = 0; StringBuffer optBuf; List prefixList = new ArrayList(); Option option; List optList = options.helpOptions(); Collections.sort( optList, new StringBufferComparator() ); for ( Iterator i = optList.iterator(); i.hasNext(); ) { option = (Option) i.next(); optBuf = new StringBuffer(8); if (option.getOpt().equals(" ")) { optBuf.append(lpad).append(" " + defaultLongOptPrefix).append(option.getLongOpt()); } else { optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt()); if ( option.hasLongOpt() ) { optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt()); } } if( option.hasArg() ) { if( option.hasArgName() ) { optBuf.append(" <").append( option.getArgName() ).append( '>' ); } else { optBuf.append(' '); } } prefixList.add(optBuf); max = optBuf.length() > max ? optBuf.length() : max; } int x = 0; for ( Iterator i = optList.iterator(); i.hasNext(); ) { option = (Option) i.next(); optBuf = new StringBuffer( prefixList.get( x++ ).toString() ); if ( optBuf.length() < max ) { optBuf.append(createPadding(max - optBuf.length())); } optBuf.append( dpad ); int nextLineTabStop = max + descPad; if( option.getDescription() != null ) { optBuf.append( option.getDescription() ); } renderWrappedText(sb, width, nextLineTabStop, optBuf.toString()); if ( i.hasNext() ) { sb.append(defaultNewLine); } } return sb; } protected StringBuffer renderWrappedText( StringBuffer sb, int width, int nextLineTabStop, String text ) { int pos = findWrapPos( text, width, 0); if ( pos == -1 ) { sb.append(rtrim(text)); return sb; } else { sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } //all following lines must be padded with nextLineTabStop space characters final String padding = createPadding(nextLineTabStop); while ( true ) { text = padding + text.substring(pos).trim(); pos = findWrapPos( text, width, nextLineTabStop ); if ( pos == -1 ) { sb.append(text); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } } /** * Finds the next text wrap position after <code>startPos</code> for the text * in <code>sb</code> with the column width <code>width</code>. * The wrap point is the last postion before startPos+width having a whitespace * character (space, \n, \r). * * @param sb text to be analyzed * @param width width of the wrapped text * @param startPos position from which to start the lookup whitespace character * @return postion on which the text must be wrapped or -1 if the wrap position is at the end * of the text */ protected int findWrapPos( String text, int width, int startPos ) { int pos = -1; // the line ends before the max wrap pos or a new line char found if ( ((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) || ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width) ) { return pos; } else if ( (startPos + width) >= text.length() ) { return -1; } //look for the last whitespace character before startPos+width pos = startPos + width; char c; while ( pos >= startPos && (c = text.charAt(pos)) != ' ' && c != '\n' && c != '\r' ) { --pos; } //if we found it - just return if ( pos > startPos ) { return pos; } else { //must look for the first whitespace chearacter after startPos + width pos = startPos + width; while ( pos <= text.length() && (c = text.charAt(pos)) != ' ' && c != '\n' && c != '\r' ) { ++pos; } return pos == text.length() ? -1 : pos; } } protected String createPadding(int len) { StringBuffer sb = new StringBuffer(len); for ( int i = 0; i < len; ++i ) { sb.append(' '); } return sb.toString(); } protected String rtrim( String s ) { if ( s == null || s.length() == 0 ) { return s; } int pos = s.length(); while ( pos >= 0 && Character.isWhitespace(s.charAt(pos-1)) ) { --pos; } return s.substring(0, pos); } private static class StringBufferComparator implements Comparator { public int compare( Object o1, Object o2 ) { String str1 = stripPrefix(o1.toString()); String str2 = stripPrefix(o2.toString()); return (str1.compareTo(str2)); } private String stripPrefix(String strOption) { // Strip any leading '-' characters int iStartIndex = strOption.lastIndexOf('-'); if (iStartIndex == -1) { iStartIndex = 0; } return strOption.substring(iStartIndex); } } }
package org.jasig.portal; import org.jasig.portal.security.IPerson; import org.jasig.portal.services.LogService; import org.jasig.portal.services.GroupService; import java.sql.*; import org.jasig.portal.groups.IEntityGroup; import org.jasig.portal.groups.EntityImpl; import org.jasig.portal.groups.IGroupMember; /** * SQL implementation for managing creation and removal of User Portal Data * @author Susan Bramhall, Yale University */ public class RDBMUserIdentityStore implements IUserIdentityStore { /** * constructor gets an rdbm service */ public void RDBMUserIdentityStore () { rdbmService = new RdbmServices(); } /** * getuPortalUID - return a unique uPortal key for a user. * calls alternate signature with createPortalData set to false. * @param IPerson object * @return uPortalUID number * @throws Authorization exception if no user is found. */ public int getPortalUID (IPerson person) throws AuthorizationException { int uPortalUID=-1; uPortalUID=this.getPortalUID(person, false); return uPortalUID; } /** * * removeuPortalUID * @param uPortalUID integer key to uPortal data for a user * @throws Authorization exception if a sql error is encountered */ public void removePortalUID(int uPortalUID) throws Exception { Connection con = rdbmService.getConnection(); try { Statement stmt = con.createStatement(); if (con.getMetaData().supportsTransactions()) con.setAutoCommit(false); try { String SQLDelete = "DELETE FROM UP_USER WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_LAYOUT WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_PARAM WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_PROFILE WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_SS_USER_PARM WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_LAYOUT_PARAM WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_USER_UA_MAP WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); SQLDelete = "DELETE FROM UP_LAYOUT_STRUCT WHERE USER_ID = '" + uPortalUID + "'"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::removePortalUID(): " + SQLDelete); stmt.executeUpdate(SQLDelete); if (con.getMetaData().supportsTransactions()) con.commit(); } finally { stmt.close(); } } catch (SQLException se) { try { if (con.getMetaData().supportsTransactions()) con.rollback(); } catch (SQLException e) {} if (DEBUG>0){ System.err.println("SQLException: " + se.getMessage()); System.err.println("SQLState: " + se.getSQLState()); System.err.println("Message: " + se.getMessage()); System.err.println("Vendor: " + se.getErrorCode());} AuthorizationException ae = new AuthorizationException("SQL Database Error"); LogService.log(LogService.ERROR, "RDBMUserIdentityStore::removePortalUID(): " + ae); throw (ae); } finally { rdbmService.releaseConnection(con); } } /** * * getuPortalUID * @param IPerson object, boolean createPortalData indicating whether to try to create * all uPortal data for this user from temp[late prototype * @return uPortalUID number or -1 if unable to create user. * @throws Authorization exception if createPortalData is false and no user is found * or if a sql error is encountered */ public int getPortalUID (IPerson person, boolean createPortalData) throws AuthorizationException { int uPortalUID=-1; // Get a connection to the database Connection con = rdbmService.getConnection(); Statement stmt = null; try { // Create the JDBC statement stmt = con.createStatement(); } catch(SQLException se) { try { // Release the connection rdbmService.releaseConnection(con); } catch(Exception e) {} // Log the exception LogService.instance().log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): Could not create database statement", se); throw new AuthorizationException("RDBMUserIdentityStore: Could not create database statement"); } try { // Retrieve the USER_ID that is mapped to their portal UID String query = "SELECT USER_ID, USER_NAME FROM UP_USER WHERE USER_NAME = '" + person.getAttribute("username") + "'"; // DEBUG LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); // Execute the query ResultSet rset = stmt.executeQuery(query); // Check to see if we've got a result if (rset.next()) { uPortalUID = rset.getInt("USER_ID"); } // If no result and we're not creating new users then fail else if(!createPortalData) { throw new AuthorizationException("No portal information exists for user " + person.getAttribute("username")); } else { /* attempt to create portal data for a new user */ int newUID; int templateUID; int templateUSER_DFLT_USR_ID ; int templateUSER_DFLT_LAY_ID; java.sql.Date templateLST_CHAN_UPDT_DT = new java.sql.Date(System.currentTimeMillis()); // Retrieve the username of the user to use as a template for this new user String templateName=(String) person.getAttribute(templateAttrName); if (DEBUG>0) System.err.println("template name is "+templateName); // Just use the guest account if the template could not be found if (templateName == null || templateName=="") { templateUID = guestUID; } // Retrieve the information for the template user query = "SELECT USER_ID, USER_DFLT_USR_ID, USER_DFLT_LAY_ID,CURR_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT FROM UP_USER WHERE USER_NAME = '"+templateName+"'"; // DEBUG if (DEBUG>0) System.err.println(query); LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + query); // Execute the query rset = stmt.executeQuery(query); // Check to see if the template user exists if (rset.next()) { templateUID = rset.getInt("USER_ID"); templateUSER_DFLT_USR_ID = templateUID; templateUSER_DFLT_LAY_ID = rset.getInt("USER_DFLT_LAY_ID"); } else { throw new AuthorizationException("No information found for template user = " + templateName + ". Cannot create new account for " + person.getAttribute("username")); } /* get a new uid for the person */ try { newUID = UserLayoutStoreFactory.getUserLayoutStoreImpl().getIncrementIntegerId("UP_USER"); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): error getting next sequence: ", e); throw new AuthorizationException("RDBMUserIdentityStore error, see error log."); } /* put new user in groups that template is in */ try{ IEntityGroup everyone = GroupService.getEveryoneGroup(); IGroupMember me = new EntityImpl(String.valueOf(newUID), Class.forName("org.jasig.portal.security.IPerson")); IGroupMember template = new EntityImpl(String.valueOf(templateUID), Class.forName("org.jasig.portal.security.IPerson")); java.util.Iterator templateGroups = template.getContainingGroups(); while (templateGroups.hasNext()) { IEntityGroup eg = (IEntityGroup) templateGroups.next(); eg.addMember(me); eg.updateMembers(); } } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): error adding new user to groups: ", e); } try { // Turn off autocommit if the database supports it if (con.getMetaData().supportsTransactions()) { con.setAutoCommit(false); } } catch(SQLException se) { // Log the exception LogService.instance().log(LogService.WARN, "RDBMUserIdentityStore: Could not turn off autocommit", se); } String Insert = new String(); /* insert new user record in UP_USER */ Insert = "INSERT INTO UP_USER "+ "(USER_ID, USER_NAME, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, CURR_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT) "+ " VALUES ("+ newUID+", '"+ person.getAttribute("username")+ "',"+ templateUSER_DFLT_USR_ID+", "+ templateUSER_DFLT_LAY_ID+", "+ "null, "+ "null, "+ "null)"; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); stmt.executeUpdate(Insert); /* insert row into up_user_layout */ Insert = "INSERT INTO UP_USER_LAYOUT (USER_ID, LAYOUT_ID, LAYOUT_TITLE, INIT_STRUCT_ID ) "+ " SELECT "+newUID+", UUL.LAYOUT_ID, UUL.LAYOUT_TITLE, NULL FROM UP_USER_LAYOUT UUL WHERE UUL.USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); stmt.executeUpdate(Insert); /* insert row into up_user_param */ Insert = "INSERT INTO UP_USER_PARAM (USER_ID, USER_PARAM_NAME, USER_PARAM_VALUE ) "+ " SELECT "+newUID+", UUP.USER_PARAM_NAME, UUP.USER_PARAM_VALUE FROM UP_USER_PARAM UUP WHERE UUP.USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); stmt.executeUpdate(Insert); /* insert row into up_user_profile */ Insert = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID ) "+ " SELECT "+newUID+", UUP.PROFILE_ID, UUP.PROFILE_NAME, UUP.DESCRIPTION, NULL, NULL, NULL "+ "FROM UP_USER_PROFILE UUP WHERE UUP.USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); stmt.executeUpdate(Insert); /* insert row into up_user_ua_map */ Insert = "INSERT INTO UP_USER_UA_MAP (USER_ID, USER_AGENT, PROFILE_ID) "+ " SELECT "+newUID+", UUUA.USER_AGENT, UUUA.PROFILE_ID"+ " FROM UP_USER_UA_MAP UUUA WHERE USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserIdentityStore::getPortalUID(): " + Insert); stmt.executeUpdate(Insert); /* insert row(s) into up_ss_user_parm */ Insert = "INSERT INTO UP_SS_USER_PARM (USER_ID, PROFILE_ID, SS_ID, SS_TYPE, PARAM_NAME, PARAM_VAL) "+ " SELECT "+newUID+", USUP.PROFILE_ID, USUP.SS_ID, USUP.SS_TYPE, USUP.PARAM_NAME, USUP.PARAM_VAL "+ " FROM UP_SS_USER_PARM USUP WHERE USUP.USER_ID="+templateUID; LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + Insert); stmt.executeUpdate(Insert); // Check to see if the database supports transactions boolean supportsTransactions = false; try { supportsTransactions = con.getMetaData().supportsTransactions(); } catch(Exception e) {} if(supportsTransactions) { // Commit the transaction con.commit(); // Use our new ID if we made it through all of the SQL uPortalUID = newUID; } else { // Use our new ID if we made it through all of the SQL uPortalUID = newUID; } } } catch (SQLException se) { // Log the exception LogService.log(LogService.ERROR, "RDBMUserIdentityStore::getPortalUID(): " + se); // Rollback the transaction try { if (con.getMetaData().supportsTransactions()) { con.rollback(); } } catch (SQLException e) { LogService.instance().log(LogService.WARN, "RDBMUserIdentityStore.getPortalUID(): Unable to rollback transaction", se); } // DEBUG if (DEBUG>0) { System.err.println("SQLException: " + se.getMessage()); System.err.println("SQLState: " + se.getSQLState()); System.err.println("Message: " + se.getMessage()); System.err.println("Vendor: " + se.getErrorCode()); } // Throw an exception throw (new AuthorizationException("SQL database error while retrieving user's portal UID")); } finally { rdbmService.releaseConnection(con); } // Return the user's ID return(uPortalUID); } /** * put your documentation comment here * @param connection */ static final protected void commit (Connection connection) { try { if (connection.getMetaData().supportsTransactions()) connection.commit(); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::commit(): " + e); } } /** * put your documentation comment here * @param connection */ static final protected void rollback (Connection connection) { try { if (connection.getMetaData().supportsTransactions()) connection.rollback(); } catch (Exception e) { LogService.log(LogService.ERROR, "RDBMUserIdentityStore::rollback(): " + e); } } }
package org.jasig.portal.utils; /** * This class includes extension functions for the CWebProxy stylesheets. * * @author Sarah Arnott, sarnott@mun.ca * @version $Revision$ */ public class StylesheetUtils { /** * Returns the absolute uri calculated from the base and file parameters... * Returns an empty string when the base does not contain the correct * protocol (ie. <something>://<something>). */ public static String getAbsURI (String base, String file) { String uri = ""; if (file.startsWith("/")) { int i = base.indexOf(": if (i != -1) { int first = base.indexOf("/", i+3); uri = base.substring(0, first).concat(file); } } else { int last = base.lastIndexOf("/"); uri = base.substring(0, last+1).concat(file); } return uri; } /** * Returns the absolute URI without any '/../'. Some browsers and web * servers do not handle these URIs correctly. * @param uri the absolute URI generated from the input source document */ private static String removeUpDirs (String uri) { if ( uri.indexOf("/../") != -1 ) { String begin; String end; while (uri.indexOf("/../") != -1) { end = uri.substring(uri.indexOf("/../")+4); begin = uri.substring(0, uri.indexOf("/../")); begin = uri.substring(0, begin.lastIndexOf("/")+1); uri = begin.concat(end); } return uri; } else { return uri; } } }
package org.jfree.chart.axis; import java.io.Serializable; import java.text.DateFormat; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import org.jfree.chart.util.ParamChecks; /** * A formatter that formats dates to show the year and quarter (for example, * '2004 IV' for the last quarter of 2004. */ public class QuarterDateFormat extends DateFormat implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -6738465248529797176L; /** Symbols for regular quarters. */ public static final String[] REGULAR_QUARTERS = new String[] {"1", "2", "3", "4"}; /** Symbols for roman numbered quarters. */ public static final String[] ROMAN_QUARTERS = new String[] {"I", "II", "III", "IV"}; /** * Symbols for greek numbered quarters. * * @since 1.0.6 */ public static final String[] GREEK_QUARTERS = new String[] {"\u0391", "\u0392", "\u0393", "\u0394"}; /** The strings. */ private String[] quarters = REGULAR_QUARTERS; /** A flag that controls whether the quarter or the year goes first. */ private boolean quarterFirst; /** * Creates a new instance for the default time zone. */ public QuarterDateFormat() { this(TimeZone.getDefault()); } /** * Creates a new instance for the specified time zone. * * @param zone the time zone (<code>null</code> not permitted). */ public QuarterDateFormat(TimeZone zone) { this(zone, REGULAR_QUARTERS); } /** * Creates a new instance for the specified time zone. * * @param zone the time zone (<code>null</code> not permitted). * @param quarterSymbols the quarter symbols. */ public QuarterDateFormat(TimeZone zone, String[] quarterSymbols) { this(zone, quarterSymbols, false); } /** * Creates a new instance for the specified time zone. * * @param zone the time zone (<code>null</code> not permitted). * @param quarterSymbols the quarter symbols. * @param quarterFirst a flag that controls whether the quarter or the * year is displayed first. * * @since 1.0.6 */ public QuarterDateFormat(TimeZone zone, String[] quarterSymbols, boolean quarterFirst) { ParamChecks.nullNotPermitted(zone, "zone"); this.calendar = new GregorianCalendar(zone); this.quarters = quarterSymbols; this.quarterFirst = quarterFirst; // the following is never used, but it seems that DateFormat requires // it to be non-null. It isn't well covered in the spec, refer to // bug parade 5061189 for more info. this.numberFormat = NumberFormat.getNumberInstance(); } /** * Formats the given date. * * @param date the date. * @param toAppendTo the string buffer. * @param fieldPosition the field position. * * @return The formatted date. */ public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { this.calendar.setTime(date); int year = this.calendar.get(Calendar.YEAR); int month = this.calendar.get(Calendar.MONTH); int quarter = month / 3; if (this.quarterFirst) { toAppendTo.append(this.quarters[quarter]); toAppendTo.append(" "); toAppendTo.append(year); } else { toAppendTo.append(year); toAppendTo.append(" "); toAppendTo.append(this.quarters[quarter]); } return toAppendTo; } /** * Parses the given string (not implemented). * * @param source the date string. * @param pos the parse position. * * @return <code>null</code>, as this method has not been implemented. */ public Date parse(String source, ParsePosition pos) { return null; } /** * Tests this formatter for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof QuarterDateFormat)) { return false; } QuarterDateFormat that = (QuarterDateFormat) obj; if (!Arrays.equals(this.quarters, that.quarters)) { return false; } if (this.quarterFirst != that.quarterFirst) { return false; } return super.equals(obj); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jma; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.dom4j.Element; import org.dom4j.DocumentHelper; import java.io.FileWriter; import java.io.IOException; import java.util.TreeMap; import java.util.Collection; import java.util.Iterator; /** * * @author jun */ public class StatisticManager { //private static final String WEB_TEST_PATH = "/home/wisenut/tomcat/public_html/jma-test/jma/bin/web_test/"; /** the web test path containing script and data files */ //private static final String WEB_TEST_PATH = "/home/jun.jiang/gitorious/ijma/bin/web_test/"; /** the web test path containing script and data files */ private static final String WEB_TEST_PATH = "/home/jun/gitorious/ijma/ijma/bin/web_test/"; /** the web test path containing script and data files */ //private static final String WEB_TEST_PATH = "/home/vernkin/projects/jma/bin/web_test/"; public static final String DB_PATH = WEB_TEST_PATH + "db/"; /** the path of data files */ public static final String SCRIPT_FILE_PATH = WEB_TEST_PATH + "go_jma.sh"; /** the path of script file */ public static final String DIFF_FILE_NAME = "diff.xml"; /** the name of the difference file */ private final String DB_FILE_NAME = "db.xml"; /** the file name of the database file */ private static StatisticManager instance_ = new StatisticManager(); /** the only instance */ private TreeMap map_ = new TreeMap(); /** the map stores each statistic record */ /** * Constructor. */ private StatisticManager() { } /** * Get the instance. * @return the only instance. */ public static StatisticManager getInstance() { return instance_; } /** * Load data from file. */ public void load() { System.out.println(new java.util.Date()); System.out.println("StatisticManager.load()"); SAXReader reader = new SAXReader(); Document dbDoc; try { dbDoc = reader.read(DB_PATH + DB_FILE_NAME); } catch(DocumentException e) { System.err.println(new java.util.Date()); System.out.println("StatisticManager.load(): " + DB_PATH + DB_FILE_NAME + " not exists, just create it."); // no such file exists, just create it with the root node. dbDoc = DocumentHelper.createDocument(); dbDoc.addElement("Collection"); } //System.out.println(dbDoc.asXML()); Element dbRoot = dbDoc.getRootElement(); // read xml content into map_ // iterate through child elements of root for (Iterator i = dbRoot.elementIterator("Record"); i.hasNext();) { Element recordElement = (Element) i.next(); Integer id = new Integer(recordElement.elementText("ID")); StatisticRecord statRecord = new StatisticRecord(); // read statistic values from diff Document diffDoc; String diffFile = DB_PATH + id + "/" + DIFF_FILE_NAME; try { diffDoc = reader.read(diffFile); } catch (DocumentException e) { // no such file exists, just ignore this record System.err.println(new java.util.Date()); System.err.println("StatisticManager.load(): error in reading file: " + diffFile); continue; } statRecord.setFromDocument(diffDoc); map_.put(id, statRecord); } System.out.println("records number: " + map_.size()); System.out.println(); } /** * Save data to file. */ synchronized public void save() throws IOException { System.out.println(new java.util.Date()); System.out.println("StatisticManager.save()"); // create document from map_ Document dbDoc = DocumentHelper.createDocument(); Element dbRoot = dbDoc.addElement("Collection"); Collection c = map_.values(); Iterator iter = c.iterator(); while(iter.hasNext()) { StatisticRecord statRecord = (StatisticRecord) iter.next(); Element recordElement = dbRoot.addElement("Record"); recordElement.addElement("ID").addText(Integer.toString(statRecord.getID())); } // write document to file FileWriter fwriter = new FileWriter(DB_PATH + DB_FILE_NAME); dbDoc.write(fwriter); fwriter.close(); System.out.println("records number: " + map_.size()); System.out.println(); } /** * Get record according to its ID value. * @param id the ID value * @return the record reference. */ public StatisticRecord getRecord(int id) { return (StatisticRecord) map_.get(new Integer(id)); } /** * Returns true if this ID exists. * @param id the ID value * @return true for ID exists, false for not exists. */ public boolean hasRecord(int id) { return map_.containsKey(new Integer(id)); } /** * Get the collection of all records. * @return the records collection. */ public Collection getTotalRecords() { return map_.values(); } /** * Create an empty record with new ID. * @return the new record created. */ synchronized public StatisticRecord createNewRecord() { int id = map_.isEmpty() ? 0 : ((Integer) map_.lastKey()).intValue(); ++id; StatisticRecord statRecord = new StatisticRecord(id); map_.put(new Integer(id), statRecord); return statRecord; } /** * Remove a record according to its ID value. * @param id the ID value */ synchronized public void removeRecord(int id) { map_.remove(new Integer(id)); } }
package org.orbeon.oxf.xforms.function; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.xforms.XFormsModel; import org.orbeon.oxf.xforms.event.events.XFormsComputeExceptionEvent; import org.orbeon.oxf.xforms.xbl.XBLContainer; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.saxon.expr.XPathContext; import org.orbeon.saxon.om.Item; import org.orbeon.saxon.trans.XPathException; import org.orbeon.saxon.value.Int64Value; /** * XForms index() function. * * 7.8.5 The index() Function */ public class Index extends XFormsFunction { public Item evaluateItem(XPathContext xpathContext) throws XPathException { final String repeatId = argument[0].evaluateAsString(xpathContext).toString(); return findIndexForRepeatId(xpathContext, repeatId); } protected Item findIndexForRepeatId(XPathContext xpathContext, String repeatStaticId) { final int index = getXBLContainer(xpathContext).getRepeatIndex(getSourceEffectiveId(xpathContext), repeatStaticId); if (index == -1) { // Throw runtime exception final String message = "Function index uses repeat id '" + repeatStaticId + "' which is not in scope"; throw new ValidationException(message, new LocationData(getSystemId(), getLineNumber(), getColumnNumber())); } else { // Return value found return new Int64Value(index); } } }
package chronontology; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class ChronOntology { public static final String WELT_URI = "https://gazetteer.dainst.org/place/2042600"; public static final String[] TYPES = {"spatiallyPartOfRegion", "isNamedAfter", "hasCoreArea"}; public static final String GAZETTEER_HOST = "https://gazetteer.dainst.org"; public static final String GAZETTEER_DATA_INTERFACE = "doc"; public static final String GAZETTEER_RESOURCE_INTERFACE = "place"; public static JSONArray getGeoJSON(String id) throws Exception { // init output JSONArray spatialData = new JSONArray(); // get data from chronontology JSONObject data = null; JSONObject resource = null; String url = id = "http://chronontology.dainst.org/data/period/" + id; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Accept", "application/json"); if (con.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // parse data data = (JSONObject) new JSONParser().parse(response.toString()); resource = (JSONObject) data.get("resource"); for (String item : TYPES) { JSONArray spatial = (JSONArray) resource.get(item); if (spatial != null) { JSONArray spatialHTTPS = new JSONArray(); for (Object element : spatial) { String tmp = element.toString().replace("http: spatialHTTPS.add(tmp); } for (Object element : spatialHTTPS) { URL daiURL = new URL(GAZETTEER_HOST + "/" + GAZETTEER_DATA_INTERFACE + "/" + element.toString().replace(GAZETTEER_HOST + "/" + GAZETTEER_RESOURCE_INTERFACE + "/", "") + ".geojson"); HttpURLConnection con2 = (HttpURLConnection) daiURL.openConnection(); con2.setRequestMethod("GET"); con2.setRequestProperty("Accept", "application/json"); if (con2.getResponseCode() < 400) { BufferedReader in2 = new BufferedReader(new InputStreamReader(con2.getInputStream(), "UTF-8")); String inputLine2; StringBuilder response2 = new StringBuilder(); while ((inputLine2 = in2.readLine()) != null) { response2.append(inputLine2); } in2.close(); // parse data JSONObject dataDAI = (JSONObject) new JSONParser().parse(response2.toString()); JSONObject propertiesDAI = (JSONObject) dataDAI.get("properties"); JSONObject prefName = (JSONObject) propertiesDAI.get("prefName"); String parentURLStr = (String) propertiesDAI.get("parent"); JSONObject geometryDAI = (JSONObject) dataDAI.get("geometry"); JSONArray geometriesDAI = (JSONArray) geometryDAI.get("geometries"); JSONObject parentGeometry = new JSONObject(); while (geometriesDAI.isEmpty()) { // of geometry is empty get geometry from parent and loop it String parentURLStrOrigin = parentURLStr; // if URI is "Welt" quit loop if (parentURLStrOrigin.equals(WELT_URI)) { // set spatialData to length zero if uri is "Welt" spatialData = new JSONArray(); break; } parentURLStr = parentURLStr.replace("/" + GAZETTEER_RESOURCE_INTERFACE + "/", "/" + GAZETTEER_DATA_INTERFACE + "/"); parentURLStr += ".geojson"; URL parentURL = new URL(parentURLStr); HttpURLConnection con3 = (HttpURLConnection) parentURL.openConnection(); con3.setRequestMethod("GET"); con3.setRequestProperty("Accept", "application/json"); if (con3.getResponseCode() < 400) { BufferedReader in3 = new BufferedReader(new InputStreamReader(con3.getInputStream(), "UTF-8")); String inputLine3; StringBuilder response3 = new StringBuilder(); while ((inputLine3 = in3.readLine()) != null) { response3.append(inputLine3); } in3.close(); // parse data JSONObject dataDAIparent = (JSONObject) new JSONParser().parse(response3.toString()); JSONObject geometryDAIparent = (JSONObject) dataDAIparent.get("geometry"); JSONArray geometriesDAIparent = (JSONArray) geometryDAIparent.get("geometries"); JSONObject propertiesDAIparent = (JSONObject) dataDAIparent.get("properties"); JSONObject prefNameParent = (JSONObject) propertiesDAIparent.get("prefName"); String prefNameTitleParent = (String) prefNameParent.get("title"); parentURLStr = (String) propertiesDAIparent.get("parent"); if (geometriesDAIparent.size() > 0) { parentGeometry.put("uri", parentURLStrOrigin); String[] idSplit = parentURLStrOrigin.split("/"); parentGeometry.put("id", idSplit[idSplit.length - 1]); parentGeometry.put("name", prefNameTitleParent); geometriesDAI = geometriesDAIparent; } } } // create output geojson JSONObject feature = new JSONObject(); feature.put("type", "Feature"); // add GeoJSON-T see https://github.com/kgeographer/geojson-t#adding-time JSONObject properties = new JSONObject(); properties.put("chronontology", data); properties.put("name", (String) prefName.get("title")); properties.put("relation", item); properties.put("uri", (String) dataDAI.get("id")); String idStr = (String) dataDAI.get("id"); String[] idSplit = idStr.split("/"); properties.put("id", idSplit[idSplit.length - 1]); if (!parentGeometry.isEmpty()) { properties.put("parentGeometry", parentGeometry); } feature.put("properties", properties); for (Object geom : geometriesDAI) { JSONObject geomEntry = (JSONObject) geom; if (geomEntry.get("type").equals("MultiPolygon")) { feature.put("geometry", geomEntry); } else if (geomEntry.get("type").equals("Point")) { feature.put("geometry", geomEntry); } } if (geometriesDAI.isEmpty()) { BufferedReader reader = new BufferedReader(new FileReader(ChronOntology.class.getClassLoader().getResource("world.json").getFile())); String line; String json = ""; while ((line = reader.readLine()) != null) { json += line; } JSONObject dataWORLD = (JSONObject) new JSONParser().parse(json.toString()); JSONArray featureWorldArray = (JSONArray) dataWORLD.get("features"); JSONObject featureWorld = (JSONObject) featureWorldArray.get(0); feature.put("geometry", featureWorld.get("geometry")); JSONObject propertiesWorld = (JSONObject) feature.get("properties"); propertiesWorld.remove("parentGeometry"); JSONObject parentGeometryWorld = new JSONObject(); parentGeometryWorld.put("uri", "https://gazetteer.dainst.org/place/2042600"); parentGeometryWorld.put("id", "2042600"); parentGeometryWorld.put("name", "Welt"); propertiesWorld.put("parentGeometry", parentGeometryWorld); } spatialData.add(feature); } } } } } // if no 200 OK available if (con.getResponseCode() > 200) { spatialData = new JSONArray(); return spatialData; } // if no geom available if (spatialData.isEmpty()) { spatialData = new JSONArray(); return spatialData; } return spatialData; } public static JSONArray getGeoJSONDummy(boolean multi) throws Exception { JSONArray spatialData = new JSONArray(); //feature 1 JSONObject feature1 = new JSONObject(); feature1.put("type", "Feature"); JSONParser parser = new JSONParser(); JSONObject geom1 = (JSONObject) parser.parse("{\"type\":\"Polygon\",\"coordinates\":[[[9.921906,54.983104],[9.93958,54.596642],[10.950112,54.363607],[10.939467,54.008693],[11.956252,54.196486],[12.51844,54.470371],[13.647467,54.075511],[14.119686,53.757029],[14.353315,53.248171],[14.074521,52.981263],[14.4376,52.62485],[14.685026,52.089947],[14.607098,51.745188],[15.016996,51.106674],[14.570718,51.002339],[14.307013,51.117268],[14.056228,50.926918],[13.338132,50.733234],[12.966837,50.484076],[12.240111,50.266338],[12.415191,49.969121],[12.521024,49.547415],[13.031329,49.307068],[13.595946,48.877172],[13.243357,48.416115],[12.884103,48.289146],[13.025851,47.637584],[12.932627,47.467646],[12.62076,47.672388],[12.141357,47.703083],[11.426414,47.523766],[10.544504,47.566399],[10.402084,47.302488],[9.896068,47.580197],[9.594226,47.525058],[8.522612,47.830828],[8.317301,47.61358],[7.466759,47.620582],[7.593676,48.333019],[8.099279,49.017784],[6.65823,49.201958],[6.18632,49.463803],[6.242751,49.902226],[6.043073,50.128052],[6.156658,50.803721],[5.988658,51.851616],[6.589397,51.852029],[6.84287,52.22844],[7.092053,53.144043],[6.90514,53.482162],[7.100425,53.693932],[7.936239,53.748296],[8.121706,53.527792],[8.800734,54.020786],[8.572118,54.395646],[8.526229,54.962744],[9.282049,54.830865],[9.921906,54.983104]]]}"); feature1.put("geometry", geom1); JSONObject properties1 = new JSONObject(); properties1.put("periodid", "xyz"); JSONObject names1 = new JSONObject(); JSONArray en1 = new JSONArray(); en1.add("roman"); names1.put("en", en1); JSONArray de1 = new JSONArray(); de1.add("römisch"); de1.add("Römisch"); names1.put("de", de1); properties1.put("names", names1); properties1.put("relation", "hasCoreArea"); properties1.put("@id", "https://gazetteer.dainst.org/place/abc"); properties1.put("chronontology", new JSONObject()); feature1.put("properties", properties1); spatialData.add(feature1); if (multi) { //feature 1 JSONObject feature2 = new JSONObject(); feature2.put("type", "Feature"); JSONParser parser2 = new JSONParser(); JSONObject geom2 = (JSONObject) parser2.parse("{\"type\":\"Polygon\",\"coordinates\":[[[-9.034818,41.880571],[-8.984433,42.592775],[-9.392884,43.026625],[-7.97819,43.748338],[-6.754492,43.567909],[-5.411886,43.57424],[-4.347843,43.403449],[-3.517532,43.455901],[-1.901351,43.422802],[-1.502771,43.034014],[0.338047,42.579546],[0.701591,42.795734],[1.826793,42.343385],[2.985999,42.473015],[3.039484,41.89212],[2.091842,41.226089],[0.810525,41.014732],[0.721331,40.678318],[0.106692,40.123934],[-0.278711,39.309978],[0.111291,38.738514],[-0.467124,38.292366],[-0.683389,37.642354],[-1.438382,37.443064],[-2.146453,36.674144],[-3.415781,36.6589],[-4.368901,36.677839],[-4.995219,36.324708],[-5.37716,35.94685],[-5.866432,36.029817],[-6.236694,36.367677],[-6.520191,36.942913],[-7.453726,37.097788],[-7.537105,37.428904],[-7.166508,37.803894],[-7.029281,38.075764],[-7.374092,38.373059],[-7.098037,39.030073],[-7.498632,39.629571],[-7.066592,39.711892],[-7.026413,40.184524],[-6.86402,40.330872],[-6.851127,41.111083],[-6.389088,41.381815],[-6.668606,41.883387],[-7.251309,41.918346],[-7.422513,41.792075],[-8.013175,41.790886],[-8.263857,42.280469],[-8.671946,42.134689],[-9.034818,41.880571]]]}"); feature2.put("geometry", geom2); JSONObject properties2 = new JSONObject(); properties2.put("periodid", "xyz"); JSONObject names2 = new JSONObject(); JSONArray en2 = new JSONArray(); en2.add("freek"); names1.put("en", en2); JSONArray de2 = new JSONArray(); de2.add("griechisch"); de2.add("Griechisch"); names2.put("de", de1); properties2.put("names", names1); properties2.put("relation", "spatiallyLocatedIn"); properties2.put("@id", "https://gazetteer.dainst.org/place/def"); properties2.put("chronontology", new JSONObject()); feature2.put("properties", properties2); spatialData.add(feature2); } return spatialData; } }
package jp.ac.ynu.pl2017.gg.reversi.gui; import java.awt.CardLayout; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.WindowConstants; import javazoom.jl.player.advanced.jlap; import jp.ac.ynu.pl2017.gg.reversi.ai.BaseAI; import jp.ac.ynu.pl2017.gg.reversi.ai.OnlineDummyAI; import jp.ac.ynu.pl2017.gg.reversi.util.ClientConnection; import jp.ac.ynu.pl2017.gg.reversi.util.FinishListenedThread; import jp.ac.ynu.pl2017.gg.reversi.util.User; public class MainFrame extends JFrame implements TitlePanel.Transition { private static final long serialVersionUID = 248580253941254005L; public static final int panelW = 854; public static final int panelH = 480; private CardLayout layout; private TitlePanel titleCard; private OfflinePlayPanel offlineCard; private User userData; private boolean login = false; public MainFrame() { super(); setTitle("Reversi × Treasure"); /*getContentPane().*/setPreferredSize(new Dimension(panelW, panelH)); setResizable(false); pack(); userData = new User(); userData.setUserName("6s"); userData.setIcon(0); userData.setBackground(0); layout = new CardLayout(); setLayout(layout); BufferedImage lBufferedImage = null; try { InputStream lInputStream = getClass().getClassLoader().getResourceAsStream("titleBack.png"); lBufferedImage = ImageIO.read(lInputStream); } catch (IOException e) { e.printStackTrace(); } titleCard = new TitlePanel(this, lBufferedImage); offlineCard = new OfflinePlayPanel(this); /* add(titleCard, TITLE); add(offlineCard, OFFLINE); add(onlineCard, ONLINE); add(settingsCard, SETTINGS); */ setContentPane(titleCard); setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); showLoginDialog(); } @Override public void changeOfflinePlayPanel() { setContentPane(offlineCard); validate(); } @Override public void changeOnlinePlayPanel() { if (!isLogin()) { showLoginDialog(); if (!isLogin()) { return; } } showRoomSearchDialog(); } @Override public void showRoomSearchDialog() { JDialog lDialog = new JDialog(); lDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); lDialog.setSize(400, 150); lDialog.setModalityType(ModalityType.APPLICATION_MODAL); lDialog.setResizable(false); JPanel lDPanel = (JPanel) lDialog.getContentPane(); lDPanel.setLayout(new FlowLayout()); JLabel lLabel = new JLabel("ID."); lDPanel.add(lLabel); JTextField lOpponentNameField = new JTextField(30); lDPanel.add(lOpponentNameField); JButton lOKButton = new JButton("OK"); lOKButton.addActionListener(e -> {lDialog.dispose(); makeMatch(lOpponentNameField.getText());}); lDPanel.add(lOKButton); JButton lRMButton = new JButton(""); lRMButton.addActionListener(e -> {lDialog.dispose(); makeMatch(""); lDialog.dispose();}); lDPanel.add(lRMButton); lDialog.setVisible(true); } private void makeMatch(String pON) { JDialog lDialog = new JDialog(); lDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // lDialog.setModalityType(ModalityType.APPLICATION_MODAL); lDialog.setResizable(false); lDialog.setSize(400, 100); JPanel lDPanel = (JPanel) lDialog.getContentPane(); lDPanel.setLayout(new FlowLayout()); JLabel lLabel = new JLabel(""); lDPanel.add(lLabel); JButton lOKButton = new JButton(""); lOKButton.addActionListener(e -> {ClientConnection.cansel(); lDialog.dispose();}); lDPanel.add(lOKButton); new FinishListenedThread(new FinishListenedThread.ThreadFinishListener() { @Override public void onThreadFinish(Object pCallbackParam) { // rthread.interrupt(); lDialog.dispose(); Object eData = pCallbackParam.toString(); if (eData instanceof Object[]) { System.err.println("MATCH FOUND"); changePlayPanel(OnlineDummyAI.class, 0, (String)((Object[])eData)[0], userData.getIcon(), (int)((Object[])eData)[1], userData.getBackground()); } else { JOptionPane.showMessageDialog(MainFrame.this, "", "", JOptionPane.ERROR_MESSAGE); } } }) { @Override public Object doRun() { // rthread.start(); System.err.println("MATCH START"); String data; if (pON.isEmpty()) { data = ClientConnection.randomMatch(); } else { data = ClientConnection.match(pON); } int icon = ClientConnection.getUserData(data).getIcon(); return new Object[]{data, icon}; } }.start(); lDialog.setVisible(true); } @Override public void changeSettingsPanel() { setContentPane(new SettingsPanel(this)); validate(); } @Override public void returnTitlePanel() { setContentPane(titleCard); validate(); } public static void main(String[] args) { ClientConnection.init(); new MainFrame(); } @Override public void changePlayPanel(Class<? extends BaseAI> pAi, int pDifficulty, String pOpponentName, int pPIcon, int pOIcon, int pImage) { BufferedImage bufferedImage = null; try { InputStream lInputStream = getClass().getClassLoader().getResourceAsStream("background/back"+(pImage+1)+".png"); bufferedImage = ImageIO.read(lInputStream); } catch (IOException e) { } setContentPane(new PlayPanel(this, pAi, pDifficulty, pOpponentName, pPIcon, pOIcon, bufferedImage)); validate(); } @Override public void changePlayPanel(Class<? extends BaseAI> pAi, int pDifficulty, String pOpponentName, int pPIcon, int pOIcon, Image pImage) { setContentPane(new PlayPanel(this, pAi, pDifficulty, pOpponentName, pPIcon, pOIcon, pImage)); validate(); } @Override public void showLoginDialog() { new LoginDialog(this); } @Override public boolean isLogin() { // TODO Debug return true; // return login; } private class LoginDialog extends JDialog { MainFrame mainFrame; private LoginDialog(Frame owner) { super(owner); mainFrame = (MainFrame) owner; setTitle(""); int width = 380; int height = 150; setSize(width, height); Dimension pSize = mainFrame.getSize(); setLocation((int)(pSize.getWidth() - width) / 2, (int)(pSize.getHeight() - height) / 2); setModal(true); JLabel userLabel = new JLabel(""); JTextField userInput = new JTextField(14); JLabel passLabel = new JLabel(""); JPasswordField passInput = new JPasswordField(14); JPanel inputPanel = new JPanel(); userInput.setHorizontalAlignment(JTextField.CENTER); passInput.setHorizontalAlignment(JPasswordField.CENTER); inputPanel.setLayout(new GridLayout(2, 2)); inputPanel.add(userLabel); inputPanel.add(userInput); inputPanel.add(passLabel); inputPanel.add(passInput); JButton loginButton = new JButton("OK"); JButton createButton = new JButton(""); loginButton.addActionListener(e -> { login = ClientConnection.login(userInput.getText(), new String(passInput.getPassword())); if (!login) { JOptionPane.showMessageDialog(this, "", "", JOptionPane.ERROR_MESSAGE); } else { // TODO // ClientConnection.getUserData(); } dispose(); }); createButton.addActionListener(e -> { login = ClientConnection.createUser(userInput.getText(), new String(passInput.getPassword())); if (!login) { JOptionPane.showMessageDialog(this, "", "", JOptionPane.ERROR_MESSAGE); } else { // TODO // ClientConnection.getUserData(); } dispose(); }); setLayout(new FlowLayout()); add(inputPanel); add(loginButton); add(createButton); setVisible(true); setDefaultCloseOperation(WindowConstants .DISPOSE_ON_CLOSE); } } @Override public User getUserData() { return userData; } }
package swift.application.swiftdoc; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import swift.client.AbstractObjectUpdatesListener; import swift.client.SwiftImpl; import swift.crdt.CRDTIdentifier; import swift.crdt.SequenceTxnLocal; import swift.crdt.interfaces.CachePolicy; import swift.crdt.interfaces.IsolationLevel; import swift.crdt.interfaces.TxnHandle; import swift.crdt.interfaces.TxnLocalCRDT; import swift.dc.DCConstants; import swift.dc.DCSequencerServer; import swift.dc.DCServer; import sys.Sys; import sys.scheduler.PeriodicTask; import sys.utils.Threading; /** * * @author smduarte, annettebieniusa * */ public class SwiftDoc { private static String sequencerName = "localhost"; private static String dcName = "localhost"; static int iterations = 10; static IsolationLevel isolationLevel = IsolationLevel.REPEATABLE_READS; static CachePolicy cachePolicy = CachePolicy.CACHED; static boolean notifications = true; static CRDTIdentifier j1 = new CRDTIdentifier("doc", "1"); static CRDTIdentifier j2 = new CRDTIdentifier("doc", "2"); public static void main(String[] args) { System.out.println("SwiftDoc start!"); // start sequencer server DCSequencerServer.main(new String[]{"-name", sequencerName}); // start DC server DCServer.main(new String[]{dcName}); Threading.newThread("client2", true, new Runnable() { public void run() { Sys.init(); SwiftImpl swift1 = SwiftImpl.newInstance(dcName, DCConstants.SURROGATE_PORT); SwiftImpl swift2 = SwiftImpl.newInstance(dcName, DCConstants.SURROGATE_PORT); runClient1(swift1, swift2); } }).start(); Threading.sleep(1000); Threading.newThread("client2", true, new Runnable() { public void run() { Sys.init(); SwiftImpl swift1 = SwiftImpl.newInstance(dcName, DCConstants.SURROGATE_PORT); SwiftImpl swift2 = SwiftImpl.newInstance(dcName, DCConstants.SURROGATE_PORT); runClient2(swift1, swift2); } }).start(); } static void runClient1(SwiftImpl swift1, SwiftImpl swift2) { client1code(swift1, swift2); } static void runClient2(SwiftImpl swift1, SwiftImpl swift2) { client2code(swift1, swift2); } static void client1code(final SwiftImpl swift1, final SwiftImpl swift2) { try { final AtomicBoolean done = new AtomicBoolean(false); final Map<Long, TextLine> samples = new HashMap<Long, TextLine>(); Threading.newThread(true, new Runnable() { public void run() { try { for (int k = 0; !done.get(); k++) { final Object barrier = new Object(); final TxnHandle handle = swift2.beginTxn(isolationLevel, k == 0 ? CachePolicy.MOST_RECENT : CachePolicy.CACHED, true); SequenceTxnLocal<TextLine> doc = handle.get(j2, true, swift.crdt.SequenceVersioned.class, new AbstractObjectUpdatesListener() { public void onObjectUpdate(TxnHandle txn, CRDTIdentifier id, TxnLocalCRDT<?> previousValue) { Threading.synchronizedNotifyAllOn(barrier); } }); Threading.synchronizedWaitOn(barrier, 5000); // System.err.println("Triggered Reader get():" + // doc.getValue()); for (TextLine i : doc.getValue()) { if (!samples.containsKey(i.serial())) { samples.put(i.serial(), i); } } handle.commit(); } } catch (Exception e) { e.printStackTrace(); } } }).start(); SwiftDocPatchReplay<TextLine> player = new SwiftDocPatchReplay<TextLine>(); player.parseFiles(new SwiftDocOps<TextLine>() { TxnHandle handle = null; SequenceTxnLocal<TextLine> doc = null; @Override public void begin() { try { handle = swift1.beginTxn(isolationLevel, cachePolicy, false); doc = handle.get(j1, true, swift.crdt.SequenceVersioned.class, null); } catch (Throwable e) { e.printStackTrace(); System.exit(0); } } public TextLine remove(int pos) { return doc.removeAt(pos); } @Override public TextLine get(int pos) { return doc.getValue().get(pos); } @Override public void add(int pos, TextLine atom) { doc.insertAt(pos, atom); } @Override public int size() { return doc.size(); } @Override public void commit() { handle.commit(); } @Override public TextLine gen(String s) { return new TextLine(s); } }); done.set(true); for (TextLine i : new ArrayList<TextLine>(samples.values())) System.out.printf("%s\n", i.latency()); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } static void client2code(final SwiftImpl swift1, final SwiftImpl swift2) { try { final Set<Long> serials = new HashSet<Long>(); for (int k = 0;; k++) { final Object barrier = new Object(); final TxnHandle handle = swift1.beginTxn(isolationLevel, k == 0 ? CachePolicy.MOST_RECENT : CachePolicy.CACHED, true); SequenceTxnLocal<TextLine> doc = handle.get(j1, true, swift.crdt.SequenceVersioned.class, new AbstractObjectUpdatesListener() { public void onObjectUpdate(TxnHandle txn, CRDTIdentifier id, TxnLocalCRDT<?> previousValue) { Threading.synchronizedNotifyAllOn(barrier); // System.err.println("previous:" + // previousValue.getValue()); } }); // Wait for the notification, before reading the new value of // the sequence... Threading.synchronizedWaitOn(barrier, 5000); // System.err.println("Triggered Reader get():" + // doc.getValue()); // Determine the new atoms this update brought... final Collection<TextLine> newAtoms = new ArrayList<TextLine>(); for (TextLine i : doc.getValue()) { if (serials.add(i.serial())) { newAtoms.add(i); } } handle.commit(); // Write the atoms into the other sequence to measure RTT... Threading.newThread(true, new Runnable() { public void run() { synchronized (serials) {//wait for the previous transaction to complete... try { final TxnHandle handle = swift2.beginTxn(isolationLevel, CachePolicy.CACHED, true); SequenceTxnLocal<TextLine> doc2 = handle.get(j2, true, swift.crdt.SequenceVersioned.class, null); for (TextLine i : newAtoms) doc2.insertAt(doc2.size(), i); handle.commit(); } catch (Exception x) { x.printStackTrace(); } } } }).start(); } } catch (Exception e) { e.printStackTrace(); } } }
package ch.usi.dag.disl.test.junit; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import ch.usi.dag.disl.exception.ScopeParserException; import ch.usi.dag.disl.scope.Scope; import ch.usi.dag.disl.scope.ScopeImpl; public class ScopeTest { // smoke tests @Test public void testSimple() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.TargetClass.main()"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "main", "()V")); } @Test public void testComplete() throws ScopeParserException { Scope s = new ScopeImpl("java.lang.String my.pkg.TargetClass.main(java.lang.String[])"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "main", "([Ljava.lang.String;)Ljava.lang.String;")); } // method tests @Test public void testMethodWildCard() throws ScopeParserException { Scope s = new ScopeImpl("java.lang.String my.pkg.TargetClass.*main(java.lang.String[])"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "blablablamain", "([Ljava.lang.String;)Ljava.lang.String;")); } @Test public void testMethodAllWildCard() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.TargetClass.*"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "clinit", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "init", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method_init", "()V")); } @Test public void testMethodInitWildCard() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.TargetClass.*init"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "clinit", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "init", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method_init", "()V")); } // return tests @Test public void testReturnAllWildCard() throws ScopeParserException { Scope s = new ScopeImpl("* my.pkg.TargetClass.method"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()I")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()Ljava.lang.String;")); } @Test public void testReturnStartSepStringWildCard() throws ScopeParserException { Scope s = new ScopeImpl("*.String my.pkg.TargetClass.method"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()Ljava.lang.String;")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()Lmy.package.String;")); } @Test public void testReturnStartNoSepStringWildCard() throws ScopeParserException { Scope s = new ScopeImpl("*String my.pkg.TargetClass.method"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()Ljava.lang.String;")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()Lmy.package.String;")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()Lmy.package.BigString;")); } // classname tests /** * FIXED * * input: * java.lang.String main() * * result: * r=null c=java.lang.String m=main p=() * * correct: * r=java.lang.String c=null m=main p=() */ @Test public void testMissingClassName() throws ScopeParserException { Scope s = new ScopeImpl("java.lang.String main()"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "main", "()Ljava.lang.String;")); } /** * FIXED * * input: * java.*.String main() * * result: * r=null c=java.* m=String main p=() * * correct: * r=java.*.String c=null m=main p=() */ @Test public void testMissingClassName2() throws ScopeParserException { Scope s = new ScopeImpl("java.*.String main()"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "main", "()Ljava.lang.String;")); } @Test public void testClassAllPackages() throws ScopeParserException { Scope s = new ScopeImpl("TargetClass.method"); assertTrue(s.toString(), s.matches("TargetClass", "method", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()V")); } @Test public void testClassDefaultPackage() throws ScopeParserException { Scope s = new ScopeImpl("[default].TargetClass.method"); assertTrue(s.toString(), s.matches("TargetClass", "method", "()V")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "()V")); } @Test public void testClassWildCard() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.*TargetClass.method"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()V")); assertTrue(s.toString(), s.matches("my/pkg/pkg/TargetClass", "method", "()V")); assertTrue(s.toString(), s.matches("my/pkg/AnotherTargetClass", "method", "()V")); assertTrue(s.toString(), s.matches("my/pkg/pkg/AnotherTargetClass", "method", "()V")); } // parameter tests @Test public void testParameterAllRandom() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.TargetClass.method(..)"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "(I)V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "([I)V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "([Ljava.lang.String;[I[I[I)V")); } @Test public void testParameterNone() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.TargetClass.method()"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()V")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "(I)V")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "([I)V")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "([Ljava.lang.String;[I[I[I)V")); } /** * FIXED * * details: * (int, int, int, ..) should not match (I)V */ @Test public void testParameterEndRandom() throws ScopeParserException { Scope s = new ScopeImpl("my.pkg.TargetClass.method(int, int, int, ..)"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "(III)V")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "(IIII)V")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "(I)V")); } // complete tests @Test public void testCompleteAllReturnPattern() throws ScopeParserException { Scope s = new ScopeImpl("int *"); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "()I")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "(I)I")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "(Ljava.lang.String)I")); assertTrue(s.toString(), s.matches("TargetClass", "method", "()I")); } @Test public void testCompleteAllAcceptPattern() throws ScopeParserException { Scope s = new ScopeImpl("*(int, int, int)"); assertTrue(s.toString(), s.matches("TargetClass", "method", "(III)I")); assertTrue(s.toString(), s.matches("my/pkg/TargetClass", "method", "(III)V")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "(II)I")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "(IIII)I")); assertFalse(s.toString(), s.matches("my/pkg/TargetClass", "method", "(Ljava.lang.String;)I")); } @Test(expected=ScopeParserException.class) public void cannotCreateEmptyScope() throws ScopeParserException { final Scope s = new ScopeImpl (""); } }
package ch.heig.amt.g4mify.api; import ch.heig.amt.g4mify.model.BadgeType; import ch.heig.amt.g4mify.model.Domain; import ch.heig.amt.g4mify.model.view.badgeType.BadgeTypeSummary; import ch.heig.amt.g4mify.model.view.badgeType.BadgeTypeDetail; import ch.heig.amt.g4mify.repository.BadgeTypesRepository; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.transaction.Transactional; import java.net.URI; import java.util.List; import java.util.stream.Collectors; import static ch.heig.amt.g4mify.model.view.ViewUtils.*; /** * @author ldavid * @created 12/5/16 */ @RestController @RequestMapping("/api/badge-types") @Api(value = "badge-types", description = "Handles CRUD operations on badges-types") public class BadgeTypesApi extends AbstractDomainApi { @Autowired private BadgeTypesRepository badgeTypesRepository; @RequestMapping(method = RequestMethod.GET) @Transactional @ApiOperation(value = "Retrieves all badge-types from the domain", produces = MediaType.APPLICATION_JSON_VALUE) @ApiResponses({ @ApiResponse(code = 200, message = "Ok"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Error retrieving badge-types from the domain")}) public ResponseEntity<List<BadgeTypeSummary>> index(@RequestParam(required = false, defaultValue = "0") long page, @RequestParam(required = false, defaultValue = "50") long pageSize) { Domain domain = getDomain(); List<BadgeTypeSummary> badgeTypes = badgeTypesRepository.findByDomain(domain) .skip(page * pageSize) .limit(pageSize) .map(outputView(BadgeTypeSummary.class)::from) .collect(Collectors.toList()); return ResponseEntity.ok(badgeTypes); } @RequestMapping(method = RequestMethod.POST) @ApiOperation(value = "Creates a new badge-type in the domain", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ApiResponses({ @ApiResponse(code = 201, message = "Created"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Error creating the badge-type in the domain")}) public ResponseEntity<?> create(@RequestBody BadgeTypeDetail body) { Domain domain = getDomain(); BadgeType input = inputView(BadgeType.class) .map("previous", orNull(prevKey -> badgeTypesRepository.findByDomainAndKey(domain, (String) prevKey).orElse(null))) .from(body); input.setDomain(domain); BadgeType badgeType = badgeTypesRepository.save(input); URI uri = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{key}") .buildAndExpand(badgeType.getKey()) .toUri(); return ResponseEntity.created(uri).body(outputView(BadgeTypeDetail.class).map("previous", orNull(prev -> ((BadgeType)prev).getKey())).from(badgeType)); } @RequestMapping(value = "/{key}", method = RequestMethod.GET) @ApiOperation(value = "Retrieves a particular badge-type from the domain", produces = MediaType.APPLICATION_JSON_VALUE) @ApiResponses({ @ApiResponse(code = 200, message = "Ok"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Error retrieving the badge-type from the domain")}) public ResponseEntity<BadgeTypeDetail> show(@PathVariable String key) { return badgeTypesRepository.findByDomainAndKey(getDomain(), key) .filter(this::canAccess) .map(badgeType -> outputView(BadgeTypeDetail.class).map("previous", orNull(prev -> ((BadgeType)prev).getKey())).from(badgeType)) .map(ResponseEntity::ok) .orElseGet(ResponseEntity.status(HttpStatus.NOT_FOUND)::build); } @RequestMapping(path = "/{key}", method = RequestMethod.PUT) @ApiOperation(value = "Updates a particular badge-type from the domain", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ApiResponses({ @ApiResponse(code = 200, message = "Ok"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Error updating the badge-type from the domain")}) public ResponseEntity<BadgeTypeSummary> update(@PathVariable String key, @RequestBody BadgeTypeDetail body) { return badgeTypesRepository.findByDomainAndKey(getDomain(), key) .filter(this::canAccess) .map(badgeType -> { updateView(badgeType) .map("previous", orNull(prevKey -> badgeTypesRepository.findByDomainAndKey(getDomain(), (String) prevKey).orElse(null))) .with(body); return badgeTypesRepository.save(badgeType); }) .map(badgeType -> outputView(BadgeTypeSummary.class).map("previous", orNull(prev -> ((BadgeType)prev).getKey())).from(badgeType)) .map(ResponseEntity::ok) .orElseGet(ResponseEntity.status(HttpStatus.NOT_FOUND)::build); } @RequestMapping(path = "/{key}", method = RequestMethod.DELETE) @ApiOperation(value = "Deletes a particular badge-type from the domain") @ApiResponses({ @ApiResponse(code = 200, message = "Ok"), @ApiResponse(code = 404, message = "Not found"), @ApiResponse(code = 500, message = "Error deleting the badge-type from the domain")}) public ResponseEntity<?> delete(@PathVariable String key) { return badgeTypesRepository.findByDomainAndKey(getDomain(), key) .filter(this::canAccess) .map(badgeType -> { badgeTypesRepository.delete(badgeType); return ResponseEntity.ok().build(); }) .orElseGet(ResponseEntity.status(HttpStatus.NOT_FOUND)::build); } private boolean canAccess(BadgeType badgeType) { return badgeType.getDomain().getId() == getDomain().getId(); } }
package ch.openech.model; import static ch.openech.xml.read.StaxEch.skip; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.minimalj.util.StringUtils; import ch.openech.xml.write.EchNamespaceUtil; public class EchXmlDownload { private final String schemaLocation; private EchXmlDownload() { this.schemaLocation = null; } private EchXmlDownload(String schemaLocation) { this.schemaLocation = schemaLocation; } private void download() { System.out.println("Download: " + schemaLocation); try { URL url = new URL(schemaLocation); String fileName = convert(url); File file = new File(fileName); file.getParentFile().mkdirs(); if (!file.exists()) { try (InputStream stream = url.openStream()) { try (ReadableByteChannel rbc = Channels.newChannel(stream)) { try (FileOutputStream fos = new FileOutputStream(file)) { fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } } } catch (FileNotFoundException f) { System.out.println("Not available: " + schemaLocation); return; } catch (IOException e) { throw new RuntimeException(e); } } try { process(file); } catch (XMLStreamException | IOException e) { throw new RuntimeException(e); } } catch (MalformedURLException e) { throw new RuntimeException(e); } } private String convert(URL url) { StringBuilder s = new StringBuilder("src/main/xml"); String host = url.getHost(); String[] hostParts = host.split("\\."); for (int i = hostParts.length - 1; i >= 0; i if (i == 0 && hostParts[i].equals("www")) { continue; } s.append("/").append(hostParts[i]); } s.append(url.getPath()); return s.toString(); } private void process(File file) throws XMLStreamException, IOException { try (InputStream inputStream = new FileInputStream(file)) { process_(inputStream); } } private void process_(InputStream inputStream) throws XMLStreamException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xml = inputFactory.createXMLEventReader(inputStream); process(xml); } private void process(XMLEventReader xml) throws XMLStreamException { while (true) { XMLEvent event = xml.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String startName = startElement.getName().getLocalPart(); if (startName.equals("schema")) { schema(xml); } else skip(xml); } else if (event.isEndElement() || event.isEndDocument()) { return; } // else skip } } private void schema(XMLEventReader xml) throws XMLStreamException { while (true) { XMLEvent event = xml.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String startName = startElement.getName().getLocalPart(); if (startName.equals("import")) { imprt(startElement); skip(xml); } else { skip(xml); } } else if (event.isEndElement()) { return; } // else skip } } private void imprt(StartElement startElement) throws XMLStreamException { String schemaLocation = startElement.getAttributeByName(new QName("schemaLocation")).getValue(); if (!StringUtils.isEmpty(schemaLocation)) { if (!schemaLocation.contains("/")) { schemaLocation = this.schemaLocation.substring(0, this.schemaLocation.lastIndexOf("/") + 1) + schemaLocation; } new EchXmlDownload(schemaLocation).download(); } } private static void download(int rootNumber, int major, int minor) { String rootNamespaceURI = EchNamespaceUtil.schemaURI(rootNumber, "" + major); EchXmlDownload download = new EchXmlDownload(EchNamespaceUtil.schemaLocation(rootNamespaceURI, "" + minor)); download.download(); } private static void process(InputStream inputStream) throws XMLStreamException { EchXmlDownload download = new EchXmlDownload(); download.process_(inputStream); } public static void main(String... args) throws Exception { // download.download(20, 2, 3); download(20, 3, 0); download(116, 3, 0); download(71, 1, 1); download(72, 1, 0); // download.download(147); // download.download(211, 1, 0); // download.download(21); // download.download(78); // download.download(93); // download.download(101); // download(108); // download.download(129); // download.download(148); // download.download(173); // download.download(196); // download.download(201); process(EchXmlDownload.class.getResourceAsStream("/ch/ech/xmlns/eCH-0211-1-0.xsd")); } }
package chav1961.purelib.basic; import java.awt.Color; import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.w3c.dom.Element; import chav1961.purelib.basic.CharUtils.ArgumentType; import chav1961.purelib.basic.CharUtils.SubstitutionSource; import chav1961.purelib.basic.exceptions.PrintingException; import chav1961.purelib.basic.exceptions.SyntaxException; import chav1961.purelib.basic.interfaces.SyntaxTreeInterface; import chav1961.purelib.basic.intern.UnsafedCharUtils; import chav1961.purelib.basic.intern.UnsafedUtils; import chav1961.purelib.cdb.SyntaxNode; import chav1961.purelib.concurrent.LightWeightRWLockerWrapper; import chav1961.purelib.concurrent.LightWeightRWLockerWrapper.Locker; import chav1961.purelib.enumerations.StylePropertiesSupported; import chav1961.purelib.enumerations.StylePropertiesSupported.ContentType; import chav1961.purelib.streams.JsonStaxParser; import chav1961.purelib.streams.interfaces.JsonStaxParserInterface; import chav1961.purelib.streams.interfaces.JsonStaxParserLexType; public class CSSUtils { private static final char[] AVAILABLE_IN_NAMES = {'-'}; private static final String PROP_ATTR_NAME_HAS_FIXED = "hasFixed"; private static final String PROP_ATTR_NAME_VALUE_TYPE = "valueType"; private static final String PROP_ATTR_NAME_INHERITANCE_AVAILABLE = "inheritanceAvailable"; private static final String PROP_ATTR_NAME_URL_AVAILABLE = "urlAvailable"; private static final String PROP_ATTR_NAME_CHILDREN = "children"; private static final String PROP_ATTR_NAME_FORMAT = "format"; private static final String PROP_ATTR_NAME_PARSER_CLASS = "parserClass"; private static final String PROP_ATTR_NAME_PARSER_METHOD = "parserMethod"; private static final Object[] COLOR_HEX_TEMPLATE = {'#',ArgumentType.hexInt}; private static final char[] COLOR_RGBA = "rgba".toCharArray(); private static final Object[] COLOR_RGBA_TEMPLATE = {COLOR_RGBA,'(',ArgumentType.ordinalInt,',',ArgumentType.ordinalInt,',',ArgumentType.ordinalInt,',',ArgumentType.ordinalInt,')'}; private static final char[] COLOR_RGB = "rgb".toCharArray(); private static final Object[] COLOR_RGB_TEMPLATE = {COLOR_RGB,'(',ArgumentType.ordinalInt,',',ArgumentType.ordinalInt,',',ArgumentType.ordinalInt,')'}; private static final char[] COLOR_HSLA = "hsla".toCharArray(); private static final Object[] COLOR_HSLA_TEMPLATE = {COLOR_HSLA,'(',ArgumentType.ordinalInt,',',ArgumentType.ordinalFloat,'%',',',ArgumentType.ordinalFloat,'%',',',ArgumentType.ordinalFloat,'%',')'}; private static final char[] COLOR_HSL = "hsl".toCharArray(); private static final Object[] COLOR_HSL_TEMPLATE = {COLOR_HSL,'(',ArgumentType.ordinalInt,',',ArgumentType.ordinalFloat,'%',',',ArgumentType.ordinalFloat,'%',')'}; private static final char[] TRANSFORM_ROTATE = "rotate".toCharArray(); private static final char[] TRANSFORM_SCALE = "scale".toCharArray(); private static final char[] TRANSFORM_TRANSLATE = "translate".toCharArray(); private static final SyntaxTreeInterface<StylePropValue<?>[]> KEYWORDS = new AndOrTree<>(); private static final SyntaxTreeInterface<StylePropertiesSupported> STYLES = new AndOrTree<>(); private static final long INHERITED; @FunctionalInterface private interface StyleValueConverter { Object convert(String source) throws SyntaxException; } static { INHERITED = KEYWORDS.placeName("inherited",null); // for (StylePropertiesSupported item : StylePropertiesSupported.values()) { // final ContentType ct; // switch (ct = item.getContentType()) { // case color: // addName(KEYWORDS,item,item.getValues()); // break; // case colorOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case distanceOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case functionOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case integerOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case numberOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case stringOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case timeOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case urlOrKeyword : // addName(KEYWORDS,item,item.getValues()); // break; // case value : // addName(KEYWORDS,item,item.getValues()); // break; // case asIs: // case compoundChoise: // case compoundSequence: // case distance: // case function: // case integer: // case number: // case string: // case subStyle: // case time: // case url: // addName(KEYWORDS,item,item.getValues()); // break; // default: // throw new UnsupportedOperationException("Content type ["+ct+"] is not supported yet"); // STYLES.placeName(item.name(),item); // STYLES.placeName(item.getExternalName(),item); } // name-name // type() // Map<> split(String,inher) // join(EnumMap<>,inher) public interface AggregateAttr { StylePropertiesSupported getType(); StylePropertiesSupported[] getDetails(); Map<StylePropertiesSupported,String> split(String content) throws SyntaxException; Map<StylePropertiesSupported,String> split(String content, SubstitutionSource inherit) throws SyntaxException; String join(Map<StylePropertiesSupported,String> content) throws PrintingException; String join(Map<StylePropertiesSupported,String> content, SubstitutionSource inherit) throws PrintingException; } /* Syntax rules: <record>::=<selectors><properties> <selectors>::=<selectorGroup>[','...] <selectorGroup>::=<subtreeSel>[{'>'|'-->'}<subtreeSel>...] <subtreeSel>::=<standaloneSel>[{'~'|'+'}<standaloneSel>...] <standaloneSel>=<selItem>['&'<selItem>...] <selItem>::={'*'|<name>|'#'<id>|'.'<class>|'::'<pseudoelement>|':'<pseudoclass>|<attrExpr>} <pseudoElement>::=<name> <pseudoClass>::=<name>['('<number>['n']['+'<number>]')'] <attrExpr>::='['<name>[<operator><operValue>]']' <operator>::={'='|'^='|'|='|'*='|'~='|'$='} <operValue>::='"'<any>'"' <properties>::='{'<property>':'<value>[';'...]'}' */ public static Map<String,Properties> parseCSS(final String cssContent) throws SyntaxException, IllegalArgumentException { if (cssContent == null || cssContent.isEmpty()) { throw new IllegalArgumentException("CSS content can't be null or empty string"); } else { final Map<String,Properties> result = new HashMap<>(); parseCSS(cssContent.toCharArray(),0,result); return result; } } public static int parseCSS(final char[] src, final int from, final Map<String,Properties> result) throws SyntaxException, IllegalArgumentException { return parseCSS(src,from,result,new int[2]); } static int parseCSS(final char[] src, int from, final Map<String,Properties> result, final int[] nameRange) throws SyntaxException, IllegalArgumentException { final int len; if (src == null || (len = src.length) == 0) { throw new IllegalArgumentException("CSS content can't be null or empty array"); } else if (from < 0 || from >= len) { throw new IllegalArgumentException("From index ["+from+"] out of range 0.."+(len-1)); } else { final List<CSSLex> lexemas = new ArrayList<>(); final StringBuilder sb = new StringBuilder(); loop: while (from < len) { if ((from = CharUtils.skipBlank(src,from,false)) >= len) { break; } switch (src[from]) { case '/' : if (src[from+1] == '*') { final int start = from; while (src[from] != '\0' && !(src[from] == '*' && src[from+1] == '/')) { from++; } if (src[from] != '\0') { from += 2; } else { throw new SyntaxException(0,start,"Unclosed comment"); } continue loop; } else { throw new SyntaxException(0,from,"Illegal character in the source content"); } case ' from = CharUtils.parseNameExtended(src,from+1,nameRange,AVAILABLE_IN_NAMES); if (nameRange[0] == nameRange[1]) { throw new SyntaxException(0,from,"Missing Id name"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.ID,new String(src,nameRange[0],nameRange[1]-nameRange[0]+1))); if (src[from] == '.' || src[from] == '#' || src[from] == ':' || src[from] == '[') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CONCAT)); } } break; case '.' : from = CharUtils.parseNameExtended(src,from+1,nameRange,AVAILABLE_IN_NAMES); if (nameRange[0] == nameRange[1]) { throw new SyntaxException(0,from,"Missing class name"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CLASS,new String(src,nameRange[0],nameRange[1]-nameRange[0]+1))); if (src[from] == '.' || src[from] == '#' || src[from] == ':' || src[from] == '[') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CONCAT)); } } break; case ':' : from = CharUtils.parseNameExtended(src,from+1,nameRange,AVAILABLE_IN_NAMES); if (nameRange[0] == nameRange[1]) { throw new SyntaxException(0,from,"Missing pseudoclass name"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.PSEUDOCLASS,new String(src,nameRange[0],nameRange[1]-nameRange[0]+1))); if (src[from] == '.' || src[from] == '#' || src[from] == ':' || src[from] == '[') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CONCAT)); } } from++; break; case '@' : from = CharUtils.parseNameExtended(src,from+1,nameRange,AVAILABLE_IN_NAMES); if (nameRange[0] == nameRange[1]) { throw new SyntaxException(0,from,"Missing attribute name"); } else { if (src[nameRange[1]] == '$') { // Has special means in the CSS nameRange[1] from } lexemas.add(new CSSLex(from,CSSLex.CSSLExType.ATTRIBUTE,new String(src,nameRange[0],nameRange[1]-nameRange[0]+1))); } break; case ',' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.DIV)); from++; break; case '[' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPENB)); from++; break; case ']' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CLOSEB)); from++; if (src[from] == '.' || src[from] == '#' || src[from] == ':' || src[from] == '[') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CONCAT)); } break; case '"' : final int start = from; sb.setLength(0); try{from = UnsafedCharUtils.uncheckedParseString(src,from+1,'\"',sb); } catch (IOException e) { throw new SyntaxException(0,from,e.getLocalizedMessage()); } if (from >= src.length || src[from] == '\0') { throw new SyntaxException(0,start,"Unpaired quotes"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.STRING,sb.toString())); } break; case '>' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.SEQUENT)); from++; break; case '+' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.PLUS)); from++; break; case '(' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPEN)); from++; break; case ')' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CLOSE)); from++; if (src[from] == '.' || src[from] == '#' || src[from] == ':' || src[from] == '[') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CONCAT)); } break; case '=' : lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPER,CSSLex.OPER_EQUALS)); from++; break; case '~' : if (src[from+1] != '=') { throw new SyntaxException(0,from,"Unknown lexema"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPER,CSSLex.OPER_CONTAINS_VALUE)); from += 2; } break; case '^' : if (src[from+1] != '=') { throw new SyntaxException(0,from,"Unknown lexema"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPER,CSSLex.OPER_STARTSWITH)); from += 2; } break; case '|' : if (src[from+1] != '=') { throw new SyntaxException(0,from,"Unknown lexema"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPER,CSSLex.OPER_STARTS_OR_EQUALS)); from += 2; } break; case '*' : if (src[from+1] != '=') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.ASTERISK)); from++; } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPER,CSSLex.OPER_CONTAINS)); from += 2; } break; case '$' : if (src[from+1] != '=') { throw new SyntaxException(0,from,"Unknown lexema"); } else { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.OPER,CSSLex.OPER_ENDSWITH)); from += 2; } break; case '{' : final Properties props = new Properties(); from = parseInnerCSS(src,from+1,nameRange,sb,props); lexemas.add(new CSSLex(from,CSSLex.CSSLExType.PROPS,props)); break; case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : from = UnsafedCharUtils.uncheckedParseInt(src,from,nameRange,true); lexemas.add(new CSSLex(from,CSSLex.CSSLExType.NUMBER,nameRange[0])); break; default : if (Character.isJavaIdentifierStart(src[from])) { from = CharUtils.parseName(src,from,nameRange); lexemas.add(new CSSLex(from,CSSLex.CSSLExType.NAME,new String(src,nameRange[0],nameRange[1]-nameRange[0]+1))); if (src[from] == '.' || src[from] == '#' || src[from] == ':' || src[from] == '[') { lexemas.add(new CSSLex(from,CSSLex.CSSLExType.CONCAT)); } } else { throw new SyntaxException(0,from,"Unknown lexema"); } } } lexemas.add(new CSSLex(from,CSSLex.CSSLExType.EOF)); final CSSLex[] lex = lexemas.toArray(new CSSLex[lexemas.size()]); int pos = 0; lexemas.clear(); do {final SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>> node = new SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>>(0,0,CSSSyntaxNode.RECORD,0L,null); pos = buildCSSTree(lex,pos,CSSSyntaxNode.RECORD, node); try{printCSSTree(node,new PrintWriter(System.err)); } catch (IOException e) { e.printStackTrace(); } result.put(convertCSSTree2XPath((SyntaxNode<CSSSyntaxNode, SyntaxNode<CSSSyntaxNode, ?>>) node.children[0]),(Properties)node.cargo); } while (pos < lex.length && lex[pos].type != CSSLex.CSSLExType.EOF); return from; } } public static <T> Map<String,StylePropValue<T>> parseStyle(final String style) throws SyntaxException { if (style == null || style.isEmpty()) { throw new IllegalArgumentException("Style can't be null or empty"); } else { final Properties props = new Properties(); final StringBuilder sb = new StringBuilder(); parseInnerCSS((style+"}").toCharArray(),0,new int[2],sb,props); final Map<String,StylePropValue<T>> result = new HashMap<>(); for (Map.Entry<Object,Object> item : props.entrySet()) { final String key = ((String)item.getKey()); final long id = STYLES.seekName(key); if (id >= 0) { result.put(key,parseStyleProperty(STYLES.getCargo(id),result,(String)item.getValue())); } else { result.put(key,new StylePropValue<T>(ContentType.asIs,null,(T)item.getValue())); } } return result; } } public static <T> StylePropValue<T> parseStyleProperty(final StylePropertiesSupported prop, final Map<String,StylePropValue<T>> props, final String content) throws SyntaxException { if (prop == null) { throw new NullPointerException("Property descriptor can't be null"); } else if (props == null) { throw new NullPointerException("Properties can't be null"); } else if (content == null || content.isEmpty()) { throw new IllegalArgumentException("Content can't be null or empty"); } else { return parseStyleProperty(prop,props,content,0,content.length()); } } public static <T> StylePropValue<T> parseStyleProperty(final StylePropertiesSupported prop, final Map<String,StylePropValue<T>> props, final String content, final int from, final int to) throws SyntaxException { if (prop == null) { throw new NullPointerException("Property descriptor can't be null"); } else if (props == null) { throw new NullPointerException("Properties can't be null"); } else if (content == null || content.isEmpty()) { throw new IllegalArgumentException("Content can't be null or empty"); } else { return parseStyleProperty(prop,props,UnsafedUtils.getStringContent(content),from,to); } } public static <T> StylePropValue<T> parseStyleProperty(final StylePropertiesSupported prop, final Map<String,StylePropValue<T>> props, final char[] content, final int from, final int to) throws SyntaxException { if (prop == null) { throw new NullPointerException("Property descriptor can't be null"); } else if (props == null) { throw new NullPointerException("Properties can't be null"); } else if (content == null || content.length == 0) { throw new IllegalArgumentException("Content can't be null or empty array"); } else if (from < 0 || from >= content.length) { throw new IllegalArgumentException("From position ["+from+"] out of range 0.."+(content.length-1)); } else if (to < 0 || to > content.length) { throw new IllegalArgumentException("To position ["+to+"] out of range 0.."+(content.length)); } else if (to < from) { throw new IllegalArgumentException("To position ["+to+"] is less than from position ["+from+"]"); } else { int end; long id; StylePropValue<T> result; switch (prop.getContentType()) { case asIs : break; case colorOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } } case color : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } return new StylePropValue<T>(prop.getContentType(),prop,(T)asColor(content)); case compoundChoise : // for (String item : prop.getValues().getContent()) { break; case compoundSequence : break; case distanceOrKeyword : if ((result = parseStylePropertyInheritance(prop,props,content,from,to)) !=null) { return result; } case distance : return new StylePropValue<T>(prop.getContentType(),prop,(T)asDistance(new String(content))); case functionOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } case function : break; case integerOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } case integer : final int[] intResult = new int[1]; if ((end = UnsafedCharUtils.uncheckedParseInt(content,from,intResult,true)) != to) { throw new IllegalArgumentException(); } else { return (StylePropValue<T>) new StylePropValue<Integer>(ContentType.integer,prop,intResult[0]); } case numberOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } case number : final float[] floatResult = new float[1]; if ((end = UnsafedCharUtils.uncheckedParseFloat(content,from,floatResult,true)) != to) { throw new IllegalArgumentException(); } else { return (StylePropValue<T>) new StylePropValue<Float>(ContentType.number,prop,floatResult[0]); } case stringOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } case string : return (StylePropValue<T>) new StylePropValue<String>(ContentType.string,prop,new String(content,from,to)); case subStyle : break; case timeOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } case time : break; case urlOrKeyword : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } case url : break; case value : if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } break; default: break; } return null; } } public static <T> StylePropValue<T> parseStylePropertyInheritance(final StylePropertiesSupported prop, final Map<String,StylePropValue<T>> props, final char[] content, final int from, final int to) throws SyntaxException { long id; if ((id = KEYWORDS.seekName(content,from,to)) >= 0) { if (id == INHERITED) { return parseStylePropertyInherited(prop,props,content,from,to); } else { for (StylePropValue<?> item : KEYWORDS.getCargo(id)) { if (item.getProp() == prop) { return (StylePropValue<T>) item; } } } } return null; } private static <T> StylePropValue<T> parseStylePropertyInherited(final StylePropertiesSupported prop, final Map<String,StylePropValue<T>> props, final char[] content, final int from, final int to) throws SyntaxException { for (StylePropertiesSupported parent : StylePropertiesSupported.values()) { if (parent.getContentType() == ContentType.compoundChoise) { // for (String item : parent.getValues().getContent()) { // if (item.equals(prop.name()) || item.equals(prop.getExternalName())) { // final StylePropValue<T> result = parseStyleProperty(parent, props, content, from, to); // if (result == null) { // return null; // else { // return null; } else if (parent.getContentType() == ContentType.compoundSequence) { // for (String item : parent.getValues().getContent()) { // if (item.equals(prop.name()) || item.equals(prop.getExternalName())) { // final StylePropValue<T> result = parseStyleProperty(parent, props, content, from, to); // if (result == null) { // return null; // else { // return null; } } return null; } public interface AttributeParser { String getAttributeName(); void process(final Element element); } public static AttributeParser buildAttributeParser(final Reader parserDescription) throws IOException, SyntaxException { if (parserDescription == null) { throw new NullPointerException("Parser descripion stream can't be null"); } else { try(final JsonStaxParserInterface parser = new JsonStaxParser(parserDescription)) { final Map<String,AttributeParser> collection = new HashMap<>(); for (JsonStaxParserLexType item : parser) { while (item == JsonStaxParserLexType.START_ARRAY) { try(final JsonStaxParserInterface nested = parser.nested()) { buildTopAttributeParsers(parser.nested(),collection); } } } return null; } } } static int parseInnerCSS(final char[] src, final int start, final int[] nameRange, final StringBuilder sb, final Properties props) throws SyntaxException { int from = start-1, begin = start; try{do {from = CharUtils.parseNameExtended(src, CharUtils.skipBlank(src,from+1,false), nameRange, AVAILABLE_IN_NAMES); if (nameRange[0] == nameRange[1]) { throw new SyntaxException(0,from,"Property name is missing"); } final String name = new String(src,nameRange[0],nameRange[1]-nameRange[0]+1); from = CharUtils.skipBlank(src,from,false); if (src[from] != ':') { throw new SyntaxException(0,from,"Colon (:) is missing"); } else { from = CharUtils.skipBlank(src,from+1,false); if (src[from] == '\"') { sb.setLength(0); begin = from; try{from = UnsafedCharUtils.uncheckedParseString(src,from+1,'\"',sb); } catch (IOException exc) { throw new SyntaxException(0,begin,exc.getLocalizedMessage()); } if (from >= src.length) { throw new SyntaxException(0,begin,"Unclosed double quote"); } else { props.setProperty(name,sb.toString()); from = CharUtils.skipBlank(src,from+1,false); } } else { begin = from; while (src[from] != '\0' && src[from] != ';' && src[from] != '}') { from++; } if (src[from] == '\0') { throw new SyntaxException(0,begin,"Unclosed '}'"); } else { while (src[from-1] <= ' ') { // trunk tailed blanks from } props.setProperty(name,new String(src,begin,from-begin)); } } if (src[from = CharUtils.skipBlank(src,from,false)] == ';') { from = CharUtils.skipBlank(src,from+1,false); } } } while (src[from] != '\0' && src[from] != '}'); } catch (IllegalArgumentException exc) { throw new SyntaxException(0,begin,exc.getLocalizedMessage(),exc); } if (src[from] != '}') { throw new SyntaxException(0,begin,"Unclosed '}'"); } else { return from+1; } } private static void buildTopAttributeParsers(final JsonStaxParserInterface parser, final Map<String, AttributeParser> collection) throws SyntaxException, IOException { String name = null; AttributeParser ap = null; for (JsonStaxParserLexType item : parser) { if (item == JsonStaxParserLexType.NAME) { name = parser.name(); } else if (item == JsonStaxParserLexType.START_OBJECT) { try(final JsonStaxParserInterface nested = parser.nested()) { ap = buildTopAttributeParser(parser, collection); } } else { throw new SyntaxException(parser.row(),parser.col(),"Only name of starting object can be here"); } } if (name == null) { throw new SyntaxException(parser.row(),parser.col(),"Attribute name is missing"); } else if (ap == null) { throw new SyntaxException(parser.row(),parser.col(),"Attribute description is missing"); } else { collection.put(name,ap); } } private static AttributeParser buildTopAttributeParser(final JsonStaxParserInterface parser, final Map<String, AttributeParser> collection) throws SyntaxException, IOException { // TODO Auto-generated method stub boolean hasFixed = false, inheritanceAvailable= false, urlAvailable = false; String valType = null, format = null, parserClass = null, parserMethod = null; for (JsonStaxParserLexType item : parser) { if (item == JsonStaxParserLexType.NAME) { final String name = parser.name(); if (parser.next() != JsonStaxParserLexType.NAME) { throw new SyntaxException(parser.row(),parser.col(),"Missing (:)"); } switch (name) { case PROP_ATTR_NAME_HAS_FIXED : if (parser.next() != JsonStaxParserLexType.BOOLEAN_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"Boolean value awaited"); } else { hasFixed = parser.booleanValue(); } break; case PROP_ATTR_NAME_VALUE_TYPE : if (parser.next() != JsonStaxParserLexType.STRING_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"String value awaited"); } else { valType = parser.stringValue(); } break; case PROP_ATTR_NAME_INHERITANCE_AVAILABLE : if (parser.next() != JsonStaxParserLexType.BOOLEAN_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"Boolean value awaited"); } else { inheritanceAvailable = parser.booleanValue(); } break; case PROP_ATTR_NAME_URL_AVAILABLE : if (parser.next() != JsonStaxParserLexType.BOOLEAN_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"Boolean value awaited"); } else { urlAvailable = parser.booleanValue(); } break; case PROP_ATTR_NAME_CHILDREN : if (parser.next() != JsonStaxParserLexType.START_ARRAY) { throw new SyntaxException(parser.row(),parser.col(),"Array awaited"); } else { // urlAvailable = parser.booleanValue(); } break; case PROP_ATTR_NAME_FORMAT : if (parser.next() != JsonStaxParserLexType.STRING_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"String value awaited"); } else { format = parser.stringValue(); } break; case PROP_ATTR_NAME_PARSER_CLASS : if (parser.next() != JsonStaxParserLexType.STRING_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"String value awaited"); } else { parserClass = parser.stringValue(); } break; case PROP_ATTR_NAME_PARSER_METHOD : if (parser.next() != JsonStaxParserLexType.STRING_VALUE) { throw new SyntaxException(parser.row(),parser.col(),"String value awaited"); } else { parserMethod = parser.stringValue(); } break; default : throw new SyntaxException(parser.row(),parser.col(),"Unsupported name ["+name+"] in the descriptor"); } } } return null; } private static int buildCSSTree(final CSSLex[] src, final int start, final CSSSyntaxNode level, final SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>> node) throws SyntaxException { int from = start; switch (level) { case RECORD : from = buildCSSTree(src,from,CSSSyntaxNode.SELECTORS,node); if (src[from].type == CSSLex.CSSLExType.PROPS) { final SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>> subnode = new SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>>(node); node.type = CSSSyntaxNode.RECORD; node.value = 0; node.cargo = src[from].props; node.children = new SyntaxNode[]{subnode}; node.parent = null; from++; } else { throw new SyntaxException(0,src[from].pos,"Properties clause is missing"); } break; case SELECTORS : from = buildCSSTree(src,from,CSSSyntaxNode.SELECTOR_GROUP,node); if (src[from].type == CSSLex.CSSLExType.DIV) { final List<SyntaxNode> orList = new ArrayList<>(); orList.add(new SyntaxNode(node)); do {from = buildCSSTree(src,from,CSSSyntaxNode.SELECTOR_GROUP,node); orList.add(new SyntaxNode(node)); } while (src[from].type == CSSLex.CSSLExType.DIV); node.type = CSSSyntaxNode.SELECTORS; node.children = orList.toArray(new SyntaxNode[orList.size()]); } break; case SELECTOR_GROUP : from = buildCSSTree(src,from,CSSSyntaxNode.SUBTREE_SEL,node); if (src[from].type == CSSLex.CSSLExType.PLUS) { final List<SyntaxNode> orList = new ArrayList<>(); orList.add(new SyntaxNode(node)); do {from = buildCSSTree(src,from,CSSSyntaxNode.SUBTREE_SEL,node); orList.add(new SyntaxNode(node)); } while (src[from].type == CSSLex.CSSLExType.PLUS); node.type = CSSSyntaxNode.SELECTOR_GROUP; node.children = orList.toArray(new SyntaxNode[orList.size()]); } break; case SUBTREE_SEL : from = buildCSSTree(src,from,CSSSyntaxNode.STANDALONE_SEL,node); if (src[from].type == CSSLex.CSSLExType.SEQUENT) { final List<SyntaxNode> nestedList = new ArrayList<>(); nestedList.add(new SyntaxNode(node)); do {from = buildCSSTree(src,from+1,CSSSyntaxNode.STANDALONE_SEL,node); nestedList.add(new SyntaxNode(node)); } while (src[from].type == CSSLex.CSSLExType.SEQUENT); node.type = CSSSyntaxNode.SUBTREE_SEL; node.children = nestedList.toArray(new SyntaxNode[nestedList.size()]); } break; case STANDALONE_SEL : from = buildCSSTree(src,from,CSSSyntaxNode.SEL_ITEM,node); if (src[from].type == CSSLex.CSSLExType.CONCAT) { final List<SyntaxNode> andList = new ArrayList<>(); andList.add(new SyntaxNode(node)); do {from = buildCSSTree(src,from+1,CSSSyntaxNode.SEL_ITEM,node); andList.add(new SyntaxNode(node)); } while (src[from].type == CSSLex.CSSLExType.CONCAT); node.type = CSSSyntaxNode.STANDALONE_SEL; node.children = andList.toArray(new SyntaxNode[andList.size()]); } break; case SEL_ITEM : node.col = src[from].pos; switch (src[from].type) { case ASTERISK : node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_ASTERISK; from++; break; case CLASS : node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_CLASS; node.cargo = src[from].strValue; from++; break; case ID : node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_ID; node.cargo = src[from].strValue; from++; break; case NAME : node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_TAG; node.cargo = src[from].strValue; from++; break; case PSEUDOCLASS: node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_PSEUDOCLASS; if (src[from+1].type == CSSLex.CSSLExType.OPEN) { if (src[from+2].type == CSSLex.CSSLExType.NUMBER && src[from+3].type == CSSLex.CSSLExType.NAME && src[from+4].type == CSSLex.CSSLExType.PLUS && src[from+5].type == CSSLex.CSSLExType.NUMBER && src[from+6].type == CSSLex.CSSLExType.CLOSE) { node.cargo = new Object[]{src[from].strValue,src[from+2].intValue,src[from+5].intValue}; from += 7; } else if (src[from+2].type == CSSLex.CSSLExType.NUMBER && src[from+3].type == CSSLex.CSSLExType.NAME && src[from+4].type == CSSLex.CSSLExType.CLOSE) { node.cargo = new Object[]{src[from].strValue,src[from+2].intValue,0}; from += 5; } else if (src[from+2].type == CSSLex.CSSLExType.NUMBER && src[from+3].type == CSSLex.CSSLExType.CLOSE) { node.cargo = new Object[]{src[from].strValue,0,src[from+2].intValue}; from += 4; } else { throw new SyntaxException(0,src[from].pos,"Illegal pseudoclass parameters"); } } else { node.cargo = new Object[]{src[from].strValue}; from++; } break; case OPENB : if (src[from+1].type == CSSLex.CSSLExType.ATTRIBUTE) { if (src[from+2].type == CSSLex.CSSLExType.CLOSEB) { node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_ATTR; node.cargo = new Object[]{src[from+1].strValue}; from+=3; } else if (src[from+2].type == CSSLex.CSSLExType.OPER && src[from+3].type == CSSLex.CSSLExType.STRING && src[from+4].type == CSSLex.CSSLExType.CLOSEB) { node.type = CSSSyntaxNode.SEL_ITEM; node.value = CSSLex.NODE_ATTR; node.cargo = new Object[]{src[from+1].strValue,src[from+2].intValue,src[from+3].strValue}; from+=5; } else { throw new SyntaxException(0,src[from].pos,"Illegal attribute check"); } } else { throw new SyntaxException(0,src[from].pos,"Illegal attribute check"); } break; default: break; } break; default : break; } return from; } private static void printCSSTree(final SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>> node, final Writer writer) throws IOException { printCSSTree(node,writer,0); } private static void printCSSTree(final SyntaxNode<CSSSyntaxNode,?> node, final Writer writer, final int tabs) throws IOException { if (node != null) { for (int index = 0; index < tabs; index++) { writer.write('\t'); } writer.write(node.type.name()); writer.write(" : "); switch ((int)node.value) { case CSSLex.NODE_ASTERISK : writer.write("*"); case CSSLex.NODE_TAG : writer.write("tag"); case CSSLex.NODE_ID : writer.write("id"); case CSSLex.NODE_CLASS : writer.write("class"); case CSSLex.NODE_ATTR : writer.write("attr"); case CSSLex.NODE_PSEUDOCLASS : writer.write("pseudoclass"); default : writer.write(String.valueOf(node.value)); } writer.write(" -> "); writer.write(node.cargo != null ? node.cargo.toString() : "null"); writer.write("\n"); if (node.children != null) { for (SyntaxNode<CSSSyntaxNode, ?> item : node.children) { printCSSTree(item,writer,tabs+1); } } } } private static String convertCSSTree2XPath(final SyntaxNode<CSSSyntaxNode,SyntaxNode<CSSSyntaxNode,?>> node) throws SyntaxException { switch (node.type) { case RECORD : return convertCSSTree2XPath((SyntaxNode<CSSSyntaxNode, SyntaxNode<CSSSyntaxNode, ?>>)node.children[0]); case SELECTORS : final StringBuilder selSb = new StringBuilder(); for (SyntaxNode<CSSSyntaxNode, ?> item : node.children) { selSb.append('|').append(convertCSSTree2XPath((SyntaxNode<CSSSyntaxNode, SyntaxNode<CSSSyntaxNode, ?>>) item)); } return selSb.substring(1); case SELECTOR_GROUP : break; case SUBTREE_SEL : final StringBuilder depthSb = new StringBuilder(); int depth = 0; for (SyntaxNode<CSSSyntaxNode, ?> item : node.children) { if (depth > 0) { depthSb.append(" and ./child["); } depthSb.append('('+convertCSSTree2XPath((SyntaxNode<CSSSyntaxNode, SyntaxNode<CSSSyntaxNode, ?>>) item)+')'); depth++; } while (--depth > 0) { depthSb.append(']'); } return depthSb.toString(); case STANDALONE_SEL : final StringBuilder andSb = new StringBuilder(); for (SyntaxNode<CSSSyntaxNode, ?> item : node.children) { andSb.append(" and ").append(convertCSSTree2XPath((SyntaxNode<CSSSyntaxNode, SyntaxNode<CSSSyntaxNode, ?>>) item)); } return andSb.substring(5); case SEL_ITEM : switch ((int)node.value) { case CSSLex.NODE_ASTERISK : return "*"; case CSSLex.NODE_TAG : return "node-name(.)=\'"+node.cargo.toString()+"\'"; case CSSLex.NODE_ID : return "@id=\'"+node.cargo.toString()+"\'"; case CSSLex.NODE_CLASS : return "contains(concat(' ',normalize-space(@class),' '),\' "+node.cargo.toString()+" \')"; case CSSLex.NODE_ATTR : if (((Object[])node.cargo).length == 1) { return "boolean(@"+((Object[])node.cargo)[0].toString()+")"; } else { switch ((Integer)((Object[])node.cargo)[1]) { case CSSLex.OPER_ENDSWITH : return "ends-with(@"+((Object[])node.cargo)[0].toString()+",\'"+((Object[])node.cargo)[2].toString()+"\')"; case CSSLex.OPER_CONTAINS : return "contains(@"+((Object[])node.cargo)[0].toString()+",\'"+((Object[])node.cargo)[2].toString()+"\')"; case CSSLex.OPER_CONTAINS_VALUE : return "contains(concat(' ',normalize-space(@"+((Object[])node.cargo)[0].toString()+"),' '),\' "+((Object[])node.cargo)[2].toString()+" \')"; case CSSLex.OPER_STARTSWITH : return "starts-with(@"+((Object[])node.cargo)[0].toString()+",\'"+((Object[])node.cargo)[2].toString()+"\')"; case CSSLex.OPER_STARTS_OR_EQUALS : return "(starts-with(@"+((Object[])node.cargo)[0].toString()+",\'"+((Object[])node.cargo)[2].toString()+"\') or @"+((Object[])node.cargo)[0].toString()+"=\'"+((Object[])node.cargo)[2].toString()+"\')"; case CSSLex.OPER_EQUALS : return "@"+((Object[])node.cargo)[0].toString()+"=\'"+((Object[])node.cargo)[2].toString()+"\'"; default : throw new SyntaxException(node.row,node.col,"Unsupported attribute operation ["+((Object[])node.cargo)[1]+"] in the syntax tree"); } } case CSSLex.NODE_PSEUDOCLASS: break; default : throw new SyntaxException(node.row,node.col,"Unsupported node ["+node.value+"] in the syntax tree"); } break; default: break; } return null; } private enum CSSSyntaxNode { RECORD, SELECTORS, SELECTOR_GROUP, SUBTREE_SEL, STANDALONE_SEL, SEL_ITEM } public static boolean isValidColor(final String color) throws SyntaxException { if (color == null || color.isEmpty()) { throw new IllegalArgumentException("Color content can't be null or empty"); } else { return isValidColor(UnsafedUtils.getStringContent(color)); } } public static Color asColor(final String color) throws SyntaxException { if (color == null || color.isEmpty()) { throw new IllegalArgumentException("Color content can't be null or empty"); } else { return asColor(UnsafedUtils.getStringContent(color)); } } public static boolean isValidColor(final char[] content) throws SyntaxException { if (content == null || content.length == 0) { throw new IllegalArgumentException("Color content can't be null or empty array"); } else { final Object[] values = new Object[4]; int from = 0; if (content[0] == ' return CharUtils.tryExtract(content,from,COLOR_HEX_TEMPLATE) > 0; } if (content.length > 4) { if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_RGBA,0,COLOR_RGBA.length)) { return CharUtils.tryExtract(content,from,COLOR_RGBA_TEMPLATE) > 0; } else if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_HSLA,0,COLOR_HSLA.length)) { return CharUtils.tryExtract(content,from,COLOR_HSLA_TEMPLATE) > 0; } } if (content.length > 3) { if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_RGB,0,COLOR_RGB.length)) { return CharUtils.tryExtract(content,from,COLOR_RGB_TEMPLATE) > 0; } else if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_HSL,0,COLOR_HSL.length)) { return CharUtils.tryExtract(content,from,COLOR_HSL_TEMPLATE) > 0; } else { return PureLibSettings.colorByName(new String(content),null) != null; } } return PureLibSettings.colorByName(new String(content),null) != null; } } public static Color asColor(final char[] content) throws SyntaxException { if (content == null || content.length == 0) { throw new IllegalArgumentException("Color content can't be null or empty array"); } else { final Object[] values = new Object[4]; int from = 0; if (content[0] == ' from = CharUtils.extract(content,from,values,COLOR_HEX_TEMPLATE); return new Color((Integer)values[0]); } if (content.length > 4) { if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_RGBA,0,COLOR_RGBA.length)) { from = CharUtils.extract(content,from,values,COLOR_RGBA_TEMPLATE); return new Color((Integer)values[0],(Integer)values[1],(Integer)values[2],(Integer)values[3]); } else if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_HSLA,0,COLOR_HSLA.length)) { from = CharUtils.extract(content,from,values,COLOR_HSLA_TEMPLATE); final Color temp = Color.getHSBColor((Integer)values[0]/256.0f,0.01f*(Float)values[1],0.01f*(Float)values[2]); return new Color(temp.getRed(),temp.getGreen(),temp.getBlue(),Math.min((int)(2.56f*(Float)values[3]),255)); } } if (content.length > 3) { if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_RGB,0,COLOR_RGB.length)) { from = CharUtils.extract(content,from,values,COLOR_RGB_TEMPLATE); return new Color((Integer)values[0],(Integer)values[1],(Integer)values[2]); } else if (UnsafedCharUtils.uncheckedCompare(content,0,COLOR_HSL,0,COLOR_HSL.length)) { from = CharUtils.extract(content,from,values,COLOR_HSL_TEMPLATE); return Color.getHSBColor((Integer)values[0]/256.0f,0.01f*(Float)values[1],0.01f*(Float)values[2]); } else { final Color toRet = PureLibSettings.colorByName(new String(content),null); if (toRet != null) { return toRet; } else { throw new SyntaxException(0,0,"Color name ["+new String(content)+"] is unknown"); } } } final Color toRet = PureLibSettings.colorByName(new String(content),null); if (toRet != null) { return toRet; } else { throw new SyntaxException(0,0,"Color name ["+new String(content)+"] is unknown"); } } } public static class Distance { private static final int MAX_CACHEABLE = 128; private static final ArgumentType[] LEXEMAS = {ArgumentType.ordinalInt,ArgumentType.name}; private static final Map<Units,Distance[]> microCache = new EnumMap<>(Units.class); private static final LightWeightRWLockerWrapper locker = new LightWeightRWLockerWrapper(); private static final float INCH = 25.4f; private static final float[] KOEFFS = {10, 1, INCH, INCH/96, INCH/72, 12*INCH/72, 1, 1, 1, 1, 1, 1, 1, 1, 1}; public enum Units { cm, mm, in, px, pt, pc, // Absolute em, ex, ch, rem, vw, vh, vmin, vmax, percent // Relative } private final int value; private final Units unit; public Distance(final int value, final Units unit) { if (value < 0) { throw new IllegalArgumentException("Value ["+value+"] must not be negative"); } else if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else { this.value = value; this.unit = unit; } } public int getValue() { return value; } public Units getUnit() { return unit; } public float getValueAs(final Units unit) { if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else if (this.unit == unit) { return getValue(); } else { return getValue()*KOEFFS[this.unit.ordinal()]/KOEFFS[unit.ordinal()]; } } public static boolean isValidDistance(final String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value can't be null or empty"); } else { try { return CharUtils.tryExtract(UnsafedUtils.getStringContent(value),0,(Object[])LEXEMAS) > 0; } catch (SyntaxException e) { return false; } } } public static Distance valueOf(final String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value can't ne null or empty"); } else { return valueOf(value.toCharArray()); } } public static boolean isValidDistance(final char[] value) { if (value == null || value.length == 0) { throw new IllegalArgumentException("Value can't be null or empty array"); } else { try { return CharUtils.tryExtract(value,0,(Object[])LEXEMAS) > 0; } catch (SyntaxException e) { return false; } } } public static Distance valueOf(final char[] content) { if (content == null || content.length == 0) { throw new IllegalArgumentException("Content can't ne null or empty array"); } else { final Object[] result = new Object[2]; try{CharUtils.extract(content,0,result,(Object[])LEXEMAS); } catch (SyntaxException e) { throw new IllegalArgumentException("String ["+new String()+"]: error at index ["+e.getCol()+"] ("+e.getLocalizedMessage()+")"); } return valueOf(((Integer)result[0]).intValue(),Units.valueOf(result[1].toString())); } } public static Distance valueOf(final int value, final Units unit) { if (value < 0) { throw new IllegalArgumentException("Value ["+value+"] can't ne negative"); } else if (unit == null) { throw new NullPointerException("Unit value can't be null"); } else if (value >= MAX_CACHEABLE) { return new Distance(value, unit); } else { try(final Locker lock = locker.lock(true)) { Distance[] list = microCache.get(unit); if (list != null && list[value] != null) { return list[value]; } } try(final Locker lock = locker.lock(false)) { Distance[] list = microCache.get(unit); if (list == null) { microCache.put(unit,list = new Distance[MAX_CACHEABLE]); } if (list[value] == null) { list[value] = new Distance(value, unit); } return list[value]; } } } @Override public String toString() { return ""+value+unit; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((unit == null) ? 0 : unit.hashCode()); result = prime * result + value; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Distance other = (Distance) obj; if (unit != other.unit) return false; if (value != other.value) return false; return true; } } public static boolean isValidDistance(final String distance) throws SyntaxException { if (distance == null || distance.isEmpty()) { throw new IllegalArgumentException("Distance string can't be null or empty"); } else { return Distance.isValidDistance(distance); } } public static Distance asDistance(final String distance) throws SyntaxException { if (distance == null || distance.isEmpty()) { throw new IllegalArgumentException("Distance string can't be null or empty"); } else { try{return Distance.valueOf(distance); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Distance ["+distance+"] has invalid syntax"); } } } public static boolean isValidDistance(final char[] distance) throws SyntaxException { if (distance == null || distance.length == 0) { throw new IllegalArgumentException("Distance can't be null or empty array"); } else { return Distance.isValidDistance(distance); } } public static Distance asDistance(final char[] distance) throws SyntaxException { if (distance == null || distance.length == 0) { throw new IllegalArgumentException("Distance string can't be null or empty"); } else { try{return Distance.valueOf(distance); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Distance ["+new String(distance)+"] has invalid syntax"); } } } public static class Angle { private static final int MAX_CACHEABLE = 128; private static final ArgumentType[] LEXEMAS = {ArgumentType.ordinalFloat,ArgumentType.name}; private static final float[][] KOEFFS = new float[][] { // deg grad rad turn /*deg*/ {1.0f, 90f/100f, (float)(Math.PI/180.0f), 90.0f/360.0f}, /*grad*/{100f/90f, 1.0f, (float)(Math.PI/200.0f), 100.0f/360.0f}, /*rad*/ {(float)(180.0f/Math.PI), (float)(200.0f/Math.PI), 1.0f, (float)(0.5f/Math.PI)}, /*turn*/{360.0f/90.0f, 360.0f/100.0f, (float)(Math.PI/0.5f), 1.0f}, }; private static final Map<Units,Angle[]> microCache = new EnumMap<>(Units.class); private static final LightWeightRWLockerWrapper locker = new LightWeightRWLockerWrapper(); public enum Units { deg, grad, rad, turn // Absolute } private final float value; private final Units unit; public Angle(final float value, final Units unit) { if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else { this.value = value; this.unit = unit; } } public float getValue() { return value; } public float getValueAs(final Units unit) { if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else if (this.unit == unit) { return getValue(); } else { return KOEFFS[this.unit.ordinal()][unit.ordinal()]*getValue(); } } public Units getUnit() { return unit; } public static Angle valueOf(final String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value ["+value+"] can't ne null or empty"); } else { final char[] content = UnsafedUtils.getStringContent(value); final Object[] result = new Object[2]; try{CharUtils.extract(content,0,result,(Object[])LEXEMAS); } catch (SyntaxException e) { throw new IllegalArgumentException("String ["+value+"]: error at index ["+e.getCol()+"] ("+e.getLocalizedMessage()+")"); } return valueOf(((Float)result[0]).intValue(),Units.valueOf(result[1].toString())); } } public static Angle valueOf(final float value, final Units unit) { if (value < 0) { throw new IllegalArgumentException("Value ["+value+"] can't ne negative"); } else if (unit == null) { throw new NullPointerException("Unit value can't be null"); } else if (value < 0 || value >= MAX_CACHEABLE || value != (float)((int)value)) { return new Angle(value, unit); } else { final int intValue = (int)value; try(final Locker lock = locker.lock(true)) { Angle[] list = microCache.get(unit); if (list != null && list[intValue] != null) { return list[intValue]; } } try(final Locker lock = locker.lock(false)) { Angle[] list = microCache.get(unit); if (list == null) { microCache.put(unit,list = new Angle[MAX_CACHEABLE]); } if (list[intValue] == null) { list[intValue] = new Angle(value, unit); } return list[intValue]; } } } @Override public String toString() { return ""+value+unit; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((unit == null) ? 0 : unit.hashCode()); result = prime * result + Float.floatToIntBits(value); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Angle other = (Angle) obj; if (unit != other.unit) return false; if (Float.floatToIntBits(value) != Float.floatToIntBits(other.value)) return false; return true; } } public static Angle asAngle(final String angle) throws SyntaxException { if (angle == null || angle.isEmpty()) { throw new IllegalArgumentException("Angle string can't be null or empty"); } else { try{return Angle.valueOf(angle); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Angle ["+angle+"] has invalid syntax"); } } } public static class Time { private static final int MAX_CACHEABLE = 128; private static final ArgumentType[] LEXEMAS = {ArgumentType.ordinalFloat,ArgumentType.name}; private static final Map<Units,Time[]> microCache = new EnumMap<>(Units.class); private static final float[][] KOEFFS = new float[][] { // msec sec /*msec*/ {1.0f, 0.001f}, /*sec*/ {1000f, 1.0f}, }; private static final LightWeightRWLockerWrapper locker = new LightWeightRWLockerWrapper(); public enum Units { msec, sec // Absolute } private final float value; private final Units unit; public Time(final float value, final Units unit) { if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else { this.value = value; this.unit = unit; } } public float getValue() { return value; } public float getValueAs(final Units unit) { if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else if (this.unit == unit) { return getValue(); } else { return KOEFFS[this.unit.ordinal()][unit.ordinal()]*getValue(); } } public Units getUnit() { return unit; } public static boolean isValidTime(final String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value can't be null or empty"); } else { try { return CharUtils.tryExtract(UnsafedUtils.getStringContent(value),0,(Object[])LEXEMAS) > 0; } catch (SyntaxException e) { return false; } } } public static Time valueOf(final String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value can't ne null or empty"); } else { final char[] content = UnsafedUtils.getStringContent(value); final Object[] result = new Object[2]; try{CharUtils.extract(content,0,result,(Object[])LEXEMAS); } catch (SyntaxException e) { throw new IllegalArgumentException("String ["+value+"]: error at index ["+e.getCol()+"] ("+e.getLocalizedMessage()+")"); } return valueOf(((Float)result[0]).floatValue(),Units.valueOf(result[1].toString())); } } public static boolean isValidTime(final char[] time) throws SyntaxException { if (time == null || time.length == 0) { throw new IllegalArgumentException("Distance can't be null or empty array"); } else { try { return CharUtils.tryExtract(time,0,(Object[])LEXEMAS) > 0; } catch (SyntaxException e) { return false; } } } public static Time valueOf(final char[] content) { if (content == null || content.length == 0) { throw new IllegalArgumentException("Content can't ne null or empty array"); } else { final Object[] result = new Object[2]; try{CharUtils.extract(content,0,result,(Object[])LEXEMAS); } catch (SyntaxException e) { throw new IllegalArgumentException("String ["+new String(content)+"]: error at index ["+e.getCol()+"] ("+e.getLocalizedMessage()+")"); } return valueOf(((Float)result[0]).floatValue(),Units.valueOf(result[1].toString())); } } public static Time valueOf(final float value, final Units unit) { if (value < 0) { throw new IllegalArgumentException("Value ["+value+"] can't ne negative"); } else if (unit == null) { throw new NullPointerException("Unit value can't be null"); } else if (value >= MAX_CACHEABLE || value != (float)((int)value)) { return new Time(value, unit); } else { final int intValue = (int)value; try(final Locker lock = locker.lock(true)) { Time[] list = microCache.get(unit); if (list != null && list[intValue] != null) { return list[intValue]; } } try(final Locker lock = locker.lock(false)) { Time[] list = microCache.get(unit); if (list == null) { microCache.put(unit,list = new Time[MAX_CACHEABLE]); } if (list[intValue] == null) { list[intValue] = new Time(value, unit); } return list[intValue]; } } } @Override public String toString() { return ""+value+unit; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((unit == null) ? 0 : unit.hashCode()); result = prime * result + Float.floatToIntBits(value); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Time other = (Time) obj; if (unit != other.unit) return false; if (Float.floatToIntBits(value) != Float.floatToIntBits(other.value)) return false; return true; } } public static boolean isValidTime(final String time) throws SyntaxException { if (time == null || time.isEmpty()) { throw new IllegalArgumentException("Time string can't be null or empty"); } else { try{return Time.isValidTime(time); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Time ["+time+"] has invalid syntax"); } } } public static boolean isValidTime(final char[] time) throws SyntaxException { if (time == null || time.length == 0) { throw new IllegalArgumentException("Time string can't be null or empty array"); } else { try{return Time.isValidTime(time); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Time ["+new String(time)+"] has invalid syntax"); } } } public static Time asTime(final String time) throws SyntaxException { if (time == null || time.isEmpty()) { throw new IllegalArgumentException("Time string can't be null or empty"); } else { try{return Time.valueOf(time); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Time ["+time+"] has invalid syntax"); } } } public static Time asTime(final char[] time) throws SyntaxException { if (time == null || time.length == 0) { throw new IllegalArgumentException("Time string can't be null or empty array"); } else { try{return Time.valueOf(time); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Time ["+new String(time)+"] has invalid syntax"); } } } public static class Frequency { private static final int MAX_CACHEABLE = 128; private static final ArgumentType[] LEXEMAS = {ArgumentType.ordinalFloat,ArgumentType.name}; private static final float[][] KOEFFS = new float[][] { // Hz kHz {1.0f, 0.001f}, /*kHz*/ {1000f, 1.0f}, }; private static final Map<Units,Frequency[]> microCache = new EnumMap<>(Units.class); private static final LightWeightRWLockerWrapper locker = new LightWeightRWLockerWrapper(); public enum Units { Hz, kHz // Absolute } private final float value; private final Units unit; public Frequency(final float value, final Units unit) { if (value < 0) { throw new IllegalArgumentException("Frequency value ["+value+"] can't be negative"); } else if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else { this.value = value; this.unit = unit; } } public float getValue() { return value; } public float getValueAs(final Units unit) { if (unit == null) { throw new NullPointerException("Unit type can't be null"); } else if (this.unit == unit) { return getValue(); } else { return KOEFFS[this.unit.ordinal()][unit.ordinal()]*getValue(); } } public Units getUnit() { return unit; } public static Frequency valueOf(final String value) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Value ["+value+"] can't ne null or empty"); } else { final char[] content = UnsafedUtils.getStringContent(value); final Object[] result = new Object[2]; try{CharUtils.extract(content,0,result,(Object[])LEXEMAS); } catch (SyntaxException e) { throw new IllegalArgumentException("String ["+value+"]: error at index ["+e.getCol()+"] ("+e.getLocalizedMessage()+")"); } return valueOf(((Float)result[0]).floatValue(),Units.valueOf(result[1].toString())); } } public static Frequency valueOf(final float value, final Units unit) { if (value < 0) { throw new IllegalArgumentException("Value ["+value+"] can't ne negative"); } else if (unit == null) { throw new NullPointerException("Unit value can't be null"); } else if (value >= MAX_CACHEABLE || value != (float)((int)value)) { return new Frequency(value, unit); } else { final int intValue = (int)value; try(final Locker lock = locker.lock(true)) { Frequency[] list = microCache.get(unit); if (list != null && list[intValue] != null) { return list[intValue]; } } try(final Locker lock = locker.lock(false)) { Frequency[] list = microCache.get(unit); if (list == null) { microCache.put(unit,list = new Frequency[MAX_CACHEABLE]); } if (list[intValue] == null) { list[intValue] = new Frequency(value, unit); } return list[intValue]; } } } @Override public String toString() { return ""+value+unit; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((unit == null) ? 0 : unit.hashCode()); result = prime * result + Float.floatToIntBits(value); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Frequency other = (Frequency) obj; if (unit != other.unit) return false; if (Float.floatToIntBits(value) != Float.floatToIntBits(other.value)) return false; return true; } } public static Frequency asFrequency(final String freq) throws SyntaxException { if (freq == null || freq.isEmpty()) { throw new IllegalArgumentException("Frequency string can't be null or empty"); } else { try{return Frequency.valueOf(freq); } catch (NumberFormatException exc) { throw new SyntaxException(0,0,"Frequency ["+freq+"] has invalid syntax"); } } } public static AffineTransform asTransform(final String transform) throws SyntaxException, IllegalArgumentException { if (transform == null || transform.isEmpty()) { throw new IllegalArgumentException("Transform string to parse can't be null or empty"); } else { final AffineTransform result = new AffineTransform(); final char[] content = new char[transform.length()+1]; final float[] number = new float[1]; float x, y; boolean wasMinus; int from = 0; transform.getChars(0,content.length-1,content,0); content[content.length-1] = '\n'; for (;;) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from,true); if (content[from] == '\n') { break; } else if (!Character.isJavaIdentifierStart(content[from])) { throw new SyntaxException(0,from,"Reserved word is missing at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else if (UnsafedCharUtils.uncheckedCompare(content,from,TRANSFORM_ROTATE,0,TRANSFORM_ROTATE.length)) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+TRANSFORM_ROTATE.length,true); if (content[from] != '(') { throw new SyntaxException(0,from,"Missing '(' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); if ((wasMinus = content[from] == '-')) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); } from = UnsafedCharUtils.uncheckedSkipBlank(content,UnsafedCharUtils.uncheckedParseFloat(content,from,number,true),true); if (content[from] != ')') { throw new SyntaxException(0,from,"Missing ')' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { from++; result.rotate(Math.PI * (wasMinus ? -number[0] : number[0]) / 180); } } } else if (UnsafedCharUtils.uncheckedCompare(content,from,TRANSFORM_SCALE,0,TRANSFORM_SCALE.length)) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+TRANSFORM_SCALE.length,true); if (content[from] != '(') { throw new SyntaxException(0,from,"Missing '(' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); if ((wasMinus = content[from] == '-')) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); } from = UnsafedCharUtils.uncheckedSkipBlank(content,UnsafedCharUtils.uncheckedParseFloat(content,from,number,true),true); if (content[from] != ',') { throw new SyntaxException(0,from,"Missing ',' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { x = wasMinus ? -number[0] : number[0]; from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); if ((wasMinus = content[from] == '-')) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); } from = UnsafedCharUtils.uncheckedSkipBlank(content,UnsafedCharUtils.uncheckedParseFloat(content,from,number,true),true); if (content[from] != ')') { throw new SyntaxException(0,from,"Missing ')' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { from++; y = wasMinus ? -number[0] : number[0]; result.scale(x,y); } } } } else if (UnsafedCharUtils.uncheckedCompare(content,from,TRANSFORM_TRANSLATE,0,TRANSFORM_TRANSLATE.length)) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+TRANSFORM_TRANSLATE.length,true); if (content[from] != '(') { throw new SyntaxException(0,from,"Missing '(' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); if ((wasMinus = content[from] == '-')) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); } from = UnsafedCharUtils.uncheckedSkipBlank(content,UnsafedCharUtils.uncheckedParseFloat(content,from,number,true),true); if (content[from] != ',') { throw new SyntaxException(0,from,"Missing ',' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { x = wasMinus ? -number[0] : number[0]; from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); if ((wasMinus = content[from] == '-')) { from = UnsafedCharUtils.uncheckedSkipBlank(content,from+1,true); } from = UnsafedCharUtils.uncheckedSkipBlank(content,UnsafedCharUtils.uncheckedParseFloat(content,from,number,true),true); if (content[from] != ')') { throw new SyntaxException(0,from,"Missing ')' at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } else { from++; y = wasMinus ? -number[0] : number[0]; result.translate(x,y); } } } } else { throw new SyntaxException(0,from,"Unknown reserved word at ["+SyntaxException.extractFragment(transform,0,from,20)+"]"); } } return result; } } public static class StylePropValue<T> { private final StylePropertiesSupported.ContentType type; private final StylePropertiesSupported prop; private final T value; public StylePropValue(final ContentType type, final StylePropertiesSupported prop, final T value) { this.type = type; this.prop = prop; this.value = value; } public StylePropertiesSupported.ContentType getType() { return type; } public StylePropertiesSupported getProp() { return prop; } public T getValue() { return value; } @Override public String toString() { return "StylePropValue [type=" + type + ", prop=" + prop + ", value=" + value + "]"; } } public static class StylePropertiesStack implements Iterable<Map<String,Object>>{ private final List<Map<String,Object>> stack = new ArrayList<>(); public void push(Map<String,Object> values) { if (values == null) { throw new NullPointerException("Values map can't be null"); } else { stack.add(0,values); } } public int size() { return stack.size(); } public Map<String,Object> peek() { if (stack.isEmpty()) { throw new EmptyStackException(); } else { return stack.get(0); } } public Map<String,Object> pop() { if (stack.isEmpty()) { throw new EmptyStackException(); } else { return stack.remove(0); } } @Override public Iterator<Map<String, Object>> iterator() { return stack.iterator(); } @Override public String toString() { return "StylePropertiesStack [stack=" + stack + "]"; } } public static class StylePropertiesTree { private static final Map<StylePropertiesSupported,StylePropertyDescription> TREE = new EnumMap<>(StylePropertiesSupported.class); static { } public static boolean isPropertySupported(final String prop) { if (prop == null || prop.isEmpty()) { throw new IllegalArgumentException("Property string can't be null or empty"); } else { return false; } } public static <T> T inferValue(final String prop, final StylePropertiesStack content) { if (prop == null || prop.isEmpty()) { throw new IllegalArgumentException("Property name can't be null or empty"); } else if (content == null) { throw new IllegalArgumentException("Properties stack can't be null"); } else if (!isPropertySupported(prop)) { for (Map<String, Object> item : content) { if (item.containsKey(prop)) { return (T)item.get(prop); } } } else { final StylePropertyDescription desc = TREE.get(StylePropertiesSupported.valueOf(prop)); for (Map<String, Object> item : content) { if (item.containsKey(prop)) { return (T)item.get(prop); } if (desc.isDetailedProperty()) { StylePropertyDescription masterDesc = TREE.get(desc.getMasterProp()); if (item.containsKey(masterDesc.getType().name())) { return (T)item.get(masterDesc.getType().name()); } } if (desc.hasContainer()) { StylePropertyDescription masterDesc = TREE.get(desc.getMasterProp()); if (item.containsKey(masterDesc.getType().name())) { return (T)item.get(masterDesc.getType().name()); } } if (!desc.isInheritanceSupported()) { break; } } return null; } return null; } public static Map<String,Object> inferAll(final StylePropertiesStack content) { return null; } class StylePropertyDescription { private final StylePropertiesSupported prop; private final boolean inheritanceSupported, listSupported; private final StylePropertiesSupported[] template; private final StylePropertyDescription[] details; StylePropertyDescription(final StylePropertiesSupported prop, final boolean inheritanceSupported, final boolean listSupported, final String description, final StylePropertiesSupported... template) { if (prop == null) { throw new NullPointerException("Styled properties type can't be null"); } else if (description == null || description.isEmpty()) { throw new IllegalArgumentException("Description can't be null or empty"); } else if (template == null) { throw new NullPointerException("Template list can't be null"); } else { this.prop = prop; this.inheritanceSupported = inheritanceSupported; this.listSupported = listSupported; this.template = template; this.details = null; } } StylePropertyDescription(final StylePropertiesSupported prop, final boolean inheritanceSupported, final boolean listSupported, final String description, final StylePropertyDescription... details) { if (prop == null) { throw new NullPointerException("Styled properties type can't be null"); } else if (description == null || description.isEmpty()) { throw new IllegalArgumentException("Description can't be null or empty"); } else if (details == null) { throw new NullPointerException("Details list can't be null"); } else { this.prop = prop; this.inheritanceSupported = inheritanceSupported; this.listSupported = listSupported; this.template = null; this.details = details; } } StylePropertiesSupported getType() { return prop; } boolean isInheritanceSupported() { return inheritanceSupported; } boolean isListSupported() { return listSupported; } boolean isContainer() { return template != null; } boolean isDetailedProperty() { return details == null; } StylePropertiesSupported getMasterProp() { return null; } boolean hasContainer() { return false; } StylePropertiesSupported getContainerProp() { return null; } <T> Class<T> getValueClass() { return null; } } } // private static void addName(final SyntaxTreeInterface<StylePropValue<?>[]> keywords, final StylePropertiesSupported prop, final ValueListDescriptor values) { // final String[] content = values.getContent(); // for (String item : content) { // final StylePropValue<String> newValue = new StylePropValue<String>(ContentType.value,prop,item); // final long id = keywords.seekName(item); // if (id < 0) { // keywords.placeName(item,new StylePropValue[]{newValue}); // else { // final StylePropValue<?>[] currentList = keywords.getCargo(id); // final StylePropValue<?>[] newList = Arrays.copyOf(currentList,currentList.length+1); // newList[newList.length-1] = newValue; // keywords.setCargo(id, newList); private static class CSSLex { private static final int OPER_ENDSWITH = 0; private static final int OPER_CONTAINS = 1; private static final int OPER_CONTAINS_VALUE = 2; private static final int OPER_STARTSWITH = 3; private static final int OPER_STARTS_OR_EQUALS = 4; private static final int OPER_EQUALS = 5; private static final int NODE_ASTERISK = 0; private static final int NODE_TAG = 1; private static final int NODE_ID = 2; private static final int NODE_CLASS = 3; private static final int NODE_ATTR = 4; private static final int NODE_PSEUDOCLASS = 5; private enum CSSLExType { ASTERISK, ID, CLASS, PSEUDOCLASS, ATTRIBUTE, DIV, CONCAT, NUMBER, STRING, NAME, OPENB, CLOSEB, OPER, SEQUENT, PLUS, OPEN, CLOSE, PROPS, EOF, } private final int pos; private final CSSLExType type; private final int intValue; private final String strValue; private final Properties props; CSSLex(final int pos, final CSSLExType type) { this(pos,type, 0, null, null); } CSSLex(final int pos, final CSSLExType type, final String strValue) { this(pos,type, 0, strValue, null); } CSSLex(final int pos, final CSSLExType type, final int intValue) { this(pos,type,intValue,null, null); } CSSLex(final int pos, final CSSLExType type, final Properties props) { this(pos,type,0,null,props); } private CSSLex(final int pos, final CSSLExType type, final int intValue, final String strValue, final Properties props) { this.pos = pos; this.type = type; this.intValue = intValue; this.strValue = strValue; this.props = props; } @Override public String toString() { return "CSSLex [pos=" + pos + ", type=" + type + ", intValue=" + intValue + ", strValue=" + strValue + ", props=" + props + "]"; } } }
package com.amee.domain; import com.amee.base.domain.ResultsWrapper; import com.amee.domain.data.DataCategory; import com.amee.domain.data.ItemValueMap; import com.amee.domain.item.BaseItemValue; import com.amee.domain.item.data.BaseDataItemValue; import com.amee.domain.item.data.DataItem; import com.amee.domain.sheet.Choices; import com.amee.platform.science.StartEndDate; import org.joda.time.DateTime; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; public interface DataItemService extends ItemService { public final static Date EPOCH = new Date(0); // This time is seven seconds less than the last unix because StartEndDate is not sensitive to seconds. public final static Date Y2038 = new DateTime(2038, 1, 19, 3, 14, 0, 0).toDate(); public long getDataItemCount(IDataCategoryReference dataCategory); public List<DataItem> getDataItems(IDataCategoryReference dataCategory); public List<DataItem> getDataItems(IDataCategoryReference dataCategory, boolean checkDataItems); public List<DataItem> getDataItems(Set<Long> dataItemIds); public DataItem getDataItemByIdentifier(DataCategory parent, String path); public Map<String, DataItem> getDataItemMap(Set<Long> dataItemIds, boolean loadValues); public ItemValueMap getDrillDownValuesMap(DataItem dataItem); public boolean equivalentDataItemExists(DataItem dataItem); public DataItem getDataItemByUid(DataCategory parent, String uid); public DataItem getItemByUid(String uid); public DataItem getDataItemByPath(DataCategory parent, String path); public String getLabel(DataItem dataItem); public Choices getUserValueChoices(DataItem dataItem, APIVersion apiVersion); public void checkDataItem(DataItem dataItem); public Date getDataItemsModified(DataCategory dataCategory); public boolean isDataItemUniqueByPath(DataItem dataItem); public boolean isDataItemValueUniqueByStartDate(BaseDataItemValue itemValue); public ResultsWrapper<BaseDataItemValue> getAllItemValues(DataItemValuesFilter filter); public void persist(DataItem dataItem); public void persist(DataItem dataItem, boolean checkDataItem); public void remove(DataItem dataItem); public void persist(BaseItemValue itemValue); public void remove(BaseItemValue itemValue); public StartEndDate getStartDate(DataItem dataItem); public StartEndDate getEndDate(DataItem dataItem); public void updateDataItemValues(DataItem dataitem); }
package com.brg.analyse; import com.brg.dao.connection.TargetConnection; import org.apache.ddlutils.Platform; import org.apache.ddlutils.PlatformFactory; import org.apache.ddlutils.model.Column; import org.apache.ddlutils.model.Database; import org.apache.ddlutils.model.Table; import org.apache.ddlutils.platform.JdbcModelReader; import javax.sql.DataSource; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class DatabaseService { private TargetConnection targetConnection; private HashMap<String, String[]> targetDatabase; private Database _tempdatabase; public DatabaseService() { targetDatabase = new HashMap<String, String[]>(); System.out.println("Loading: Connectie met target database"); setTargetDatabase(); } public void setTargetDatabase() { int len = 0; try { //Set database in memory for loading speed _tempdatabase = this.getDatabase(); //Loop over tables for(Table t : this.getTables()) { String tableName = t.getName(); int columnlen = this.getColumns(len).length; int currcolum = 0; String[] columns = new String[columnlen]; //Loop over columns in table for(Column cmn : this.getColumns(len)) { //Put column name in string array columns[currcolum] = cmn.getName(); currcolum++; } //Put table with columns in hashmap targetDatabase.put(tableName, columns); len++; } } catch (Exception e) { e.printStackTrace(); } //Clear memory _tempdatabase = null; } /** * Get target database * @return Database * @throws Exception */ public Database getDatabase() throws Exception { targetConnection = targetConnection.getInstance(); DataSource dataSource = targetConnection.getDataSource(); Platform platform = PlatformFactory.createNewPlatformInstance(dataSource); JdbcModelReader modelReader = platform.getModelReader(); Database database = modelReader.getDatabase(targetConnection.getConnection(), targetConnection.getSchema(), null, targetConnection.getSchema(), null); return database; } /** * Get target tables * @return Table[] * @throws Exception */ private Table[] getTables() throws Exception { Table[] tables = _tempdatabase.getTables(); return tables; } private Table getTable(int i) throws Exception { Table table = _tempdatabase.getTable(i); return table; } private Column[] getColumns(int tableId) throws Exception { Column[] columns = _tempdatabase.getTable(tableId).getColumns(); return columns; } }