answer
stringlengths
17
10.2M
package no.openshell.oddstr13.minecartmeter; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; /** * Handler for the /pos sample command. * @author SpaceManiac */ public class MinecartMeterCommandhandler implements CommandExecutor { private final MinecartMeter plugin; public MinecartMeterCommandhandler(MinecartMeter plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { if (plugin.config.getBoolean("debug", false)) { System.out.println("[DEBUG]: command minecartmeter executed"); } boolean isconsolle = false; boolean isop = false; boolean isplayer = false; boolean debug = plugin.config.getBoolean("debug", false); Player player; if (sender instanceof Player) { player = (Player)sender; isop = player.isOp(); isplayer = true; } else { isconsolle = true; } if (split.length == 1) { if (isconsolle || isop) { if (split[1].equalsIgnoreCase("reload")) { if (debug) { System.out.println("[DEBUG]: reloading config"); } plugin.reloadConfig(); if (debug) { System.out.println("[DEBUG]: config reloaded"); } if (isplayer) { player = (Player)sender; player.sendMessage("MinecartMeter config reloaded."); } return true; } } } if (!(isplayer)) { return false; } player = (Player)sender; player.sendMessage("/minecartmeter"); return true; /* if (split.length == 0) { Location location = player.getLocation(); player.sendMessage("You are currently at " + location.getX() +"," + location.getY() + "," + location.getZ() + " with " + location.getYaw() + " yaw and " + location.getPitch() + " pitch"); return true; } else if (split.length == 3) { try { double x = Double.parseDouble(split[0]); double y = Double.parseDouble(split[1]); double z = Double.parseDouble(split[2]); player.teleportTo(new Location(player.getWorld(), x, y, z)); } catch (NumberFormatException ex) { player.sendMessage("Given location is invalid"); } return true; } else { return false; } */ } }
package com.flipstudio.pluma; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(JUnit4.class) public class PlumaTests { //region Fields private static final File DATABASE_FILE = new File(System.getProperty("java.io.tmpdir"), "TestDB.sqlite"); private static final ArrayList<String> QUERIES = new ArrayList<String>(); private Database mDatabase; //endregion //region Setup @Before public void setUp() throws Exception { if (DATABASE_FILE.exists() && !DATABASE_FILE.delete()) { throw new RuntimeException("Can not delete database file."); } mDatabase = new Database(DATABASE_FILE.getPath()); mDatabase.open(); assertTrue("Can not open database.", mDatabase.isOpen() && DATABASE_FILE.exists()); mDatabase.execute( "CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT, lastName text, birth datetime);\n" + "INSERT INTO people (name,lastName,birth) VALUES ('Jeremy','Xyla','1179129666000');\n" + "INSERT INTO people (name,lastName,birth) VALUES ('Damon','Althea','1029576914000');\n" + "INSERT INTO people (name,lastName,birth) VALUES ('Reese','Kalia','763347737000');"); mDatabase.setDatabaseListener(new Database.DatabaseListener() { @Override public void onExecuteQuery(String query) { recordQuery(query); } }); } //endregion //region Updates @Test public void testUpdate() throws Exception { startTest("Testing updates."); String insertListQuery = "INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)"; ArrayList<Object> listArgs = new ArrayList<Object>(); listArgs.add("Arden"); listArgs.add("Winter"); listArgs.add(new Date(638340461000L)); assertTrue("Could not insert record.", mDatabase.executeUpdate(insertListQuery, listArgs)); assertTrue("Could not insert second record.", mDatabase.executeUpdate(insertListQuery, "Damian", "Ifeoma", new Date(1021405116000L))); HashMap<String, Object> mapArgs = new HashMap<String, Object>(); mapArgs.put("name", "Chaney"); mapArgs.put("lastName", "Kathleen"); mapArgs.put("birth", new Date(812710812000L)); assertTrue("Could not insert third record.", mDatabase.executeUpdate( "INSERT INTO people (name, lastName, birth) VALUES (:name, :lastName, :birth)", mapArgs)); assertQueries("INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)", "INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)", "INSERT INTO people (name, lastName, birth) VALUES (:name, :lastName, :birth)"); } //endregion //region Queries @Test public void testQuery() throws Exception { startTest("Testing queries."); ResultSet rs = mDatabase.executeQuery("SELECT id, name, lastName, birth FROM people"); assertEquals("Unexpected column count.", 4, rs.getColumnCount()); ArrayList<HashMap<String, Object>> people = new ArrayList<HashMap<String, Object>>(); while (rs.next()) { HashMap<String, Object> person = new HashMap<String, Object>(); person.put("id", rs.getInt(0)); person.put("name", rs.getString(1)); person.put("lastName", rs.getString(2)); person.put("birth", rs.getDate(3)); people.add(person); } assertEquals("Unexpected people count.", 3, people.size()); assertEquals("Unexpected person id.", 2, people.get(1).get("id")); assertEquals("Unexpected person name.", "Jeremy", people.get(0).get("name")); assertEquals("Unexpected person last name.", "Kalia", people.get(2).get("lastName")); assertEquals("Unexpected person birth.", new Date(763347737000L), people.get(2).get("birth")); rs = mDatabase.executeQuery("SELECT id, name FROM people WHERE id = ?", 2); assertEquals("Unexpected column count.", 2, rs.getColumnCount()); if (rs.next()) { assertEquals("Unexpected name.", "Damon", rs.getString(1)); assertEquals("Unexpected id.", 2, rs.getBigInteger(0).intValue()); } Map<String, Object> args = new TreeMap<String, Object>(); args.put("FirstName", "Damon"); rs = mDatabase.executeQuery("SELECT id FROM people WHERE name = :FirstName", args); if (rs.next()) { assertEquals("Unexpected id.", 2, rs.getInt(0)); } assertQueries( "SELECT id, name, lastName, birth FROM people", "SELECT id, name FROM people WHERE id = ?", "SELECT id FROM people WHERE name = :FirstName"); } //endregion //region Next @Test public void testNext() throws Exception { startTest("Next"); ResultSet rs = mDatabase.executeQuery("SELECT name FROM people WHERE id = ?", 2); if (rs.next()) { assertEquals("Unexpected name", "Damon", rs.getString(0)); } assertTrue("Unable to close result set ", rs.close()); assertTrue("Unable to execute update", mDatabase.executeUpdate("DELETE FROM people")); rs = mDatabase.executeQuery("SELECT id, name FROM people"); assertFalse("Unexpected value", rs.next()); assertTrue("Unexpected value", rs.close()); } //endregion //region Last Insert Id @Test public void testLastInsertId() throws Exception { String insert = "INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)"; boolean result = mDatabase.executeUpdate(insert, "Carl", "Ifeoma", 757399978000L); assertTrue("Can not insert record.", result); long lastId = mDatabase.getLastInsertId(); assertEquals("Unexpected last id.", 4, lastId); } //endregion //region Exec @Test public void testExec() throws Exception { mDatabase.execute("PRAGMA foreign_keys = ON"); ResultSet rs = mDatabase.executeQuery("PRAGMA foreign_keys"); if (rs.next()) { assertEquals("Unexpected foreign keys.", 1, rs.getInt(0)); } assertTrue("Can not close result set.", rs.close()); mDatabase.execute("PRAGMA foreign_keys = OFF"); rs = mDatabase.executeQuery("PRAGMA foreign_keys"); if (rs.next()) { assertEquals("Unexpected foreign keys.", 0, rs.getInt(0)); } assertTrue("Can not close result set.", rs.close()); } //endregion //region Statements @Test public void testResetStatement() throws Exception { Statement statement = mDatabase.prepareStatement("INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)"); List<Object> binds = Arrays.<Object>asList( "Donna", "Hope", new Date(1374143861000L), "Judith", "Maia", new Date(1415985639000L), "Willa", "Janna", new Date(1381038472000L) ); int bindIndex = 1; for (Object object : binds) { assertEquals("Could not bind object", Pluma.SQLITE_OK, statement.bindObject(bindIndex++, object)); if (bindIndex == 4) { assertEquals("Could not execute statement", Pluma.SQLITE_DONE, statement.step()); bindIndex = 1; assertEquals("Could not reset statement", Pluma.SQLITE_OK, statement.reset()); } } assertEquals("Could not close statement", Pluma.SQLITE_OK, statement.close()); } @Test public void testClearStatement() throws Exception { Statement statement = mDatabase.prepareStatement("INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)"); assertEquals("Could not bind first object", Pluma.SQLITE_OK, statement.bind(1, "Cecilia")); assertEquals("Could not bind second object", Pluma.SQLITE_OK, statement.bind(2, "Marshall")); assertEquals("Could not bind third object", Pluma.SQLITE_OK, statement.bind(3, 1419088806000L)); assertEquals("Could not clear statement", Pluma.SQLITE_OK, statement.clearBindings()); assertEquals("Could not bind first object", Pluma.SQLITE_OK, statement.bind(1, "Ivory")); assertEquals("Could not bind second object", Pluma.SQLITE_OK, statement.bind(2, "Mariko")); assertEquals("Could not bind third object", Pluma.SQLITE_OK, statement.bind(3, 1421394493000L)); assertEquals("Could not execute statement", Pluma.SQLITE_DONE, statement.step()); long id = mDatabase.getLastInsertId(); ResultSet rs = mDatabase.executeQuery("SELECT name FROM people WHERE id = ?", id); assertTrue("Empty result set", rs.next()); assertEquals("Invalid name", "Ivory", rs.getString(0)); assertTrue("Could not close result set", rs.close()); assertEquals("Could not close statement", Pluma.SQLITE_OK, statement.close()); } //endregion //region Functions @Test public void testFunctionFirstChar() throws Exception { mDatabase.registerFunction("FIRST_CHAR", 1, new SQLiteFunction() { @Override protected void run(int argc) { if (argc == 1) { final String text = getStringArg(0); if (text != null && text.length() > 0) { setStringResult(Character.toString(text.charAt(0))); return; } } setNullResult(); } }); final ResultSet resultSet = mDatabase.executeQuery("SELECT FIRST_CHAR(name) FROM people"); final String[] strings = {"J", "D", "R"}; int index = 0; while (resultSet.next()) { assertEquals("Unexpected result.", strings[index++], resultSet.getString(0)); } } @Test public void testFunctionThread() throws Exception { mDatabase.registerFunction("LAST_CHAR", 1, new SQLiteFunction() { @Override protected void run(int argc) { assertEquals("Unexpected thread", "PlumaTestThread", Thread.currentThread().getName()); if (argc == 1) { final String text = getStringArg(0); if (text != null && text.length() > 0) { setStringResult(Character.toString(text.charAt(text.length() - 1))); return; } } setNullResult(); } }); new Thread(new Runnable() { @Override public void run() { try { final ResultSet rs = mDatabase.executeQuery("SELECT LAST_CHAR(name) FROM people"); final String[] strings = {"y", "n", "e"}; int index = 0; while (rs.next()) { assertEquals("Unexpected result.", strings[index++], rs.getString(0)); } } catch (SQLiteException e) { throw new RuntimeException(e); } } }, "PlumaTestThread").start(); } //endregion //region Close @Test public void testClose() throws Exception { assertTrue("Database is not open.", mDatabase.isOpen()); assertTrue("Can not close database.", mDatabase.close()); assertTrue("Database is not closed.", mDatabase.isClosed()); } //endregion //region Get SQL @Test public void testGetSQL() throws Exception { final Statement statement = mDatabase.prepareStatement("INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)"); assertEquals("Statement SQL does not match", "INSERT INTO people (name, lastName, birth) VALUES (?, ?, ?)", statement.getSQL()); ResultSet rs = mDatabase.executeQuery("SELECT name FROM people WHERE id = ?", 2); assertEquals("ResultSet SQL does not match.", "SELECT name FROM people WHERE id = ?", rs.getSQL()); statement.close(); rs.close(); } //endregion //region Private private void startTest(String message) { QUERIES.clear(); System.out.println(message); } private void assertQueries(String... queries) { assertEquals("Unexpected queries count", queries.length, QUERIES.size()); for (int i = 0; i < queries.length; i++) { assertEquals("Unexpected query", queries[i].toLowerCase(), QUERIES.get(i).toLowerCase()); } } private void recordQuery(String query) { System.out.println(">>> " + query); QUERIES.add(query); } //endregion //region FTS @Test public void testCreateTable() throws Exception { String sql = "CREATE VIRTUAL TABLE _ftsProduct USING fts4(name, price, quantity, clientId, notindexed=clientId, tokenize=character)"; boolean result = mDatabase.executeUpdate(sql); assertTrue("Can create virtual table.", result); } //endregion }
package org.altbeacon.beacon.service.scanner; import android.annotation.TargetApi; import android.bluetooth.BluetoothAdapter; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.os.ParcelUuid; import android.os.SystemClock; import android.support.annotation.MainThread; import android.support.annotation.WorkerThread; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.logging.LogManager; import org.altbeacon.beacon.service.DetectionTracker; import org.altbeacon.bluetooth.BluetoothCrashResolver; import java.security.Security; import java.util.ArrayList; import java.util.List; @TargetApi(21) public class CycledLeScannerForLollipop extends CycledLeScanner { private static final String TAG = "CycledLeScannerForLollipop"; private static final long BACKGROUND_L_SCAN_DETECTION_PERIOD_MILLIS = 10000l; private BluetoothLeScanner mScanner; private ScanCallback leScanCallback; private long mBackgroundLScanStartTime = 0l; private long mBackgroundLScanFirstDetectionTime = 0l; private boolean mScanDeferredBefore = false; private boolean mMainScanCycleActive = false; private final BeaconManager mBeaconManager; public CycledLeScannerForLollipop(Context context, long scanPeriod, long betweenScanPeriod, boolean backgroundFlag, CycledLeScanCallback cycledLeScanCallback, BluetoothCrashResolver crashResolver) { super(context, scanPeriod, betweenScanPeriod, backgroundFlag, cycledLeScanCallback, crashResolver); mBeaconManager = BeaconManager.getInstanceForApplication(mContext); } @Override protected void stopScan() { postStopLeScan(); } /* Android 5 background scan algorithm (largely handled in this method) Same as pre-Android 5, except when on the between scan period. In this period: If a beacon has been seen in the past 10 seconds, don't do any scanning for the between scan period. Otherwise: - create hardware masks for any beacon regardless of identifiers - look for these hardware masks, and if you get one, report the detection when calculating the time to the next scan cycle, make it be on the seconds modulus of the between scan period plus the scan period This is an improvement over the current state, but the disadvantages are: - If a somebody else's beacon is present and yours is not yet visible when the app is in the background, you won't get the accelerated discovery. You only get the accelerated discovery if no beacons are visible before one of your regions appears. Getting around this would mean setting up filters that are specific to your monitored regions, which is a possible future improvement. - Once you are in your region, detecting when you go out of your region will still take until the next scan cycle starts, which by default is five minutes. So the bottom line is it works like this: - If no beacons at all are visible when your app enters the background, then a low-power scan will continue. - If any beacons are visible, even if they do not match a defined region, no background scanning will occur until the next between scan period expires (5 minutes by default) - If a beacon is subsequently detected during this low-power scan, it will start a 10-second background scanning period. At the end of this period, if the app is still in the background, then no beacons will be detected until the next scan cycle starts (5 minutes max by default) - If one of the beacons detected during this 10 second period matches a region you have defined, a region entry callback will be sent, allowing you to bring your app to the foreground to continue scanning if desired. - The effective result is that if no beacons are around, and then they are discovered, you will get a callback within a few seconds on Android L vs. up to 5 minutes on older operating system versions. */ protected boolean deferScanIfNeeded() { // This method is called to see if it is time to start a scan long millisecondsUntilStart = mNextScanCycleStartTime - SystemClock.elapsedRealtime(); if (millisecondsUntilStart > 0) { mMainScanCycleActive = false; long secsSinceLastDetection = SystemClock.elapsedRealtime() - DetectionTracker.getInstance().getLastDetectionTime(); // If we have seen a device recently // devices should behave like pre-Android L devices, because we don't want to drain battery // by continuously delivering packets for beacons visible in the background if (mScanDeferredBefore == false) { if (secsSinceLastDetection > BACKGROUND_L_SCAN_DETECTION_PERIOD_MILLIS) { mBackgroundLScanStartTime = SystemClock.elapsedRealtime(); mBackgroundLScanFirstDetectionTime = 0l; LogManager.d(TAG, "This is Android L. Doing a filtered scan for the background."); // On Android L, between scan cycles do a scan with a filter looking for any beacon // if we see one of those beacons, we need to deliver the results startScan(); } else { // TODO: Consider starting a scan with delivery based on the filters *NOT* being seen // This API is now available in Android M LogManager.d(TAG, "This is Android L, but we last saw a beacon only %s " + "ago, so we will not keep scanning in background.", secsSinceLastDetection); } } if (mBackgroundLScanStartTime > 0l) { // if we are in here, we have detected beacons recently in a background L scan if (DetectionTracker.getInstance().getLastDetectionTime() > mBackgroundLScanStartTime) { if (mBackgroundLScanFirstDetectionTime == 0l) { mBackgroundLScanFirstDetectionTime = DetectionTracker.getInstance().getLastDetectionTime(); } if (SystemClock.elapsedRealtime() - mBackgroundLScanFirstDetectionTime >= BACKGROUND_L_SCAN_DETECTION_PERIOD_MILLIS) { // if we are in here, it has been more than 10 seconds since we detected // a beacon in background L scanning mode. We need to stop scanning // so we do not drain battery LogManager.d(TAG, "We've been detecting for a bit. Stopping Android L background scanning"); stopScan(); mBackgroundLScanStartTime = 0l; } else { // report the results up the chain LogManager.d(TAG, "Delivering Android L background scanning results"); mCycledLeScanCallback.onCycleEnd(); } } } LogManager.d(TAG, "Waiting to start full Bluetooth scan for another %s milliseconds", millisecondsUntilStart); // Don't actually wait until the next scan time -- only wait up to 1 second. This // allows us to start scanning sooner if a consumer enters the foreground and expects // results more quickly. if (mScanDeferredBefore == false && mBackgroundFlag) { setWakeUpAlarm(); } mHandler.postDelayed(new Runnable() { @MainThread @Override public void run() { scanLeDevice(true); } }, millisecondsUntilStart > 1000 ? 1000 : millisecondsUntilStart); mScanDeferredBefore = true; return true; } else { if (mBackgroundLScanStartTime > 0l) { stopScan(); mBackgroundLScanStartTime = 0; } mScanDeferredBefore = false; mMainScanCycleActive = true; } return false; } @Override protected void startScan() { if (!isBluetoothOn()) { LogManager.d(TAG, "Not starting scan because bluetooth is off"); return; } List<ScanFilter> filters = new ArrayList<ScanFilter>(); ScanSettings settings; if (mBackgroundFlag && !mMainScanCycleActive) { LogManager.d(TAG, "starting filtered scan in SCAN_MODE_LOW_POWER"); settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build(); filters = new ScanFilterUtils().createScanFiltersForBeaconParsers( mBeaconManager.getBeaconParsers()); } else { LogManager.d(TAG, "starting non-filtered scan in SCAN_MODE_LOW_LATENCY"); settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)).build(); } postStartLeScan(filters, settings); } @Override protected void finishScan() { LogManager.d(TAG, "Stopping scan"); stopScan(); mScanningPaused = true; } private void postStartLeScan(final List<ScanFilter> filters, final ScanSettings settings) { final BluetoothLeScanner scanner = getScanner(); if (scanner == null) { return; } final ScanCallback scanCallback = getNewLeScanCallback(); mScanHandler.removeCallbacksAndMessages(null); mScanHandler.post(new Runnable() { @WorkerThread @Override public void run() { try { scanner.startScan(filters, settings, scanCallback); } catch (IllegalStateException e) { LogManager.w(TAG, "Cannot start scan. Bluetooth may be turned off."); } catch (NullPointerException npe) { LogManager.e(npe, TAG, "Cannot start scan. Unexpected NPE."); } catch (SecurityException e) { // Thrown by Samsung Knox devices if bluetooth access denied for an app LogManager.e(TAG, "Cannot start scan. Security Exception"); } } }); } private void postStopLeScan() { if (!isBluetoothOn()){ LogManager.d(TAG, "Not stopping scan because bluetooth is off"); return; } final BluetoothLeScanner scanner = getScanner(); if (scanner == null) { return; } final ScanCallback scanCallback = getNewLeScanCallback(); mScanHandler.removeCallbacksAndMessages(null); mScanHandler.post(new Runnable() { @WorkerThread @Override public void run() { try { LogManager.d(TAG, "Stopping LE scan on scan handler"); scanner.stopScan(scanCallback); } catch (IllegalStateException e) { LogManager.w(TAG, "Cannot stop scan. Bluetooth may be turned off."); } catch (NullPointerException npe) { LogManager.e(npe, TAG, "Cannot stop scan. Unexpected NPE."); } catch (SecurityException e) { // Thrown by Samsung Knox devices if bluetooth access denied for an app LogManager.e(TAG, "Cannot stop scan. Security Exception"); } } }); } private boolean isBluetoothOn() { try { BluetoothAdapter bluetoothAdapter = getBluetoothAdapter(); if (bluetoothAdapter != null) { return (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON); } LogManager.w(TAG, "Cannot get bluetooth adapter"); } catch (SecurityException e) { LogManager.w(TAG, "SecurityException checking if bluetooth is on"); } return false; } private BluetoothLeScanner getScanner() { try { if (mScanner == null) { LogManager.d(TAG, "Making new Android L scanner"); BluetoothAdapter bluetoothAdapter = getBluetoothAdapter(); if (bluetoothAdapter != null) { mScanner = getBluetoothAdapter().getBluetoothLeScanner(); } if (mScanner == null) { LogManager.w(TAG, "Failed to make new Android L scanner"); } } } catch (SecurityException e) { LogManager.w(TAG, "SecurityException making new Android L scanner"); } return mScanner; } private ScanCallback getNewLeScanCallback() { if (leScanCallback == null) { leScanCallback = new ScanCallback() { @MainThread @Override public void onScanResult(int callbackType, ScanResult scanResult) { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "got record"); List<ParcelUuid> uuids = scanResult.getScanRecord().getServiceUuids(); if (uuids != null) { for (ParcelUuid uuid : uuids) { LogManager.d(TAG, "with service uuid: "+uuid); } } } mCycledLeScanCallback.onLeScan(scanResult.getDevice(), scanResult.getRssi(), scanResult.getScanRecord().getBytes()); if (mBackgroundLScanStartTime > 0) { LogManager.d(TAG, "got a filtered scan result in the background."); } } @MainThread @Override public void onBatchScanResults(List<ScanResult> results) { LogManager.d(TAG, "got batch records"); for (ScanResult scanResult : results) { mCycledLeScanCallback.onLeScan(scanResult.getDevice(), scanResult.getRssi(), scanResult.getScanRecord().getBytes()); } if (mBackgroundLScanStartTime > 0) { LogManager.d(TAG, "got a filtered batch scan result in the background."); } } @MainThread @Override public void onScanFailed(int errorCode) { switch (errorCode) { case SCAN_FAILED_ALREADY_STARTED: LogManager.e( TAG, "Scan failed: a BLE scan with the same settings is already started by the app" ); break; case SCAN_FAILED_APPLICATION_REGISTRATION_FAILED: LogManager.e( TAG, "Scan failed: app cannot be registered" ); break; case SCAN_FAILED_FEATURE_UNSUPPORTED: LogManager.e( TAG, "Scan failed: power optimized scan feature is not supported" ); break; case SCAN_FAILED_INTERNAL_ERROR: LogManager.e( TAG, "Scan failed: internal error" ); break; default: LogManager.e( TAG, "Scan failed with unknown error (errorCode=" + errorCode + ")" ); break; } } }; } return leScanCallback; } }
package org.blockartistry.DynSurround.client.footsteps.system; import java.util.Locale; import java.util.Random; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.blockartistry.DynSurround.DSurround; import org.blockartistry.DynSurround.ModOptions; import org.blockartistry.DynSurround.client.ClientRegistry; import org.blockartistry.DynSurround.client.footsteps.implem.AcousticsManager; import org.blockartistry.DynSurround.client.footsteps.implem.ConfigOptions; import org.blockartistry.DynSurround.client.footsteps.implem.Variator; import org.blockartistry.DynSurround.client.footsteps.implem.Substrate; import org.blockartistry.DynSurround.client.footsteps.interfaces.EventType; import org.blockartistry.DynSurround.client.footsteps.interfaces.IAcoustic; import org.blockartistry.DynSurround.client.footsteps.interfaces.IOptions.Option; import org.blockartistry.DynSurround.client.handlers.EnvironStateHandler.EnvironState; import org.blockartistry.DynSurround.facade.FacadeHelper; import org.blockartistry.DynSurround.registry.ArmorClass; import org.blockartistry.lib.MCHelper; import org.blockartistry.lib.MyUtils; import org.blockartistry.lib.TimeUtils; import org.blockartistry.lib.WorldUtils; import org.blockartistry.lib.math.MathStuff; import org.blockartistry.lib.random.XorShiftRandom; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class Generator { protected static final Random RANDOM = XorShiftRandom.current(); protected static final IBlockState AIR_STATE = Blocks.AIR.getDefaultState(); protected final Isolator isolator; protected final Variator VAR; protected float dmwBase; protected float dwmYChange; protected double yPosition; protected boolean isFlying; protected float fallDistance; protected float lastReference; protected boolean isImmobile; protected long timeImmobile; protected boolean isRightFoot; protected double xMovec; protected double zMovec; protected boolean scalStat; protected boolean stepThisFrame; protected boolean isMessyFoliage; protected long brushesTime; // We calc our own because of inconsistencies with Minecraft protected double distanceWalkedOnStepModified; public Generator(@Nonnull final Isolator isolator, @Nonnull final Variator var) { this.isolator = isolator; this.VAR = var; } public void generateFootsteps(@Nonnull final EntityLivingBase entity) { simulateFootsteps(entity); simulateAirborne(entity); simulateBrushes(entity); if (ModOptions.footstepsSoundFactor > 0) entity.nextStepDistance = Integer.MAX_VALUE; else if (entity.nextStepDistance == Integer.MAX_VALUE) entity.nextStepDistance = 0; } protected boolean stoppedImmobile(float reference) { final long current = TimeUtils.currentTimeMillis(); final float diff = this.lastReference - reference; this.lastReference = reference; if (!this.isImmobile && diff == 0f) { this.timeImmobile = current; this.isImmobile = true; } else if (this.isImmobile && diff != 0f) { this.isImmobile = false; return current - timeImmobile > VAR.IMMOBILE_DURATION; } return false; } protected void updateWalkedOnStep(@Nonnull final EntityLivingBase entity) { final double dX = entity.posX - entity.prevPosX; final double dY = entity.posY - entity.prevPosY; final double dZ = entity.posZ - entity.prevPosZ; this.distanceWalkedOnStepModified += Math.sqrt(dX * dX + dY * dY + dZ * dZ); } protected void simulateFootsteps(@Nonnull final EntityLivingBase ply) { updateWalkedOnStep(ply); final float distanceReference = (float) this.distanceWalkedOnStepModified; // final float distanceReference = ply.distanceWalkedOnStepModified; this.stepThisFrame = false; if (this.dmwBase > distanceReference) { this.dmwBase = 0; this.dwmYChange = 0; } final double movX = ply.motionX; final double movZ = ply.motionZ; double scal = movX * this.xMovec + movZ * this.zMovec; if (this.scalStat != scal < 0.001f) { this.scalStat = !this.scalStat; if (this.scalStat && VAR.PLAY_WANDER && !this.hasSpecialStoppingConditions(ply)) { playSinglefoot(ply, 0d, EventType.WANDER, this.isRightFoot); } } this.xMovec = movX; this.zMovec = movZ; if (ply.onGround || ply.isInWater() || ply.isOnLadder()) { EventType event = null; float dwm = distanceReference - this.dmwBase; final boolean immobile = stoppedImmobile(distanceReference); if (immobile && !ply.isOnLadder()) { dwm = 0; this.dmwBase = distanceReference; } float distance = 0f; if (ply.isOnLadder() && !ply.onGround) { distance = VAR.STRIDE_LADDER; } else if (!ply.isInWater() && MathStuff.abs(this.yPosition - ply.posY) > 0.4d) { // This ensures this does not get recorded as landing, but as a // step if (this.yPosition < ply.posY) { // Going upstairs distance = VAR.STRIDE_STAIR; event = speedDisambiguator(ply, EventType.UP, EventType.UP_RUN); } else if (!ply.isSneaking()) { // Going downstairs distance = -1f; event = speedDisambiguator(ply, EventType.DOWN, EventType.DOWN_RUN); } this.dwmYChange = distanceReference; } else { distance = VAR.STRIDE; } if (event == null) { event = speedDisambiguator(ply, EventType.WALK, EventType.RUN); } distance = reevaluateDistance(event, distance); if (dwm > distance) { produceStep(ply, event, 0F); stepped(ply, event); this.dmwBase = distanceReference; } } // This fixes an issue where the value is evaluated // while the player is between two steps in the air // while descending stairs if (ply.onGround) { this.yPosition = ply.posY; } } protected void stepped(@Nonnull final EntityLivingBase ply, @Nonnull final EventType event) { } protected float reevaluateDistance(@Nonnull final EventType event, final float distance) { return distance; } protected void produceStep(@Nonnull final EntityLivingBase ply, @Nonnull final EventType event) { produceStep(ply, event, 0d); } protected void produceStep(@Nonnull final EntityLivingBase ply, @Nullable EventType event, final double verticalOffsetAsMinus) { if (!this.playSpecialStoppingConditions(ply)) { if (event == null) event = speedDisambiguator(ply, EventType.WALK, EventType.RUN); playSinglefoot(ply, verticalOffsetAsMinus, event, this.isRightFoot); this.isRightFoot = !this.isRightFoot; } this.stepThisFrame = true; } protected void simulateAirborne(@Nonnull final EntityLivingBase ply) { if ((ply.onGround || ply.isOnLadder()) == this.isFlying) { this.isFlying = !this.isFlying; simulateJumpingLanding(ply); } if (this.isFlying) this.fallDistance = ply.fallDistance; } protected void simulateJumpingLanding(@Nonnull final EntityLivingBase ply) { if (this.hasSpecialStoppingConditions(ply)) return; final boolean isJumping = ply.isJumping; if (this.isFlying && isJumping) { // ply.isJumping) if (VAR.EVENT_ON_JUMP) { double speed = ply.motionX * ply.motionX + ply.motionZ * ply.motionZ; if (speed < VAR.SPEED_TO_JUMP_AS_MULTIFOOT) { // STILL JUMP playMultifoot(ply, 0.4d, EventType.JUMP); // 0.7531999805212d // (magic number // for vertical // offset?) } else { playSinglefoot(ply, 0.4d, EventType.JUMP, this.isRightFoot); // RUNNING // JUMP // Do not toggle foot: After landing sounds, the first foot // will be same as the one used to jump. } } } else if (!this.isFlying) { if (this.fallDistance > VAR.LAND_HARD_DISTANCE_MIN) { playMultifoot(ply, 0d, EventType.LAND); // Always assume the // player lands on their // two feet // Do not toggle foot: After landing sounds, the first foot will // be same as the one used to jump. } else if (!this.stepThisFrame && !ply.isSneaking()) { playSinglefoot(ply, 0d, speedDisambiguator(ply, EventType.CLIMB, EventType.CLIMB_RUN), this.isRightFoot); this.isRightFoot = !this.isRightFoot; } } } protected EventType speedDisambiguator(@Nonnull final EntityLivingBase ply, @Nonnull final EventType walk, @Nonnull final EventType run) { final double velocity = ply.motionX * ply.motionX + ply.motionZ * ply.motionZ; return velocity > VAR.SPEED_TO_RUN ? run : walk; } protected void simulateBrushes(@Nonnull final EntityLivingBase ply) { final long current = TimeUtils.currentTimeMillis(); if (this.brushesTime > current) return; this.brushesTime = current + 100; if ((ply.motionX == 0d && ply.motionZ == 0d) || ply.isSneaking()) return; final int yy = MathStuff.floor(ply.posY - 0.1d - ply.getYOffset() - (ply.onGround ? 0d : 0.25d)); final Association assos = this.findAssociationMessyFoliage(new BlockPos(ply.posX, yy, ply.posZ)); if (assos != null) { if (!this.isMessyFoliage) { this.isMessyFoliage = true; this.playAssociation(ply, assos, EventType.WALK); } } else { this.isMessyFoliage = false; } } protected void playSinglefoot(@Nonnull final EntityLivingBase ply, final double verticalOffsetAsMinus, @Nonnull final EventType eventType, final boolean foot) { final Association assos = this.findAssociationForPlayer(ply, verticalOffsetAsMinus, foot); this.playAssociation(ply, assos, eventType); } protected void playMultifoot(@Nonnull final EntityLivingBase ply, final double verticalOffsetAsMinus, final EventType eventType) { // STILL JUMP final Association leftFoot = this.findAssociationForPlayer(ply, verticalOffsetAsMinus, false); final Association rightFoot = this.findAssociationForPlayer(ply, verticalOffsetAsMinus, true); this.playAssociation(ply, leftFoot, eventType); this.playAssociation(ply, rightFoot, eventType); } protected float scalex(final float number, final float min, final float max) { return MathStuff.clamp((number - min) / (max - min), 0.0F, 1.0F); } /* * Former Solver code moved into Generator. */ /** * Play an association. */ protected void playAssociation(@Nonnull final EntityLivingBase ply, @Nullable final Association assos, @Nonnull final EventType eventType) { if (assos != null && !assos.isNotEmitter()) { if (assos.getNoAssociation()) { this.isolator.getDefaultStepPlayer().playStep(ply, assos); } else { this.isolator.getAcoustics().playAcoustic(ply, assos, eventType); } } } protected boolean hasFootstepImprint(@Nullable final IBlockState state, @Nonnull final BlockPos pos) { if (state != null) { final IBlockState footstepState = FacadeHelper.resolveState(state, EnvironState.getWorld(), pos, EnumFacing.UP); return ClientRegistry.FOOTSTEPS.hasFootprint(footstepState); } return false; } protected boolean hasFootstepImprint(@Nonnull final Vec3d pos) { // Check the block above to see if it has a footprint. Intended to handle things // like snow on stone. BlockPos blockPos = new BlockPos(pos).up(); IBlockState state = WorldUtils.getBlockState(EnvironState.getWorld(), blockPos); if (state != null && hasFootstepImprint(state, blockPos)) return true; // If the block above blocks movement then it's not possible to lay // down a footprint. if (state.getMaterial().blocksMovement()) return false; // Check the requested block blockPos = new BlockPos(pos); state = WorldUtils.getBlockState(EnvironState.getWorld(), blockPos); if (state != null) { return hasFootstepImprint(state, blockPos); } return false; } /** * Find an association for a player particular foot. This will fetch the player * angle and use it as a basis to find out what block is below their feet (or * which block is likely to be below their feet if the player is walking on the * edge of a block when walking over non-emitting blocks like air or water).<br> * <br> * Returns null if no blocks are valid emitting blocks.<br> * Returns a string that begins with "_NO_ASSOCIATION" if a matching block was * found, but has no association in the blockmap. */ @Nonnull protected Association findAssociationForPlayer(@Nonnull final EntityLivingBase player, final double verticalOffsetAsMinus, final boolean isRightFoot) { // Moved from routine below - why do all this calculation just to toss // it away if (MathStuff.abs(player.motionY) < 0.02) return null; // Don't play sounds on every tiny bounce final float rotDegrees = MathStuff.wrapDegrees(player.rotationYaw); final double rot = MathStuff.toRadians(rotDegrees); final double xn = MathStuff.cos(rot); final double zn = MathStuff.sin(rot); final float feetDistanceToCenter = 0.2f * (isRightFoot ? -1 : 1); final double xx = player.posX + xn * feetDistanceToCenter; final double minY = player.getEntityBoundingBox().minY; final double zz = player.posZ + zn * feetDistanceToCenter; final BlockPos pos = new BlockPos(xx, minY - 0.1D - verticalOffsetAsMinus, zz); final Association result = addSoundOverlay(player, findAssociationForLocation(player, pos)); if (result != null && !player.isJumping) { final Vec3d printLocation = new Vec3d(xx, minY, zz); if (hasFootstepImprint(printLocation.addVector(0D, -0.5D, 0D))) result.generatePrint(player, printLocation, rotDegrees, isRightFoot); } return result; } /** * Find an association for a player, and a location. This will try to find the * best matching block on that location, or near that location, for instance if * the player is walking on the edge of a block when walking over non-emitting * blocks like air or water)<br> * <br> * Returns null if no blocks are valid emitting blocks.<br> * Returns a string that begins with "_NO_ASSOCIATION" if a matching block was * found, but has no association in the blockmap. */ @Nonnull protected Association findAssociationForLocation(@Nonnull final EntityLivingBase player, @Nonnull final BlockPos pos) { final World world = player.getEntityWorld(); if (player.isInWater()) DSurround.log().debug( "WARNING!!! Playing a sound while in the water! This is supposed to be halted by the stopping conditions!!"); Association worked = findAssociationForBlock(world, pos); // If it didn't work, the player has walked over the air on the border // of a block. // | o | < player is here // wool | air | // V z if (worked == null) { // Create a trigo. mark contained inside the block the player is // over double xdang = (player.posX - pos.getX()) * 2 - 1; double zdang = (player.posZ - pos.getZ()) * 2 - 1; // -1 0 1 // | + | 0 --> x // V z // If the player is at the edge of that if (Math.max(MathStuff.abs(xdang), MathStuff.abs(zdang)) > 0.2f) { // Find the maximum absolute value of X or Z boolean isXdangMax = MathStuff.abs(xdang) > MathStuff.abs(zdang); // < maxofX- maxofX+ > // Take the maximum border to produce the sound if (isXdangMax) { // If we are in the positive border, add 1, // else subtract 1 worked = findAssociationForBlock(world, xdang > 0 ? pos.east() : pos.west()); } else { worked = findAssociationForBlock(world, zdang > 0 ? pos.south() : pos.north()); } // If that didn't work, then maybe the footstep hit in the // direction of walking // Try with the other closest block if (worked == null) { // Take the maximum direction and try with // the orthogonal direction of it if (isXdangMax) { worked = findAssociationForBlock(world, zdang > 0 ? pos.south() : pos.north()); } else { worked = findAssociationForBlock(world, xdang > 0 ? pos.east() : pos.west()); } } } } return worked; } /** * Find an association for a certain block assuming the player is standing on * it. This will sometimes select the block above because some block act like * carpets. This also applies when the block targeted by the location is * actually not emitting, such as lilypads on water.<br> * <br> * Returns null if the block is not a valid emitting block (this causes the * engine to continue looking for valid blocks). This also happens if the carpet * is non-emitting.<br> * Returns a string that begins with "_NO_ASSOCIATION" if the block is valid, * but has no association in the blockmap. If the carpet was selected, this * solves to the carpet. */ @Nonnull protected Association findAssociationForBlock(@Nonnull final World world, @Nonnull BlockPos pos) { IBlockState in = WorldUtils.getBlockState(world, pos); BlockPos tPos = pos.up(); final IBlockState above = WorldUtils.getBlockState(world, tPos); IAcoustic[] association = null; if (above != AIR_STATE) association = ClientRegistry.FOOTSTEPS.getBlockMap().getBlockSubstrateAcoustics(world, above, tPos, Substrate.CARPET); if (association == null || association == AcousticsManager.NOT_EMITTER) { // This condition implies that if the carpet is NOT_EMITTER, solving // will CONTINUE with the actual block surface the player is walking // on NOT_EMITTER carpets will not cause solving to skip if (in == AIR_STATE) { tPos = pos.down(); final IBlockState below = WorldUtils.getBlockState(world, tPos); association = ClientRegistry.FOOTSTEPS.getBlockMap().getBlockSubstrateAcoustics(world, below, tPos, Substrate.FENCE); if (association != null) { pos = tPos; in = below; DSurround.log().debug("Fence detected"); } } if (association == null) { association = ClientRegistry.FOOTSTEPS.getBlockMap().getBlockAcoustics(world, in, pos); } if (association != null && association != AcousticsManager.NOT_EMITTER) { // This condition implies that foliage over a NOT_EMITTER block // CANNOT PLAY This block most not be executed if the // association // is a carpet => this block of code is here, not outside this // if else group. if (above != AIR_STATE) { IAcoustic[] foliage = ClientRegistry.FOOTSTEPS.getBlockMap().getBlockSubstrateAcoustics(world, above, pos.up(), Substrate.FOLIAGE); if (foliage != null && foliage != AcousticsManager.NOT_EMITTER) { association = MyUtils.concatenate(association, foliage); DSurround.log().debug("Foliage detected"); } } } } else { pos = tPos; in = above; DSurround.log().debug("Carpet detected"); } if (association != null) { if (association == AcousticsManager.NOT_EMITTER) { // if (in.getBlock() != Blocks.air) { // air block // PFLog.debugf("Not emitter for %0 : %1", in); return null; // Player has stepped on a non-emitter block as // defined in the blockmap } else { // PFLog.debugf("Found association for %0 : %1 : %2", in, // association); return new Association(in, pos, association); } } else { IAcoustic[] primitive = resolvePrimitive(in); if (primitive != null) { if (primitive == AcousticsManager.NOT_EMITTER) { // PFLog.debugf("Primitive for %0 : %1 : %2 is NOT_EMITTER! // Following behavior is uncertain.", in, primitive); return null; } // PFLog.debugf("Found primitive for %0 : %1 : %2", in, // primitive); return new Association(in, pos, primitive); } else { // PFLog.debugf("No association for %0 : %1", in); return new Association(in, pos); } } } @Nonnull protected IAcoustic[] resolvePrimitive(@Nonnull final IBlockState state) { if (state == AIR_STATE) return AcousticsManager.NOT_EMITTER; final SoundType type = MCHelper.getSoundType(state); if (type == null) return AcousticsManager.NOT_EMITTER; final String soundName; boolean flag = false; if (type.getStepSound() == null || type.getStepSound().getSoundName().getResourcePath().isEmpty()) { soundName = "UNDEFINED"; flag = true; } else soundName = type.getStepSound().getSoundName().toString(); final String substrate = String.format(Locale.ENGLISH, "%.2f_%.2f", type.getVolume(), type.getPitch()); // Check for primitive in register IAcoustic[] primitive = this.isolator.getPrimitiveMap().getPrimitiveMapSubstrate(soundName, substrate); if (primitive == null) { if (flag) { primitive = this.isolator.getPrimitiveMap().getPrimitiveMapSubstrate(soundName, "break_" + soundName); // Check // sound } if (primitive == null) { primitive = this.isolator.getPrimitiveMap().getPrimitiveMap(soundName); } } if (primitive != null) { DSurround.log().debug("Primitive found for %s: %s", soundName, substrate); return primitive; } DSurround.log().debug("No primitive for %s: %s", soundName, substrate); return null; } /** * Play special sounds that must stop the usual footstep figuring things out * process. */ protected boolean playSpecialStoppingConditions(@Nonnull final EntityLivingBase ply) { if (ply.isInWater()) { final float volume = (float) MathStuff .sqrt(ply.motionX * ply.motionX + ply.motionY * ply.motionY + ply.motionZ * ply.motionZ) * 1.25F; final ConfigOptions options = new ConfigOptions(); options.getMap().put(Option.GLIDING_VOLUME, volume > 1 ? 1 : volume); // material water, see EntityLivingBase line 286 this.isolator.getAcoustics().playAcoustic(ply, AcousticsManager.SWIM, ply.isInsideOfMaterial(Material.WATER) ? EventType.SWIM : EventType.WALK, options); return true; } return false; } /** * Tells if footsteps can be played. */ protected boolean hasSpecialStoppingConditions(@Nonnull final EntityLivingBase ply) { return ply.isInWater(); } /** * Find an association for a certain block assuming the player is standing on * it, using a custom strategy which strategies are defined by the solver. */ @Nonnull protected Association findAssociationMessyFoliage(@Nonnull final BlockPos pos) { final World world = EnvironState.getWorld(); final BlockPos up = pos.up(); final IBlockState above = WorldUtils.getBlockState(world, up); if (above == AIR_STATE) return null; IAcoustic[] association = null; boolean found = false; // Try to see if the block above is a carpet... /* * String association = this.isolator.getBlockMap().getBlockMapSubstrate( * PF172Helper.nameOf(xblock), xmetadata, "carpet"); * * if (association == null || association.equals("NOT_EMITTER")) { // This * condition implies that // if the carpet is NOT_EMITTER, solving will CONTINUE * with the actual // block surface the player is walking on // > NOT_EMITTER * carpets will not cause solving to skip * * // Not a carpet association = * this.isolator.getBlockMap().getBlockMap(PF172Helper.nameOf(block), metadata); * * if (association != null && !association.equals("NOT_EMITTER")) { // This * condition implies that // foliage over a NOT_EMITTER block CANNOT PLAY * * // This block most not be executed if the association is a carpet // => this * block of code is here, not outside this if else group. */ IAcoustic[] foliage = ClientRegistry.FOOTSTEPS.getBlockMap().getBlockSubstrateAcoustics(world, above, up, Substrate.FOLIAGE); if (foliage != null && foliage != AcousticsManager.NOT_EMITTER) { // we discard the normal block association, and mark the foliage as // detected // association = association + "," + foliage; association = foliage; IAcoustic[] isMessy = ClientRegistry.FOOTSTEPS.getBlockMap().getBlockSubstrateAcoustics(world, above, up, Substrate.MESSY); if (isMessy != null && isMessy == AcousticsManager.MESSY_GROUND) found = true; } /* * } // else { the information is discarded anyways, the method returns null or * no association } } else // Is a carpet return null; */ if (found && association != null) { return association == AcousticsManager.NOT_EMITTER ? null : new Association(association); } return null; } /** * Adds additional sound overlays to the acoustic based on other environment * aspects, such as armor being worn. */ @Nonnull protected Association addSoundOverlay(@Nonnull final EntityLivingBase entity, @Nullable Association assoc) { final ArmorClass armor; final ArmorClass foot; if (EnvironState.isPlayer(entity)) { armor = EnvironState.getPlayerArmorClass(); foot = EnvironState.getPlayerFootArmorClass(); } else { armor = ArmorClass.effectiveArmorClass(entity); foot = ArmorClass.footArmorClass(entity); } final IAcoustic armorAddon = this.isolator.getAcoustics().getAcoustic(armor.getAcoustic()); IAcoustic footAddon = this.isolator.getAcoustics().getAcoustic(foot.getFootAcoustic()); if (armorAddon == null && footAddon == null) return assoc; // Eliminate duplicates if (armorAddon == footAddon) footAddon = null; if (assoc == null) assoc = new Association(); if (armorAddon != null) assoc.add(armorAddon); if (footAddon != null) assoc.add(footAddon); return assoc; } }
package org.mskcc.cgds.scripts; import java.io.*; import java.util.*; /** * * Given expression and CNV data for a set of samples (patients), generate normalized expression values. * Currently the input must be TCGA data, with samples identified by TCGA barcode identifiers. * * Each gene is normalized separately. First, the expression distribution for unaltered copies of the * gene is estimated by calculating the mean and variance of the expression values for samples in which * the gene is diploid (as reported by the CNV data). We call this the unaltered distribution. * * If the gene has no diploid samples, then its normalized expression is reported as NA. * Otherwise, for every sample, the gene's normalized expression is reported as * * (r - mu)/sigma * * where r is the raw expression value, and mu and sigma are the mean and standard deviation * of the unaltered distribution, respectively. * * The syntax is simple: * * java ComputeZscoreUnit <copy_number_file> <expression_file> <output_file> [<min_number_of_diploids>] * * The output is written onto a file named "output_file" * * Any number of columns may precede the data. However, the following must be satisfied: * * - the first column provides gene identifiers * - sample names start with the "TCGA" prefix * * Algorithm * Input copy number (CNA) and expression (exp) files * concept: * for each gene{ * identify diploid cases in CNA * obtain mean and sd of exp of diploid cases * for each case{ * zScore <- (value - mean)/sd * } * } * * implementation: * read CNA: build hash geneCopyNumberStatus: gene -> Array of (caseID, value ) pairs * read exp: skip normal cases; * for each gene{ * get mean and s.d. of elements of diploids * get zScore for each case * } * * @author Giovanni Ciriello * @author Arthur Goldberg goldberg@cbio.mskcc.org * */ public class ComputeZScoreUnit{ static HashMap<String, ArrayList<String[]>> geneCopyNumberStatus; static int SAMPLES; static String zScoresFile; static String SampleNamePrefix = "TCGA"; static final int DEFAULT_MIN_NUM_DIPLOIDS = 10; static int MIN_NUM_DIPLOIDS = DEFAULT_MIN_NUM_DIPLOIDS; static final int MIN_NUM_ALLOWED_DIPLOIDS = 3; public static void main (String[]args){ // TODO, perhaps: use command line parser if( args.length != 3 && args.length != 4){ fatalError( "incorrect number of arguments. Arguments should be '<copy_number_file> <expression_file> <output_file> [<min_number_of_diploids>]'." ); } String copyNumberFile = args[0]; String expressionFile = args[1]; zScoresFile = args[2]; if( args.length == 4){ try { MIN_NUM_DIPLOIDS = Integer.parseInt(args[3] ); } catch (NumberFormatException e) { fatalError( "incorrect arguments. 'min_number_of_diploids', was entered as " + args[3] + " but must be an integer." ); } if( MIN_NUM_DIPLOIDS < MIN_NUM_ALLOWED_DIPLOIDS ){ fatalError( "incorrect arguments. 'min_number_of_diploids', was entered as " + args[3] + " but must be at least " + MIN_NUM_ALLOWED_DIPLOIDS + "." ); } } geneCopyNumberStatus = readCopyNumberFile(copyNumberFile); computeZScoreXP(expressionFile); } private static void computeZScoreXP(String file){ BufferedReader in = null; PrintWriter out = null; String NOT_AVAILABLE = "NA"; try { out = new PrintWriter(new FileWriter( zScoresFile )); } catch (IOException e) { fatalError( "cannot open <output_file> '" + zScoresFile + "' for writing."); } try { in = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { fatalError( "cannot read <expression_file> in '" + file + "'."); } String header; try { header = in.readLine(); String[]values = header.split("\t"); int firstSamplePosition = getFirstDataColumn( values ); // catch error if no sample id contains SampleNamePrefix if( NO_POSITION == firstSamplePosition ){ fatalError( "no sample id contains " + SampleNamePrefix + " in <expression_file>, '" + file + "'."); } SAMPLES = values.length;// - firstSamplePosition; String[]samples = new String[SAMPLES]; // the names of all samples HashSet<String> normalSamples = new HashSet<String>(); // make set of case IDs of normal samples, and list of all truncated samples for(int i=firstSamplePosition; i<SAMPLES; i++){ if(isNormal(values[i])){ normalSamples.add(truncatedSampleName(values[i])); } samples[i] = truncatedSampleName(values[i]); } ArrayList<String> outputLine = new ArrayList<String>(); // header contains only ids of tumor samples outputLine.add("GeneSymbol"); for(int i=firstSamplePosition;i<samples.length;i++) if(!normalSamples.contains(samples[i])) outputLine.add(samples[i]); out.println( join( outputLine, "\t") ); // SAMPLES is number of tumors SAMPLES = SAMPLES-normalSamples.size()-firstSamplePosition; System.out.println(file+")\t"+SAMPLES+" SAMPLES ("+normalSamples.size()+" normals)"); // discards second line from expr file: it should be: "Composite Element REF signal ... " // TODO: check that 2nd line does not contain data in.readLine(); String line; int genes = 0; int genesWithValidScores = 0; int genesFound=0; int rowsWithSomeDiploidCases = 0; // process expression file while((line = in.readLine())!=null){ values = line.split("\t"); String id = values[0]; // gene identifier in 1st column // ignore gene's data if its copy number status is unknown if(geneCopyNumberStatus.containsKey(id)){ genesFound++; ArrayList<String[]> tumorSampleExpressions = new ArrayList<String[]>(); for(int i=firstSamplePosition;i<values.length;i++){ if(!normalSamples.contains(samples[i])){ String[] p = new String[2]; p[0] = samples[i]; p[1] = values[i]; tumorSampleExpressions.add(p); } } ArrayList<String[]> cnStatus = geneCopyNumberStatus.get(id); double[] zscores = getZscore( id, tumorSampleExpressions, cnStatus ); if(zscores != null){ rowsWithSomeDiploidCases++; outputLine.clear(); outputLine.add(id); for(int k =0;k<zscores.length;k++) // Double.NaN indicates an invalid expression value if(zscores[k] != Double.NaN){ // limit precision outputLine.add( String.format( "%.4f", zscores[k] ) ); }else{ outputLine.add( NOT_AVAILABLE ); } out.println( join( outputLine, "\t") ); genesWithValidScores++; }else{ outputLine.clear(); outputLine.add(id); for(int k =0;k<SAMPLES;k++) outputLine.add( NOT_AVAILABLE ); out.println( join( outputLine, "\t") ); } genes++; }else{ outputLine.clear(); outputLine.add(id); for(int k =0;k<SAMPLES;k++) outputLine.add( NOT_AVAILABLE ); out.println( join( outputLine, "\t") ); } } if( 0 == genesFound ){ fatalError( "none of the genes in the expression file '" + file + "' were in the copy number file." ); } if( 0 == rowsWithSomeDiploidCases ){ fatalError( "no genes with at least " + MIN_NUM_DIPLOIDS + " diploid cases found. Check copy number file." ); } } catch (IOException e) { fatalError( "cannot read from <expression_file> in '" + file + "'."); } out.close(); } static int NO_POSITION = -1; private static int getFirstDataColumn( String[] values){ int tmp = NO_POSITION; search: for(int i=0;i<values.length;i++) if(values[i].indexOf(SampleNamePrefix) != -1){ tmp = i; break search; } return tmp; } /** * Given expression and copy number data for a set of cases for one gene * return array of z-Scores for the expression data. * * @param exp ArrayList of String[] = [ sampleID, expression ] * @param cn ArrayList< [sampleID, copyNumber] > * @return array of z-Scores for the expression data; null if there were no diploid values */ private static double[] getZscore(String id, ArrayList<String[]> xp, ArrayList<String[]> cn){ double[] z = null; double[] diploid = new double[SAMPLES]; HashSet<String> diploidSamples = new HashSet<String>(); String DiploidSample = "0"; // CN value of 0 indicates diploid for(int i=0;i<cn.size();i++){ if(cn.get(i)[1].equals( DiploidSample )) diploidSamples.add(cn.get(i)[0]); // entry [0] is the sampleID; TODO: put in a named record (class) } int xPos = 0; int count = 0; // for each expression measurement for(int i=0;i<xp.size();i++){ // if the sample is diploid if(diploidSamples.contains(xp.get(i)[0])){ count++; // and the expression value is not NA or NaN or null if(xp.get(i)[1].compareTo("NA")!=0 && xp.get(i)[1].compareTo("NaN")!=0 && xp.get(i)[1].compareTo("null")!=0){ // then add the measurement to the array of diploid values try { diploid[xPos++] = Double.parseDouble(xp.get(i)[1]); } catch (NumberFormatException e) { fatalError( "expression value '" + xp.get(i)[1] + "' for gene " + id + " in sample " + xp.get(i)[0] + " is not a floating point number." ); } } } } // make sure there are enough diploid values to normalize to the distribution // perhaps TODO: also make sure that the distribution of diploids is close enough to normal if( MIN_NUM_DIPLOIDS <= xPos ){ // remove empty elements at end of diploid diploid = resize(diploid,xPos); // get mean and s.d. of elements of diploid double avg = avg(diploid); double std = std(diploid, avg); // create an array of z-Scores // do not compute z-Score if std == 0 // TODO: use some minimum threshold for std if( 0.0d < std ){ z = getZ(id, xp, avg, std); } } return z; } public static double[] getZ(String id, ArrayList<String[]> xp, double avg, double std){ double[]z = new double[xp.size()]; if( 0.0d == std){ // this should not happen fatalError( "cannot normalize relative to distribution with standard deviation of 0.0." ); } for(int i=0;i<xp.size();i++){ if(xp.get(i)[1].compareTo("NA")!=0 && xp.get(i)[1].compareTo("NaN")!=0 && xp.get(i)[1].compareTo("null")!=0){ double s; try { s = Double.parseDouble(xp.get(i)[1]); s = s - avg; s = s/std; z[i] = s; } catch (NumberFormatException e) { fatalError( "expression value '" + xp.get(i)[1] + "' for gene " + id + " in sample " + xp.get(i)[0] + " is not a floating point number." ); } } else z[i] = Double.NaN; } return z; } /** * Read the copy number file and generate copy number status table * returns: HashMap<String,ArrayList<String[]>> that * maps geneName -> ArrayList< [ sampleName, value ] > */ public static HashMap<String,ArrayList<String[]>> readCopyNumberFile(String file){ HashMap<String,ArrayList<String[]>> map = new HashMap<String,ArrayList<String[]>>(); BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { fatalError( "cannot open copy number file '" + file + "' for reading."); } // assumes single header line String header; try { header = in.readLine(); String[]values = header.split("\t"); int firstSamplePosition = getFirstDataColumn( values ); // error if no sample id contains SampleNamePrefix if( NO_POSITION == firstSamplePosition ){ fatalError( "no sample id contains " + SampleNamePrefix + " in <CopyNumberFile>, '" + file + "'."); } SAMPLES = values.length; // - firstSamplePosition; String[]samples = new String[SAMPLES]; HashSet<String> tempSamplesNames = new HashSet<String>(); for(int i=firstSamplePosition;i<SAMPLES;i++){ samples[i] = truncatedSampleName(values[i]); // error if sample name is duplicated in CNV file if( tempSamplesNames.contains(samples[i] ) ){ fatalError( "multiple columns with same truncated sample id of " + samples[i] + " in <CopyNumberFile>, '" + file + "'."); } tempSamplesNames.add( samples[i] ); } System.out.println(file+")\t"+(SAMPLES-firstSamplePosition)+" SAMPLES"); String line; while((line=in.readLine())!=null){ values = line.split("\t"); String id = values[0]; if(!map.containsKey(id)){ ArrayList<String[]> tmp = new ArrayList<String[]>(); for(int i = firstSamplePosition;i<values.length;i++){ String[] p = new String[2]; p[0] = samples[i]; p[1] = values[i]; tmp.add(p); } map.put(id,tmp); }else{ // remove duplicate ids, and report a warning // TODO: this is a subtle bug; if a gene appears an even number of times in the input, then it doesn't appear in the output; // if it appears an odd number, then the last one appears in the output; fix by creating a list of dupes map.remove(id); warning( "duplicate entry for gene " + id + " in <CopyNumberFile>, '" + file + "'."); } } System.out.println(file+")\t"+ map.size() +" GENES"); if( map.size() == 0 ){ fatalError( "no gene IDs in copy number file '" + file + "'."); } } catch (IOException e) { fatalError( "cannot read copy number file '" + file + "'."); } return map; } /** * Return the truncated version of a TCGA sample name */ private static String truncatedSampleName(String name){ String truncatedName = ""; int dash = 0; for(int i=0;i<name.length();i++){ if(name.charAt(i)=='-') dash++; if(dash == 3) return truncatedName; else truncatedName=truncatedName+name.charAt(i); } return truncatedName; } /** * Check if a sample name corresponds to normal samples * I.e., tests for normal tissue samples in TCGA case ID barcodes # The main parts of the barcode are TCGA-xx-xxxx-xxx-xxx-xxxx-xx # (1)-(2)-(3)-(4)(5)-(6)(7)-(8)-(9) # ... # (4) Sample Type = e.g. solid tumor (01) or normal blood (10) # ... # # The different sample types for (4) are: # ... # 11 normal tissue (not always matched to a cancer patient, used for mRNA, microRNA, methylation) */ public static boolean isNormal(String name){ String suffix = ""; int dash = 0; search: for(int i=0;i<name.length();i++){ if(name.charAt(i)=='-') dash++; if(dash == 3){ suffix = name.substring(i,name.length()); break search; } } if(suffix.indexOf("-11") == 0 ) return true; return false; } private static double avg(double[]v){ double avg = 0; for(int i=0;i<v.length;i++) avg=avg+v[i]; avg=avg/(double)v.length; return avg; } private static double std(double[]v,double avg){ double std = 0; for(int i=0;i<v.length;i++) std=std+Math.pow((v[i]-avg),2); std=std/(double)(v.length-1); std=Math.sqrt(std); return std; } private static double[] resize(double[]v, int s){ double[]tmp = new double[s]; for(int i=0;i<s;i++) tmp[i]=v[i]; return tmp; } private static void fatalError(String msg){ System.err.println( "ComputeZScoreUnit: Fatal error: " + msg ); System.exit(1); } private static void warning(String msg){ System.err.println( "ComputeZScoreUnit: " + msg ); } public static String join(Collection<String> s, String delimiter) { if (s.isEmpty()) return ""; Iterator<String> iter = s.iterator(); StringBuffer buffer = new StringBuffer(iter.next()); while (iter.hasNext()) buffer.append(delimiter).append(iter.next()); return buffer.toString(); } }
package com.winterwell.utils.io; import java.io.InputStream; import java.io.ObjectInputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.math.BigInteger; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Entity; import com.winterwell.utils.IFn; import com.winterwell.utils.Printer; import com.winterwell.utils.Proc; import com.winterwell.utils.ReflectionUtils; import com.winterwell.utils.StrUtils; import com.winterwell.utils.TodoException; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.ArrayMap; import com.winterwell.utils.containers.Cache; import com.winterwell.utils.containers.Containers; import com.winterwell.utils.containers.Pair; import com.winterwell.utils.io.DBUtils.DBOptions; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.Dt; import com.winterwell.utils.time.TUnit; import com.winterwell.utils.time.Time; import com.winterwell.utils.time.TimeUtils; class RSIterator implements Iterator<Object[]> { private int cols; private Boolean hasNext; private final ResultSet rs; private Runnable closeFn; public RSIterator(ResultSet rs, Runnable closeFn) { assert rs != null; this.rs = rs; this.closeFn = closeFn; try { cols = rs.getMetaData().getColumnCount(); } catch (SQLException e) { throw Utils.runtime(e); } } private void advanceIfNeeded() { if (hasNext != null) return; try { hasNext = rs.next(); // Close? if (!hasNext && closeFn != null) { rs.close(); closeFn.run(); } } catch (SQLException e) { throw Utils.runtime(e); } } @Override public boolean hasNext() { // handle repeated calls without repeated advances advanceIfNeeded(); return hasNext; } @Override public Object[] next() { // do we need to advance? Not if #hasNext() was called just before advanceIfNeeded(); // Either next or hasNext will now trigger an advance hasNext = null; try { Object[] row = new Object[cols]; for (int i = 0; i < row.length; i++) { row[i] = rs.getObject(i + 1); // not zero indexed } return row; } catch (SQLException e) { throw Utils.runtime(e); } } @Override public void remove() { try { rs.deleteRow(); } catch (SQLException e) { throw Utils.runtime(e); } } } /** * Static general purpose SQL utils * * @see JpaUtils * @author daniel * @testedby {@link SqlUtilsTest} */ public class SqlUtils { public synchronized static void shutdown() { init = false; if (pool != null) { pool.close(); pool = null; } } /** * HACK for debugging SoDash -- how many postgres threads are we running? How many are idle? * @param name * @return */ public static int[] getPostgresThreadInfo(String name) { Proc proc = new Proc("ps -ef "+name); proc.run(); proc.waitFor(new Dt(10, TUnit.SECOND)); String out = proc.getOutput(); proc.close(); String[] lines = StrUtils.splitLines(out); int cnt=lines.length, idlers=0; for (String line : lines) { if (line.contains("idle in transaction")) idlers++; } return new int[]{cnt,idlers}; } public static DBOptions options; /** * Convenience for {@link #getConnection(String, String, String)} using the static options. * @return a connection with auto-commit OFF (this is needed for streaming * mode) * @see #setDBOptions(DBOptions) */ public static Connection getConnection() { assert options != null && options.dbUrl != null : "No connection info! " + options; return getConnection(options); } /** * * @return a connection with auto-commit OFF (this is needed for streaming * mode) */ public static Connection getConnection(DBOptions dboptions) { return getConnection(dboptions.dbUrl, dboptions.dbUser, dboptions.dbPassword); } /** * @param select * @param con * Can be null if options have been setup -- in which case a new * connection will be created & closed. * @param max * 0 for unlimited * @return results */ public static Iterable<Object[]> executeQuery(String select, Connection con, int max) { boolean autoClose = false; try { if (con == null) { con = getConnection(); autoClose = true; } Statement stmnt = con.createStatement(); if (max > 0) stmnt.setMaxRows(max); ResultSet rs = stmnt.executeQuery(select); Iterable<Object[]> rsit = asIterable(rs, null); if (autoClose) { // copy out now, so we can close the connection return Containers.getList(rsit); } return rsit; } catch (Exception e) { Log.report("db", Utils.getRootCause(e), Level.WARNING); throw Utils.runtime(e); } finally { if (autoClose) SqlUtils.close(con); } } /** * @param select * @param con * Can be null if options have been setup -- in which case a new * connection will be created & closed. * Will be committed, unless this connection has auto-commit on. * @return results */ public static int executeUpdate(String sql, Connection con) { boolean autoClose = false; Statement stmnt = null; try { if (con == null) { con = getConnection(); autoClose = true; } stmnt = con.createStatement(); int rs = stmnt.executeUpdate(sql); if (!con.getAutoCommit()) con.commit(); return rs; } catch (Exception e) { Log.report("db", Utils.getRootCause(e), Level.WARNING); throw Utils.runtime(e); } finally { SqlUtils.close(stmnt); if (autoClose) SqlUtils.close(con); } } /** * @param select * @param con * Can be null if options have been setup -- in which case a new * connection will be created & closed. * @return results */ public static boolean executeCommand(String sql, Connection con, boolean swallowExceptions) { boolean autoClose = false; Statement stmnt = null; try { if (con == null) { con = getConnection(); autoClose = true; } stmnt = con.createStatement(); boolean rs = stmnt.execute(sql); if (!con.getAutoCommit()) con.commit(); return rs; } catch (Exception e) { Log.w("db", sql+" -> "+Utils.getRootCause(e)); if (swallowExceptions) { // close so the next command can start afresh if ( ! autoClose) { SqlUtils.close(con); } return false; } throw Utils.runtime(e); } finally { if (autoClose) SqlUtils.close(con); } } /** * table name is lower-cased. * * @see SqlUtils#getTableColumns(String) */ static final Cache<String, List<Pair<String>>> table2columns = new Cache( 100); private static final String LOGTAG = "sql"; /** * Provides streaming row-by-row access, if the resultset was created for * that. Or just convenient iteration.<br> * To get streaming: <br> * - connection.setAutoCommit(false); (NB: getConnection() does this for * you) <br> * - statement.setFetchSize(1);<br> * * WARNING: This iterable can only be looped over once! WARNING: You must * close the database resources after use! * * @param rs * @return */ public static Iterable<Object[]> asIterable(final ResultSet rs) { return asIterable(rs, null); } /** * Provides streaming row-by-row access, if the resultset was created for * that. Or just convenient iteration.<br> * To get streaming: <br> * - connection.setAutoCommit(false); (NB: getConnection() does this for * you) <br> * - statement.setFetchSize(1);<br> * * WARNING: This iterable can only be looped over once! * * @param rs * @param closeFn * Called when the resultset reaches the end. * @return */ public static Iterable<Object[]> asIterable(final ResultSet rs, final Runnable closeFn) { return new Iterable<Object[]>() { boolean fresh = true; @Override public Iterator<Object[]> iterator() { // You can only loop once! assert fresh; fresh = false; return new RSIterator(rs, closeFn); } }; } public static void close(Statement statement) { if (statement == null) return; try { statement.close(); } catch (SQLException e) { throw Utils.runtime(e); } } /** * * @param col * @param cols * @return -1 if not found */ static int getColumnIndex(String col, List<Pair<String>> cols) { assert cols != null; for (int i = 0; i < cols.size(); i++) { Pair<String> pair = cols.get(i); if (pair.first.equalsIgnoreCase(col)) return i; } return -1; } /** * Set a connection pool (e.g. use {@link BoneCPPool}) * * @param pool */ public synchronized static void setPool(IPool pool) { if (pool != null) { pool.close(); } SqlUtils.pool = pool; } /** * TODO ??How to use the connection pool?? (we favour bonecp over c3p0) * * @param dbUrl * @param user * @param password * @return a connection with auto-commit OFF (this is needed for streaming * mode) */ public static Connection getConnection(String dbUrl, String user, String password) { try { initCommonJdbcDriver(dbUrl); Connection con; if (pool != null && dbUrl.equals(pool.getURL()) && Utils.equals(user, pool.getUsername())) { // Use the pool (which matches our setup) con = pool.getConnection(); } else { con = DriverManager.getConnection(dbUrl,user, password); } // This is needed for streaming mode, so set it so by default // -- you must then explicitly call commit! con.setAutoCommit(false); return con; } catch (Exception e) { throw Utils.runtime(e); } } private static boolean init; private static IPool pool; /** * Load the Postgres/MySQL/etc driver if needed * * @param dbUrl * @throws Exception */ public static void initCommonJdbcDriver(String dbUrl) throws Exception { if (dbUrl == null) throw new NullPointerException(); if (dbUrl.startsWith("jdbc:postgresql:")) { // PostgreSQL Class.forName("org.postgresql.Driver"); } else if (dbUrl.startsWith("jdbc:mysql:")) { // MySQL Class.forName("com.mysql.jdbc.Driver"); } else if (dbUrl.startsWith("jdbc:h2:")) { // H2 is a lightweight pure Java db. Useful for testing. Class.forName("org.h2.Driver"); } else { Log.report("sql", "Unrecognised DB " + dbUrl, Level.WARNING); } } /** * @param con * @param tbl * @return List of (name,type)s */ public static List<Pair<String>> getTableColumns(Connection con, String tbl) { Statement statement = null; try { statement = con.createStatement(); statement.setMaxRows(1); ResultSet rs = statement.executeQuery("select * from " + tbl); ResultSetMetaData meta = rs.getMetaData(); List<Pair<String>> list = new ArrayList(); for (int i = 0; i < meta.getColumnCount(); i++) { String name = meta.getColumnName(i + 1); String type = meta.getColumnTypeName(i + 1); Pair p = new Pair(name, type); list.add(p); } return list; } catch (SQLException e) { throw Utils.runtime(e); } finally { close(statement); } } /** * A crude imitation of what Hibernate does: mapping database rows into Java * objects. * @author daniel * * @param <X> The output type, e.g. DBText */ static class InflateFn<X> implements IFn<Object[], X> { final Constructor<X> con; final Field[] fields; public InflateFn(Class<X> klass, Field[] fields) throws NoSuchMethodException, SecurityException { con = klass.getDeclaredConstructor(); con.setAccessible(true); this.fields = fields; } @Override public X apply(Object[] row) { try { X x = con.newInstance(); for (int i = 0; i < row.length; i++) { Field f = fields[i]; if (f == null) { continue; } Object val = row[i]; // conversions! val = inflate2_convert(val, f.getType()); f.set(x, val); } return x; } catch (Exception e) { throw Utils.runtime(e); } } } /** * A crude imitation of what Hibernate does: mapping database rows into Java * objects. * * @param select * The select clause. E.g. "x.xid,x.contents". This will be split * to WARNING: assumes you use x. to refer to the main object. * @param rs * Database rows * @param klass * @return */ public static <X> Iterable<X> inflate(String select, Iterable<Object[]> rs, final Class<X> klass) { // x.id, x.contents, etc. final Field[] fields = inflate2_whichColumns(select, klass); try { return Containers.applyLazy(rs, new InflateFn<X>(klass, fields)); } catch (Exception e1) { throw Utils.runtime(e1); } } private static Object inflate2_convert(Object val, Class type) throws Exception { if (val == null) return null; Class<? extends Object> vc = val.getClass(); if (vc == type) return val; // numbers if (vc == BigInteger.class) { if (type == Long.class) return ((BigInteger) val).longValue(); if (type == Double.class) return ((BigInteger) val).doubleValue(); } // enums if (ReflectionUtils.isa(type, Enum.class)) { Object[] ks = type.getEnumConstants(); assert ks != null : type; if (val instanceof Integer || val instanceof Long) { int i = (Integer) val; return ks[i]; } String sval = (String) val; for (Object k : ks) { if (k.toString().equals(sval)) { return k; } } throw new IllegalArgumentException("Unrecognised enum value: "+val+" for "+type); } // time if (type==Time.class) { return new Time(val.toString()); } // exceptions if (ReflectionUtils.isa(type, Throwable.class)) { byte[] bytes = (byte[]) val; InputStream in = new FastByteArrayInputStream(bytes, bytes.length); ObjectInputStream objIn = new ObjectInputStream(in); Object data = objIn.readObject(); objIn.close(); return data; } // How to handle JPA entities? We can't :( return val; } /** * Assume column-names = field-names, and we use "x.field" to refer to them * in the select! * * @param select * @param klass * @return */ static <X> Field[] inflate2_whichColumns(String select, Class<X> klass) { // We just want the top-level selected columns Pattern pSelectColsFrom = Pattern.compile("^select\\s+(.+?)\\s+from", Pattern.CASE_INSENSITIVE); Matcher m = pSelectColsFrom.matcher(select); if (m.find()) { select = m.group(1); } // NB: these are "x.field" // Build map of column-num to Field String[] cols = select.split(","); Field[] fields = new Field[cols.length]; for (int i = 0; i < fields.length; i++) { if (!cols[i].startsWith("x.")) { // ignore it?! // This allows for other columns to be mixed in } String col = cols[i].substring(2); Field field = ReflectionUtils.getField(klass, col); if (field == null) { // ignore it?! // This allows for other columns to be mixed in continue; } fields[i] = field; } // open up the security if (fields.length != 0) { Field.setAccessible(fields, true); } return fields; } /** * Encode the text to escape any SQL characters, and add surrounding 's. * This is for use as String constants -- not for use in LIKE statements * (which need extra escaping). * * @param text * Can be null (returns "null"). * @return e.g. don't => 'don''t' */ public static String sqlEncode(String text) { if (text == null) return "null"; text = "'" + text.replace("'", "''") + "'"; return text; } public static String sqlEncodeNoQuote(String text) { if (text == null) return "null"; text = text.replace("'", "''"); return text; } static void upsert2_insert(String table, Map<String, ?> col2val, boolean specialCaseId, List<Pair<String>> columnInfo, CharSequence whereClause, StringBuilder upsert) { upsert.append("insert into " + table + " select "); // Build what we put into each column for (Pair<String> colInfo : columnInfo) { // SoDash/Hibernate HACK: ignore any given id value & use the local // sequence? NB: this always sets a not-null id if (specialCaseId && "id".equals(colInfo.first)) { upsert.append("nextval('hibernate_sequence'),"); continue; } // Keep Hibernate happy - avoid oid and setParameter with null if ("oid".equals(colInfo.second) || col2val.get(colInfo.first) == null) { upsert.append("null,"); continue; } // a normal insert upsert.append(":" + colInfo.first + ","); } StrUtils.pop(upsert, 1); // block if already present upsert.append(" where not exists (select 1 from " + table + whereClause + ");"); } /** * @param idColumns * @param col2val * @return the identifying where clause */ static StringBuilder upsert2_where(String[] idColumns, Map<String, ?> col2val) { StringBuilder whereClause = new StringBuilder(" where ("); for (int i = 0; i < idColumns.length; i++) { String col = idColumns[i]; // SQL hack: " is null" not "=null" if (col2val.get(col) == null) { whereClause.append(col + " is null and "); continue; } whereClause.append(col + "=:" + col + " and "); } StrUtils.pop(whereClause, 4); whereClause.append(")"); return whereClause; } /** * Does NOT explicitly commit * * @param con * Can be null */ public static void close(Connection con) { if (con == null) return; try { con.close(); } catch (SQLException e) { // swallow throw Utils.runtime(e); } } /** * @param rs * Can be null */ public static void close(ResultSet rs) { if (rs == null) return; try { rs.close(); } catch (SQLException e) { throw Utils.runtime(e); } } /** * Set static database connection options. * Obviously this won't do if you need to connect to multiple databases, but for most programs, that's fine. * @param options Can be null to clear the options */ public static void setDBOptions(DBOptions options) { assert (SqlUtils.options == null || ReflectionUtils.equalish(SqlUtils.options, options)) : "Incompatible setup for SqlUtils static db connection."; SqlUtils.options = options; if (options!=null) { assert options.dbUrl != null : options; } } /** * Update where exists. * * @param table * @param col2val * @param specialCaseId * @param columnInfo * @param whereClause * @param upsert * @return "update table set stuff where whereClause;" */ static void upsert2_update(String table, Map<String, ?> col2val, boolean specialCaseId, List<Pair<String>> columnInfo, StringBuilder whereClause, StringBuilder upsert) { // ... create a=:a parameters upsert.append("update " + table + " set "); for (Pair<String> colInfo : columnInfo) { // SoDash/Hibernate HACK: don't change the id! if (specialCaseId && "id".equals(colInfo.first)) { continue; } // Keep Hibernate happy - avoid oid and setParameter with null if ("oid".equals(colInfo.second) || col2val.get(colInfo.first) == null) { upsert.append(colInfo.first + "=null,"); continue; } // a normal update upsert.append(colInfo.first + "=:" + colInfo.first + ","); } // lose the trailing , if (upsert.charAt(upsert.length() - 1) == ',') { StrUtils.pop(upsert, 1); } upsert.append(whereClause); upsert.append(";\n"); } /** * @param time * @return 'timestamp' for direct injection into an sql query. If you're * using Query.setParameter, just use a Date, e.g. Time.getDate(). */ public static String timestamp(Time time) { long l = time.getTime(); Timestamp timestampRaw = new Timestamp(l); String timestamp = timestampRaw.toString(); return '\'' + timestamp + '\''; } /** * Create a partial index which only covers ~ a month. Call this every month * to drop the old indexes and create a new one. * * @param table * @param indexedColumn * @param timestampColumn */ public static void createMonthlyIndex(String table, String indexedColumn, String timestampColumn) { // Go back a month, and then to the start of that month Time start = TimeUtils.getStartOfMonth(new Time()).minus(TUnit.MONTH); // drop some earlier ones TODO get a list of indexes instead Time old = start; for (int i = 0; i < 3; i++) { old = old.minus(TUnit.MONTH); // do this first, so we don't nuke the // current index String mmyy = old.format("MM_yy"); Log.d("sql.index", "Dropping if it exists: monthly index for " + table + " " + mmyy); boolean ok = executeCommand("drop index " + table + "_monthly_" + mmyy + "_idx", null, true); } Connection con = getConnection(); try { // What type of timestamp? a Java Long or an SQL Timestamp? Class type = null; List<Pair<String>> cols = getTableColumns(con, table); for (Pair<String> pair : cols) { if (!pair.first.equalsIgnoreCase(timestampColumn)) continue; String _type = pair.second.toLowerCase(); if (_type.startsWith("timestamp")) { type = Timestamp.class; } else if (_type.equals("long")) { type = Long.class; } else if (_type.equals("bigint")) { type = Long.class; } break; } String _start = type == Timestamp.class ? timestamp(start) : Long .toString(start.getTime()); String mmyy = start.format("MM_yy"); boolean ok = executeCommand("create index " + table + "_monthly_" + mmyy + "_idx on " + table + " (" + indexedColumn + ") where " + timestampColumn + ">" + _start, con, true); if (ok) Log.i("sql.index", "Created monthly index for " + table + " " + mmyy); else Log.i("sql.index", "monthly index for " + table + " " + mmyy + " already exists"); } finally { close(con); } } public static <X> Iterable<X> inflate(Iterable<Object[]> rows, Class<X> klass) { String select = selectAllFields(klass, "x"); return inflate(select, rows, klass); } /** * The guts of what columns are selected ("select" not included, nor the * "from ... where..." stuff) * * @param klass * @param var * e.g. "x" if using "from DBText x" * @return e.g. "x.name,x.id" */ public static String selectAllFields(Class klass, String var) { List<Field> fields = ReflectionUtils.getAllFields(klass); StringBuilder select = new StringBuilder(); for (Field field : fields) { if (ReflectionUtils.isTransient(field)) continue; if (field.getType().isAnnotationPresent(Entity.class)) { select.append(var + "." + field.getName() + "_id,"); } else { select.append(var + "." + field.getName() + ","); } } StrUtils.pop(select, 1); String s = select.toString(); return s; } public static int insert(Map<String,Object> item, String table, Connection con) { // half-hearted anti-injection check assert !table.contains(";") && !table.contains("--") : table; boolean autoClose = false; try { if (con == null) { con = getConnection(); autoClose = true; } Statement stmnt = con.createStatement(); // List<Field> fields = ReflectionUtils.getAllFields(row.getClass()); // fields = Containers.filter(fields, f -> ! ReflectionUtils.isTransient(f)); // StringBuilder select = new StringBuilder(); ArrayList<String> keys = new ArrayList(item.keySet()); String cols = StrUtils.join(keys, ","); StringBuilder values = new StringBuilder(); for(String f : keys) { Object v = item.get(f); if (v == null) { values.append("null,"); continue; } if (v instanceof Number) values.append(v+","); else if (v instanceof Boolean) values.append(v+","); else if (v instanceof String) values.append(SqlUtils.sqlEncode((String)v)+","); else { values.append(SqlUtils.sqlEncode(v.toString())+","); } } StrUtils.pop(values, 1); String sql = "insert into " + table + " (" + cols + ") values (" + values + ");"; // if (true) // throw new TodoException(); int rs = stmnt.executeUpdate(sql); if (!con.getAutoCommit()) con.commit(); return rs; } catch (Exception e) { Log.report("db", Utils.getRootCause(e), Level.WARNING); throw Utils.runtime(e); } finally { if (autoClose) SqlUtils.close(con); } } public static interface IPool { String getURL(); String getUsername(); Connection getConnection() throws SQLException; void close(); } /** * Convenience for single-result result sets. * * @param rs * @return The first row, or null if empty */ public static Object[] getOneRow(ResultSet rs) { Iterator<Object[]> rit = asIterable(rs).iterator(); return rit.hasNext() ? rit.next() : null; } /** * Commit and close. * * @param conn * Can be null (does nothing) * @throws RuntimeException * If either operation fails. But close is always called, even * if commit fails. */ public static void commmitAndClose(Connection conn) throws RuntimeException { if (conn == null) return; Exception ex = null; try { conn.commit(); } catch (Exception e) { ex = e; } try { conn.close(); } catch (Exception e) { if (ex == null) ex = e; // forget this 2nd exception -- report the first one } if (ex != null) throw Utils.runtime(ex); } /** * Convenience wrapper for {@link Connection#isClosed()}) * @param _connection Can be null (returns true). * @return true if closed (or throws an exception), false if _probably_ alive and well * (but no guarantees -- see {@link Connection#isClosed()}). * */ public static boolean isClosed(Connection _connection) { if (_connection==null) return true; try { return _connection.isClosed(); } catch (SQLException e) { Log.w(LOGTAG, e); return true; } } /** * upsert = update if exists + insert if new * * @param table * @param idColumns * The columns which identify the row. E.g. the primary key. Must * not contain any nulls. Should be a subset of columns. * @param col2val * The values to set for every non-null column. Any missing * columns will be set to null. * @param specialCaseId * If true, the "id" column is treated specially -- * nextval(hibernate_sequence) is used for the insert, and no * change is made on update. This is a hack 'cos row ids don't * travel across servers. * @return An upsert query, with it's parameters set. */ public static Object upsert(Connection em, String table, String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { List<Pair<String>> columnInfo = upsert2_columnInfo(em, table, idColumns, col2val, specialCaseId); StringBuilder whereClause = SqlUtils.upsert2_where(idColumns, col2val); StringBuilder upsert = new StringBuilder(); // 1. update where exists SqlUtils.upsert2_update(table, col2val, specialCaseId, columnInfo, whereClause, upsert); // 2. insert where not exists SqlUtils.upsert2_insert(table, col2val, specialCaseId, columnInfo, whereClause, upsert); // do it return executeUpdate(upsert.toString(), em); } // static void upsert2_setParams(Map<String, ?> col2val, // boolean specialCaseId, List<Pair<String>> columnInfo, Query q) { // for (Pair<String> colInfo : columnInfo) { // Object v = col2val.get(colInfo.first); // // did this column get ignored? // if ("oid".equals(colInfo.second) || v == null) { // continue; // if (specialCaseId && "id".equals(colInfo.first)) { // continue; // // set param // q.setParameter(colInfo.first, v); // /** // * Half an upsert: update-if-exists Does nothing if the row does not exist. // * // * Yes this is hacky. Got any better ideas? // * // * @param idColumns // * The columns which identify the row. E.g. the primary key. Must // * not contain any nulls. Should be a subset of columns. // * @param col2val // * The values to set for every non-null column. Any missing // * columns will be set to null. // * @param specialCaseId // * If true, the "id" column is treated specially -- // * nextval(hibernate_sequence) is used for the insert, and no // * change is made on update. This is a hack 'cos row ids don't // * travel across servers. Normally false. // * @return An update-where query, with it's parameters set. // */ // public static Query update(Connection em, String table, // String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { // List<Pair<String>> columnInfo = upsert2_columnInfo(em, table, // idColumns, col2val, specialCaseId); // StringBuilder whereClause = SqlUtils.upsert2_where(idColumns, col2val); // StringBuilder upsert = new StringBuilder(); // // 1. update // SqlUtils.upsert2_update(table, col2val, specialCaseId, columnInfo, // whereClause, upsert); // // create query // Query q = em.createNativeQuery(upsert.toString()); //// // set params //// upsert2_setParams(col2val, specialCaseId, columnInfo, q); // return q; // /** // * Half an upsert: insert-if-not-there. Does nothing if the row already // * exists. // * // * @param idColumns // * The columns which identify the row. E.g. the primary key. Must // * not contain any nulls. Should be a subset of columns. // * @param col2val // * The values to set for every non-null column. Any missing // * columns will be set to null. // * @param specialCaseId // * If true, the "id" column is treated specially -- // * nextval(hibernate_sequence) is used for the insert, and no // * change is made on update. This is a hack 'cos row ids don't // * travel across servers. Normally false. // * @return An insert-if-absent query, with it's parameters set. // */ // public static Query insertIfAbsent(Connection em, String table, // String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { // List<Pair<String>> columnInfo = upsert2_columnInfo(em, table, // idColumns, col2val, specialCaseId); // StringBuilder whereClause = SqlUtils.upsert2_where(idColumns, col2val); // StringBuilder upsert = new StringBuilder(); // // 1. insert where not exists // SqlUtils.upsert2_insert(table, col2val, specialCaseId, columnInfo, // whereClause, upsert); // // create query // Query q = em.createNativeQuery(upsert.toString()); //// // set params //// upsert2_setParams(col2val, specialCaseId, columnInfo, q); // return q; private static List<Pair<String>> upsert2_columnInfo(Connection con, String table, String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { List<Pair<String>> columnInfo = getTableColumns(con, table); // safety check inputs assert idColumns.length <= columnInfo.size(); for (String idc : idColumns) { assert idc != null : Printer.toString(idColumns); int i = SqlUtils.getColumnIndex(idc, columnInfo); assert i != -1 : idc + " vs " + columnInfo; } if (specialCaseId) { assert ! Containers.contains("id", idColumns); // assert getColumnIndex(em, "id", table) != -1 : table + " = " // + getTableColumns(em, table); } else { assert ! col2val.containsKey("id") : col2val; } return columnInfo; } /** * * @param conn * @param table * @param where * @param props * @param max 0 for unlimited * @return * @throws SQLException */ public static List<Map<String, Object>> select( Connection conn, String table, String where, List<String> props, int max ) throws SQLException { String sql = "select "+StrUtils.join(props, ",")+" from "+table+" where "+where; // call the DB Iterable<Object[]> rit = executeQuery(sql, conn, max); List<Map<String, Object>> maps = new ArrayList(); for (Object[] row : rit) { ArrayMap map = new ArrayMap(); for(int i=0; i<props.size(); i++) { String prop = props.get(i); map.put(prop, row[i]); } maps.add(map); } return maps; } }
package com.winterwell.utils.io; import java.io.InputStream; import java.io.ObjectInputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.math.BigInteger; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Entity; import com.winterwell.utils.IFn; import com.winterwell.utils.Printer; import com.winterwell.utils.Proc; import com.winterwell.utils.ReflectionUtils; import com.winterwell.utils.StrUtils; import com.winterwell.utils.TodoException; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.Cache; import com.winterwell.utils.containers.Containers; import com.winterwell.utils.containers.Pair; import com.winterwell.utils.io.DBUtils.DBOptions; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.Dt; import com.winterwell.utils.time.TUnit; import com.winterwell.utils.time.Time; import com.winterwell.utils.time.TimeUtils; class RSIterator implements Iterator<Object[]> { private int cols; private Boolean hasNext; private final ResultSet rs; private Runnable closeFn; public RSIterator(ResultSet rs, Runnable closeFn) { assert rs != null; this.rs = rs; this.closeFn = closeFn; try { cols = rs.getMetaData().getColumnCount(); } catch (SQLException e) { throw Utils.runtime(e); } } private void advanceIfNeeded() { if (hasNext != null) return; try { hasNext = rs.next(); // Close? if (!hasNext && closeFn != null) { rs.close(); closeFn.run(); } } catch (SQLException e) { throw Utils.runtime(e); } } @Override public boolean hasNext() { // handle repeated calls without repeated advances advanceIfNeeded(); return hasNext; } @Override public Object[] next() { // do we need to advance? Not if #hasNext() was called just before advanceIfNeeded(); // Either next or hasNext will now trigger an advance hasNext = null; try { Object[] row = new Object[cols]; for (int i = 0; i < row.length; i++) { row[i] = rs.getObject(i + 1); // not zero indexed } return row; } catch (SQLException e) { throw Utils.runtime(e); } } @Override public void remove() { try { rs.deleteRow(); } catch (SQLException e) { throw Utils.runtime(e); } } } /** * Static general purpose SQL utils * * @see JpaUtils * @author daniel * @testedby {@link SqlUtilsTest} */ public class SqlUtils { public synchronized static void shutdown() { init = false; if (pool != null) { pool.close(); pool = null; } } /** * HACK for debugging SoDash -- how many postgres threads are we running? How many are idle? * @param name * @return */ public static int[] getPostgresThreadInfo(String name) { Proc proc = new Proc("ps -ef "+name); proc.run(); proc.waitFor(new Dt(10, TUnit.SECOND)); String out = proc.getOutput(); proc.close(); String[] lines = StrUtils.splitLines(out); int cnt=lines.length, idlers=0; for (String line : lines) { if (line.contains("idle in transaction")) idlers++; } return new int[]{cnt,idlers}; } public static DBOptions options; /** * Convenience for {@link #getConnection(String, String, String)} using the static options. * @return a connection with auto-commit OFF (this is needed for streaming * mode) * @see #setDBOptions(DBOptions) */ public static Connection getConnection() { assert options != null && options.dbUrl != null : "No connection info! " + options; return getConnection(options); } /** * * @return a connection with auto-commit OFF (this is needed for streaming * mode) */ public static Connection getConnection(DBOptions dboptions) { return getConnection(dboptions.dbUrl, dboptions.dbUser, dboptions.dbPassword); } /** * @param select * @param con * Can be null if options have been setup -- in which case a new * connection will be created & closed. * @param max * 0 for unlimited * @return results */ public static Iterable<Object[]> executeQuery(String select, Connection con, int max) { boolean autoClose = false; try { if (con == null) { con = getConnection(); autoClose = true; } Statement stmnt = con.createStatement(); if (max > 0) stmnt.setMaxRows(max); ResultSet rs = stmnt.executeQuery(select); Iterable<Object[]> rsit = asIterable(rs, null); if (autoClose) { // copy out now, so we can close the connection return Containers.getList(rsit); } return rsit; } catch (Exception e) { Log.report("db", Utils.getRootCause(e), Level.WARNING); throw Utils.runtime(e); } finally { if (autoClose) SqlUtils.close(con); } } /** * @param select * @param con * Can be null if options have been setup -- in which case a new * connection will be created & closed. * Will be committed, unless this connection has auto-commit on. * @return results */ public static int executeUpdate(String sql, Connection con) { boolean autoClose = false; Statement stmnt = null; try { if (con == null) { con = getConnection(); autoClose = true; } stmnt = con.createStatement(); int rs = stmnt.executeUpdate(sql); if (!con.getAutoCommit()) con.commit(); return rs; } catch (Exception e) { Log.report("db", Utils.getRootCause(e), Level.WARNING); throw Utils.runtime(e); } finally { SqlUtils.close(stmnt); if (autoClose) SqlUtils.close(con); } } /** * @param select * @param con * Can be null if options have been setup -- in which case a new * connection will be created & closed. * @return results */ public static boolean executeCommand(String sql, Connection con, boolean swallowExceptions) { boolean autoClose = false; Statement stmnt = null; try { if (con == null) { con = getConnection(); autoClose = true; } stmnt = con.createStatement(); boolean rs = stmnt.execute(sql); if (!con.getAutoCommit()) con.commit(); return rs; } catch (Exception e) { Log.w("db", sql+" -> "+Utils.getRootCause(e)); if (swallowExceptions) { // close so the next command can start afresh if ( ! autoClose) { SqlUtils.close(con); } return false; } throw Utils.runtime(e); } finally { if (autoClose) SqlUtils.close(con); } } /** * table name is lower-cased. * * @see SqlUtils#getTableColumns(String) */ static final Cache<String, List<Pair<String>>> table2columns = new Cache( 100); private static final String LOGTAG = "sql"; /** * Provides streaming row-by-row access, if the resultset was created for * that. Or just convenient iteration.<br> * To get streaming: <br> * - connection.setAutoCommit(false); (NB: getConnection() does this for * you) <br> * - statement.setFetchSize(1);<br> * * WARNING: This iterable can only be looped over once! WARNING: You must * close the database resources after use! * * @param rs * @return */ public static Iterable<Object[]> asIterable(final ResultSet rs) { return asIterable(rs, null); } /** * Provides streaming row-by-row access, if the resultset was created for * that. Or just convenient iteration.<br> * To get streaming: <br> * - connection.setAutoCommit(false); (NB: getConnection() does this for * you) <br> * - statement.setFetchSize(1);<br> * * WARNING: This iterable can only be looped over once! * * @param rs * @param closeFn * Called when the resultset reaches the end. * @return */ public static Iterable<Object[]> asIterable(final ResultSet rs, final Runnable closeFn) { return new Iterable<Object[]>() { boolean fresh = true; @Override public Iterator<Object[]> iterator() { // You can only loop once! assert fresh; fresh = false; return new RSIterator(rs, closeFn); } }; } public static void close(Statement statement) { if (statement == null) return; try { statement.close(); } catch (SQLException e) { throw Utils.runtime(e); } } /** * * @param col * @param cols * @return -1 if not found */ static int getColumnIndex(String col, List<Pair<String>> cols) { assert cols != null; for (int i = 0; i < cols.size(); i++) { Pair<String> pair = cols.get(i); if (pair.first.equalsIgnoreCase(col)) return i; } return -1; } /** * Set a connection pool (e.g. use {@link BoneCPPool}) * * @param pool */ public synchronized static void setPool(IPool pool) { if (pool != null) { pool.close(); } SqlUtils.pool = pool; } /** * TODO ??How to use the connection pool?? (we favour bonecp over c3p0) * * @param dbUrl * @param user * @param password * @return a connection with auto-commit OFF (this is needed for streaming * mode) */ public static Connection getConnection(String dbUrl, String user, String password) { try { initCommonJdbcDriver(dbUrl); Connection con; if (pool != null && dbUrl.equals(pool.getURL()) && Utils.equals(user, pool.getUsername())) { // Use the pool (which matches our setup) con = pool.getConnection(); } else { con = DriverManager.getConnection(dbUrl,user, password); } // This is needed for streaming mode, so set it so by default // -- you must then explicitly call commit! con.setAutoCommit(false); return con; } catch (Exception e) { throw Utils.runtime(e); } } private static boolean init; private static IPool pool; /** * Load the Postgres/MySQL/etc driver if needed * * @param dbUrl * @throws Exception */ public static void initCommonJdbcDriver(String dbUrl) throws Exception { if (dbUrl == null) throw new NullPointerException(); if (dbUrl.startsWith("jdbc:postgresql:")) { // PostgreSQL Class.forName("org.postgresql.Driver"); } else if (dbUrl.startsWith("jdbc:mysql:")) { // MySQL Class.forName("com.mysql.jdbc.Driver"); } else if (dbUrl.startsWith("jdbc:h2:")) { // H2 is a lightweight pure Java db. Useful for testing. Class.forName("org.h2.Driver"); } else { Log.report("sql", "Unrecognised DB " + dbUrl, Level.WARNING); } } /** * @param con * @param tbl * @return List of (name,type)s */ public static List<Pair<String>> getTableColumns(Connection con, String tbl) { Statement statement = null; try { statement = con.createStatement(); statement.setMaxRows(1); ResultSet rs = statement.executeQuery("select * from " + tbl); ResultSetMetaData meta = rs.getMetaData(); List<Pair<String>> list = new ArrayList(); for (int i = 0; i < meta.getColumnCount(); i++) { String name = meta.getColumnName(i + 1); String type = meta.getColumnTypeName(i + 1); Pair p = new Pair(name, type); list.add(p); } return list; } catch (SQLException e) { throw Utils.runtime(e); } finally { close(statement); } } /** * A crude imitation of what Hibernate does: mapping database rows into Java * objects. * @author daniel * * @param <X> The output type, e.g. DBText */ static class InflateFn<X> implements IFn<Object[], X> { final Constructor<X> con; final Field[] fields; public InflateFn(Class<X> klass, Field[] fields) throws NoSuchMethodException, SecurityException { con = klass.getConstructor(); con.setAccessible(true); this.fields = fields; } @Override public X apply(Object[] row) { try { X x = con.newInstance(); for (int i = 0; i < row.length; i++) { Field f = fields[i]; if (f == null) { continue; } Object val = row[i]; // conversions! val = inflate2_convert(val, f.getType()); f.set(x, val); } return x; } catch (Exception e) { throw Utils.runtime(e); } } } /** * A crude imitation of what Hibernate does: mapping database rows into Java * objects. * * @param select * The select clause. E.g. "x.xid,x.contents". This will be split * to WARNING: assumes you use x. to refer to the main object. * @param rs * Database rows * @param klass * @return */ public static <X> Iterable<X> inflate(String select, Iterable<Object[]> rs, final Class<X> klass) { // x.id, x.contents, etc. final Field[] fields = inflate2_whichColumns(select, klass); try { return Containers.applyLazy(rs, new InflateFn<X>(klass, fields)); } catch (Exception e1) { throw Utils.runtime(e1); } } private static Object inflate2_convert(Object val, Class type) throws Exception { if (val == null) return null; Class<? extends Object> vc = val.getClass(); if (vc == type) return val; // numbers if (vc == BigInteger.class) { if (type == Long.class) return ((BigInteger) val).longValue(); if (type == Double.class) return ((BigInteger) val).doubleValue(); } // enums if (ReflectionUtils.isa(type, Enum.class)) { Object[] ks = type.getEnumConstants(); assert ks != null : type; if (val instanceof Integer || val instanceof Long) { int i = (Integer) val; return ks[i]; } String sval = (String) val; for (Object k : ks) { if (k.toString().equals(sval)) { return k; } } throw new IllegalArgumentException("Unrecognised enum value: "+val+" for "+type); } // exceptions if (ReflectionUtils.isa(type, Throwable.class)) { byte[] bytes = (byte[]) val; InputStream in = new FastByteArrayInputStream(bytes, bytes.length); ObjectInputStream objIn = new ObjectInputStream(in); Object data = objIn.readObject(); objIn.close(); return data; } // How to handle JPA entities? We can't :( return val; } /** * Assume column-names = field-names, and we use "x.field" to refer to them * in the select! * * @param select * @param klass * @return */ static <X> Field[] inflate2_whichColumns(String select, Class<X> klass) { // We just want the top-level selected columns Pattern pSelectColsFrom = Pattern.compile("^select\\s+(.+?)\\s+from", Pattern.CASE_INSENSITIVE); Matcher m = pSelectColsFrom.matcher(select); if (m.find()) { select = m.group(1); } // NB: these are "x.field" // Build map of column-num to Field String[] cols = select.split(","); Field[] fields = new Field[cols.length]; for (int i = 0; i < fields.length; i++) { if (!cols[i].startsWith("x.")) { // ignore it?! // This allows for other columns to be mixed in } String col = cols[i].substring(2); Field field = ReflectionUtils.getField(klass, col); if (field == null) { // ignore it?! // This allows for other columns to be mixed in continue; } fields[i] = field; } // open up the security if (fields.length != 0) { Field.setAccessible(fields, true); } return fields; } /** * Encode the text to escape any SQL characters, and add surrounding 's. * This is for use as String constants -- not for use in LIKE statements * (which need extra escaping). * * @param text * Can be null (returns "null"). * @return e.g. don't => 'don''t' */ public static String sqlEncode(String text) { if (text == null) return "null"; text = "'" + text.replace("'", "''") + "'"; return text; } public static String sqlEncodeNoQuote(String text) { if (text == null) return "null"; text = text.replace("'", "''"); return text; } static void upsert2_insert(String table, Map<String, ?> col2val, boolean specialCaseId, List<Pair<String>> columnInfo, CharSequence whereClause, StringBuilder upsert) { upsert.append("insert into " + table + " select "); // Build what we put into each column for (Pair<String> colInfo : columnInfo) { // SoDash/Hibernate HACK: ignore any given id value & use the local // sequence? NB: this always sets a not-null id if (specialCaseId && "id".equals(colInfo.first)) { upsert.append("nextval('hibernate_sequence'),"); continue; } // Keep Hibernate happy - avoid oid and setParameter with null if ("oid".equals(colInfo.second) || col2val.get(colInfo.first) == null) { upsert.append("null,"); continue; } // a normal insert upsert.append(":" + colInfo.first + ","); } StrUtils.pop(upsert, 1); // block if already present upsert.append(" where not exists (select 1 from " + table + whereClause + ");"); } /** * @param idColumns * @param col2val * @return the identifying where clause */ static StringBuilder upsert2_where(String[] idColumns, Map<String, ?> col2val) { StringBuilder whereClause = new StringBuilder(" where ("); for (int i = 0; i < idColumns.length; i++) { String col = idColumns[i]; // SQL hack: " is null" not "=null" if (col2val.get(col) == null) { whereClause.append(col + " is null and "); continue; } whereClause.append(col + "=:" + col + " and "); } StrUtils.pop(whereClause, 4); whereClause.append(")"); return whereClause; } /** * Does NOT explicitly commit * * @param con * Can be null */ public static void close(Connection con) { if (con == null) return; try { con.close(); } catch (SQLException e) { // swallow throw Utils.runtime(e); } } /** * @param rs * Can be null */ public static void close(ResultSet rs) { if (rs == null) return; try { rs.close(); } catch (SQLException e) { throw Utils.runtime(e); } } /** * Set static database connection options. * Obviously this won't do if you need to connect to multiple databases, but for most programs, that's fine. * @param options Can be null to clear the options */ public static void setDBOptions(DBOptions options) { assert (SqlUtils.options == null || ReflectionUtils.equalish(SqlUtils.options, options)) : "Incompatible setup for SqlUtils static db connection."; SqlUtils.options = options; if (options!=null) { assert options.dbUrl != null : options; } } /** * Update where exists. * * @param table * @param col2val * @param specialCaseId * @param columnInfo * @param whereClause * @param upsert * @return "update table set stuff where whereClause;" */ static void upsert2_update(String table, Map<String, ?> col2val, boolean specialCaseId, List<Pair<String>> columnInfo, StringBuilder whereClause, StringBuilder upsert) { // ... create a=:a parameters upsert.append("update " + table + " set "); for (Pair<String> colInfo : columnInfo) { // SoDash/Hibernate HACK: don't change the id! if (specialCaseId && "id".equals(colInfo.first)) { continue; } // Keep Hibernate happy - avoid oid and setParameter with null if ("oid".equals(colInfo.second) || col2val.get(colInfo.first) == null) { upsert.append(colInfo.first + "=null,"); continue; } // a normal update upsert.append(colInfo.first + "=:" + colInfo.first + ","); } // lose the trailing , if (upsert.charAt(upsert.length() - 1) == ',') { StrUtils.pop(upsert, 1); } upsert.append(whereClause); upsert.append(";\n"); } /** * @param time * @return 'timestamp' for direct injection into an sql query. If you're * using Query.setParameter, just use a Date, e.g. Time.getDate(). */ public static String timestamp(Time time) { long l = time.getTime(); Timestamp timestampRaw = new Timestamp(l); String timestamp = timestampRaw.toString(); return '\'' + timestamp + '\''; } /** * Create a partial index which only covers ~ a month. Call this every month * to drop the old indexes and create a new one. * * @param table * @param indexedColumn * @param timestampColumn */ public static void createMonthlyIndex(String table, String indexedColumn, String timestampColumn) { // Go back a month, and then to the start of that month Time start = TimeUtils.getStartOfMonth(new Time()).minus(TUnit.MONTH); // drop some earlier ones TODO get a list of indexes instead Time old = start; for (int i = 0; i < 3; i++) { old = old.minus(TUnit.MONTH); // do this first, so we don't nuke the // current index String mmyy = old.format("MM_yy"); Log.d("sql.index", "Dropping if it exists: monthly index for " + table + " " + mmyy); boolean ok = executeCommand("drop index " + table + "_monthly_" + mmyy + "_idx", null, true); } Connection con = getConnection(); try { // What type of timestamp? a Java Long or an SQL Timestamp? Class type = null; List<Pair<String>> cols = getTableColumns(con, table); for (Pair<String> pair : cols) { if (!pair.first.equalsIgnoreCase(timestampColumn)) continue; String _type = pair.second.toLowerCase(); if (_type.startsWith("timestamp")) { type = Timestamp.class; } else if (_type.equals("long")) { type = Long.class; } else if (_type.equals("bigint")) { type = Long.class; } break; } String _start = type == Timestamp.class ? timestamp(start) : Long .toString(start.getTime()); String mmyy = start.format("MM_yy"); boolean ok = executeCommand("create index " + table + "_monthly_" + mmyy + "_idx on " + table + " (" + indexedColumn + ") where " + timestampColumn + ">" + _start, con, true); if (ok) Log.i("sql.index", "Created monthly index for " + table + " " + mmyy); else Log.i("sql.index", "monthly index for " + table + " " + mmyy + " already exists"); } finally { close(con); } } public static <X> Iterable<X> inflate(Iterable<Object[]> rows, Class<X> klass) { String select = selectAllFields(klass, "x"); return inflate(select, rows, klass); } /** * The guts of what columns are selected ("select" not included, nor the * "from ... where..." stuff) * * @param klass * @param var * e.g. "x" if using "from DBText x" * @return e.g. "x.name,x.id" */ public static String selectAllFields(Class klass, String var) { List<Field> fields = ReflectionUtils.getAllFields(klass); StringBuilder select = new StringBuilder(); for (Field field : fields) { if (ReflectionUtils.isTransient(field)) continue; if (field.getType().isAnnotationPresent(Entity.class)) { select.append(var + "." + field.getName() + "_id,"); } else { select.append(var + "." + field.getName() + ","); } } StrUtils.pop(select, 1); String s = select.toString(); return s; } @Deprecated // TODO public static int insert(Object row, String table, Connection con) { // half-hearted anti-injection check assert !table.contains(";") && !table.contains("--") : table; boolean autoClose = false; try { if (con == null) { con = getConnection(); autoClose = true; } Statement stmnt = con.createStatement(); List<Field> fields = ReflectionUtils.getAllFields(row.getClass()); StringBuilder select = new StringBuilder(); for (Field field : fields) { if (ReflectionUtils.isTransient(field)) continue; } StringBuilder cols = new StringBuilder(); StringBuilder values = new StringBuilder(); String sql = "insert into " + table + " (" + cols + ") values (" + values + ");"; if (true) throw new TodoException(); int rs = stmnt.executeUpdate(sql); if (!con.getAutoCommit()) con.commit(); return rs; } catch (Exception e) { Log.report("db", Utils.getRootCause(e), Level.WARNING); throw Utils.runtime(e); } finally { if (autoClose) SqlUtils.close(con); } } public static interface IPool { String getURL(); String getUsername(); Connection getConnection() throws SQLException; void close(); } /** * Convenience for single-result result sets. * * @param rs * @return The first row, or null if empty */ public static Object[] getOneRow(ResultSet rs) { Iterator<Object[]> rit = asIterable(rs).iterator(); return rit.hasNext() ? rit.next() : null; } /** * Commit and close. * * @param conn * Can be null (does nothing) * @throws RuntimeException * If either operation fails. But close is always called, even * if commit fails. */ public static void commmitAndClose(Connection conn) throws RuntimeException { if (conn == null) return; Exception ex = null; try { conn.commit(); } catch (Exception e) { ex = e; } try { conn.close(); } catch (Exception e) { if (ex == null) ex = e; // forget this 2nd exception -- report the first one } if (ex != null) throw Utils.runtime(ex); } /** * Convenience wrapper for {@link Connection#isClosed()}) * @param _connection Can be null (returns true). * @return true if closed (or throws an exception), false if _probably_ alive and well * (but no guarantees -- see {@link Connection#isClosed()}). * */ public static boolean isClosed(Connection _connection) { if (_connection==null) return true; try { return _connection.isClosed(); } catch (SQLException e) { Log.w(LOGTAG, e); return true; } } /** * upsert = update if exists + insert if new * * @param table * @param idColumns * The columns which identify the row. E.g. the primary key. Must * not contain any nulls. Should be a subset of columns. * @param col2val * The values to set for every non-null column. Any missing * columns will be set to null. * @param specialCaseId * If true, the "id" column is treated specially -- * nextval(hibernate_sequence) is used for the insert, and no * change is made on update. This is a hack 'cos row ids don't * travel across servers. * @return An upsert query, with it's parameters set. */ public static Object upsert(Connection em, String table, String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { List<Pair<String>> columnInfo = upsert2_columnInfo(em, table, idColumns, col2val, specialCaseId); StringBuilder whereClause = SqlUtils.upsert2_where(idColumns, col2val); StringBuilder upsert = new StringBuilder(); // 1. update where exists SqlUtils.upsert2_update(table, col2val, specialCaseId, columnInfo, whereClause, upsert); // 2. insert where not exists SqlUtils.upsert2_insert(table, col2val, specialCaseId, columnInfo, whereClause, upsert); // do it return executeUpdate(upsert.toString(), em); } // static void upsert2_setParams(Map<String, ?> col2val, // boolean specialCaseId, List<Pair<String>> columnInfo, Query q) { // for (Pair<String> colInfo : columnInfo) { // Object v = col2val.get(colInfo.first); // // did this column get ignored? // if ("oid".equals(colInfo.second) || v == null) { // continue; // if (specialCaseId && "id".equals(colInfo.first)) { // continue; // // set param // q.setParameter(colInfo.first, v); // /** // * Half an upsert: update-if-exists Does nothing if the row does not exist. // * // * Yes this is hacky. Got any better ideas? // * // * @param idColumns // * The columns which identify the row. E.g. the primary key. Must // * not contain any nulls. Should be a subset of columns. // * @param col2val // * The values to set for every non-null column. Any missing // * columns will be set to null. // * @param specialCaseId // * If true, the "id" column is treated specially -- // * nextval(hibernate_sequence) is used for the insert, and no // * change is made on update. This is a hack 'cos row ids don't // * travel across servers. Normally false. // * @return An update-where query, with it's parameters set. // */ // public static Query update(Connection em, String table, // String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { // List<Pair<String>> columnInfo = upsert2_columnInfo(em, table, // idColumns, col2val, specialCaseId); // StringBuilder whereClause = SqlUtils.upsert2_where(idColumns, col2val); // StringBuilder upsert = new StringBuilder(); // // 1. update // SqlUtils.upsert2_update(table, col2val, specialCaseId, columnInfo, // whereClause, upsert); // // create query // Query q = em.createNativeQuery(upsert.toString()); //// // set params //// upsert2_setParams(col2val, specialCaseId, columnInfo, q); // return q; // /** // * Half an upsert: insert-if-not-there. Does nothing if the row already // * exists. // * // * @param idColumns // * The columns which identify the row. E.g. the primary key. Must // * not contain any nulls. Should be a subset of columns. // * @param col2val // * The values to set for every non-null column. Any missing // * columns will be set to null. // * @param specialCaseId // * If true, the "id" column is treated specially -- // * nextval(hibernate_sequence) is used for the insert, and no // * change is made on update. This is a hack 'cos row ids don't // * travel across servers. Normally false. // * @return An insert-if-absent query, with it's parameters set. // */ // public static Query insertIfAbsent(Connection em, String table, // String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { // List<Pair<String>> columnInfo = upsert2_columnInfo(em, table, // idColumns, col2val, specialCaseId); // StringBuilder whereClause = SqlUtils.upsert2_where(idColumns, col2val); // StringBuilder upsert = new StringBuilder(); // // 1. insert where not exists // SqlUtils.upsert2_insert(table, col2val, specialCaseId, columnInfo, // whereClause, upsert); // // create query // Query q = em.createNativeQuery(upsert.toString()); //// // set params //// upsert2_setParams(col2val, specialCaseId, columnInfo, q); // return q; private static List<Pair<String>> upsert2_columnInfo(Connection con, String table, String[] idColumns, Map<String, ?> col2val, boolean specialCaseId) { List<Pair<String>> columnInfo = getTableColumns(con, table); // safety check inputs assert idColumns.length <= columnInfo.size(); for (String idc : idColumns) { assert idc != null : Printer.toString(idColumns); int i = SqlUtils.getColumnIndex(idc, columnInfo); assert i != -1 : idc + " vs " + columnInfo; } if (specialCaseId) { assert ! Containers.contains("id", idColumns); // assert getColumnIndex(em, "id", table) != -1 : table + " = " // + getTableColumns(em, table); } else { assert ! col2val.containsKey("id") : col2val; } return columnInfo; } }
package org.exoplatform.social.client.api.net; import java.io.IOException; @SuppressWarnings("serial") public class SocialHttpClientException extends IOException { /** * Constructor for SocialHttpClientException. * * @param message the message of exception * @param cause the cause of exception */ public SocialHttpClientException(String message, Throwable cause) { super(message); initCause(cause); } /** * Constructor for SocialHttpClientException. * @param message the message of exception */ public SocialHttpClientException(String message) { super(message); } }
package org.jenkinsci.plugins.registry.notification.webhook; import hudson.model.*; import hudson.model.Queue; import hudson.security.ACL; import jenkins.model.Jenkins; import jenkins.model.ParameterizedJobMixIn; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.jenkinsci.plugins.registry.notification.Coordinator; import org.jenkinsci.plugins.registry.notification.DockerHubTrigger; import org.jenkinsci.plugins.registry.notification.TriggerStore; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.interceptor.RespondSuccess; import javax.annotation.Nonnull; import java.io.IOException; import java.net.URLDecoder; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public abstract class JSONWebHook implements UnprotectedRootAction { private static final Logger logger = Logger.getLogger(JSONWebHook.class.getName()); public String getIconFileName() { return null; } public String getDisplayName() { return "DockerHub web hook"; } @RequirePOST @RespondSuccess public void doNotify(@QueryParameter(required = false) String payload, StaplerRequest request, StaplerResponse response) throws IOException { WebHookPayload hookPayload = null; if (payload != null) { try { hookPayload = createPushNotification(JSONObject.fromObject(payload)); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse the web hook payload!", e); } } else { hookPayload = parse(request); } if (hookPayload != null) { for (PushNotification pushNotification : hookPayload.getPushNotifications()) { try { trigger(response, pushNotification); } catch (Exception e) { logger.log(Level.SEVERE, "Could not trigger a job!", e); } } } } /** * Stapler entry for the multi build result page * @param sha the id of the trigger data. * @return the details * @throws IOException if so * @throws InterruptedException if so */ @Nonnull public ResultPage getDetails(@Nonnull final String sha) throws IOException, InterruptedException { TriggerStore.TriggerEntry entry = TriggerStore.getInstance().getEntry(sha); if (entry != null) { return new ResultPage(entry); } else { return ResultPage.NO_RESULT; } } protected void trigger(StaplerResponse response, final PushNotification pushNotification) throws IOException { final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return; } ACL.impersonate(ACL.SYSTEM, new Runnable() { @Override public void run() { // search all jobs for DockerHubTrigger for (ParameterizedJobMixIn.ParameterizedJob p : jenkins.getAllItems(ParameterizedJobMixIn.ParameterizedJob.class)) { DockerHubTrigger trigger = DockerHubTrigger.getTrigger(p); if (trigger == null) { logger.log(Level.FINER, "job {0} doesn't have DockerHubTrigger set", p.getName()); continue; } logger.log(Level.FINER, "Inspecting candidate job {0}", p.getName()); Set<String> allRepoNames = trigger.getAllRepoNames(); String repoName = pushNotification.getRepoName(); if (allRepoNames.contains(repoName)) { schedule((Job) p, pushNotification); } } } }); } private void schedule(@Nonnull final Job job, @Nonnull final PushNotification pushNotification) { if (new JobbMixIn(job).schedule(pushNotification.getCause())) { logger.info(pushNotification.getCauseMessage()); Coordinator coordinator = Coordinator.getInstance(); if (coordinator != null) { coordinator.onTriggered(job, pushNotification); } } } /** * If someone wanders in to the index page, redirect to Jenkins root. * * @param request the request object * @param response the response object * @throws IOException if so */ public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException { response.sendRedirect(request.getContextPath() + "/"); } protected abstract WebHookPayload createPushNotification(JSONObject data); private WebHookPayload parse(StaplerRequest req) throws IOException { //TODO Actually test what duckerhub is really sending String body = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding()); String contentType = req.getContentType(); if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")) { body = URLDecoder.decode(body, req.getCharacterEncoding()); } logger.log(Level.FINER, "Received commit hook notification : {0}", body); try { JSONObject payload = JSONObject.fromObject(body); return createPushNotification(payload); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse the web hook payload!", e); return null; } } /** * Workaround until {@link ParameterizedJobMixIn#getDefaultParametersValues()} gets public. */ static class JobbMixIn<JobT extends Job<JobT, RunT> & ParameterizedJobMixIn.ParameterizedJob<JobT, RunT> & Queue.Task, RunT extends Run<JobT, RunT> & Queue.Executable> extends ParameterizedJobMixIn<JobT, RunT> { /** * Some breathing room to iterate through most/all of the jobs before the first triggered build starts. */ public static final int MIN_QUIET = 3; private JobT the; JobbMixIn(JobT the) { this.the = the; } @Override protected JobT asJob() { return the; } boolean schedule(Cause cause) { if (!asJob().isBuildable()) { return false; } List<Action> queueActions = new LinkedList<Action>(); queueActions.add(new ParametersAction(getParameterValues())); queueActions.add(new CauseAction(cause)); int quiet = Math.max(MIN_QUIET, asJob().getQuietPeriod()); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { logger.log(Level.WARNING, "Tried to schedule a build while Jenkins was gone."); return false; } final Queue queue = jenkins.getQueue(); if (queue == null) { throw new IllegalStateException("The queue is not initialized?!"); } Queue.Item i = queue.schedule2(asJob(), quiet, queueActions).getItem(); return i != null && i.getFuture() != null; } private List<ParameterValue> getParameterValues() { Set<ParameterValue> result = new HashSet<ParameterValue>(); if (isParameterized()) { result.addAll(getDefaultParametersValues()); } return Collections.unmodifiableList(new LinkedList<ParameterValue>(result)); } /** * Direct copy from {@link ParameterizedJobMixIn#getDefaultParametersValues()} (version 1.580). * * @return the configured parameters with their default values. */ private List<ParameterValue> getDefaultParametersValues() { ParametersDefinitionProperty paramDefProp = asJob().getProperty(ParametersDefinitionProperty.class); ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>(); /* * This check is made ONLY if someone will call this method even if isParametrized() is false. */ if (paramDefProp == null) return defValues; /* Scan for all parameter with an associated default values */ for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) { ParameterValue defaultValue = paramDefinition.getDefaultParameterValue(); if (defaultValue != null) defValues.add(defaultValue); } return defValues; } } }
package org.openhab.binding.heos.internal.discovery; import static org.openhab.binding.heos.HeosBindingConstants.*; import static org.openhab.binding.heos.internal.resources.HeosConstants.*; import java.util.HashMap; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService; import org.eclipse.smarthome.config.discovery.DiscoveryResult; import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.ThingUID; import org.openhab.binding.heos.handler.HeosBridgeHandler; import org.openhab.binding.heos.internal.resources.HeosGroup; import org.openhab.binding.heos.internal.resources.HeosPlayer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; /** * The {@link HeosPlayerDiscovery} discovers the player and groups within * the HEOS network and reacts on changed groups or player. * * @author Johannes Einig - Initial contribution */ public class HeosPlayerDiscovery extends AbstractDiscoveryService { private final static int SEARCH_TIME = 20; private final static int INITIAL_DELAY = 5; private final static int SCAN_INTERVAL = 20; private Logger logger = LoggerFactory.getLogger(HeosPlayerDiscovery.class); private HeosBridgeHandler bridge; private PlayerScan scanningRunnable; private ScheduledFuture<?> scanningJob; public HeosPlayerDiscovery(HeosBridgeHandler bridge) throws IllegalArgumentException { super(20); this.bridge = bridge; this.scanningRunnable = new PlayerScan(); bridge.setHeosPlayerDiscovery(this); // Debug // this.startBackgroundDiscovery(); } @Override public Set<ThingTypeUID> getSupportedThingTypes() { Set<ThingTypeUID> supportedThings = Sets.newHashSet(THING_TYPE_GROUP, THING_TYPE_PLAYER); return supportedThings; } @Override protected void startScan() { logger.info("Start scan for HEOS Player"); HashMap<String, HeosPlayer> playerMap = new HashMap<>(); playerMap = bridge.getNewPlayer(); if (playerMap == null) { // Debug // System.out.println("Debug: Player Map = Null"); } else { logger.info("Found: {} new Player", playerMap.size()); ThingUID bridgeUID = bridge.getThing().getUID(); for (String playerPID : playerMap.keySet()) { HeosPlayer player = playerMap.get(playerPID); ThingUID uid = new ThingUID(THING_TYPE_PLAYER, playerMap.get(playerPID).getPid()); HashMap<String, Object> properties = new HashMap<String, Object>(); properties.put(NAME, player.getName()); properties.put(PID, player.getPid()); properties.put(PLAYER_TYPE, player.getModel()); properties.put(HOST, player.getIp()); properties.put(TYPE, PLAYER); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel(player.getName()) .withProperties(properties).withBridge(bridgeUID).build(); thingDiscovered(result); } } logger.info("Start scan for HEOS Groups"); HashMap<String, HeosGroup> groupMap = new HashMap<>(); groupMap = bridge.getNewGroups(); if (playerMap == null) { // Debug // System.out.println("Debug: Player Map = Null"); } else { if (!groupMap.isEmpty()) { logger.info("Found: {} new Groups", groupMap.size()); ThingUID bridgeUID = bridge.getThing().getUID(); for (String groupGID : groupMap.keySet()) { HeosGroup group = groupMap.get(groupGID); // uses an unsigned hashCode from the group name to identify the group and generates the Thing UID. // Only the name does not work because it can consists non allowed characters. This also making it // possible to add player to a group. Keeping the Name lets the binding still identifying the group // as known ThingUID uid = new ThingUID(THING_TYPE_GROUP, group.getGroupMemberHash()); HashMap<String, Object> properties = new HashMap<String, Object>(); properties.put(NAME, group.getName()); properties.put(GID, group.getGid()); properties.put(LEADER, group.getLeader()); properties.put(TYPE, GROUP); properties.put(NAME_HASH, group.getNameHash()); properties.put(GROUP_MEMBER_HASH, group.getGroupMemberHash()); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel(group.getName()) .withProperties(properties).withBridge(bridgeUID).build(); thingDiscovered(result); } } else { logger.info("No HEOS Groups found"); } } removedPlayers(); removedGroups(); } // Informs the system of removed groups by using the thingRemoved method. private void removedGroups() { HashMap<String, HeosGroup> removedGroupMap = new HashMap<>(); removedGroupMap = bridge.getRemovedGroups(); if (!removedGroupMap.isEmpty()) { for (String key : removedGroupMap.keySet()) { // The same as above! ThingUID uid = new ThingUID(THING_TYPE_GROUP, removedGroupMap.get(key).getGroupMemberHash()); logger.info("Removed HEOS Group: " + uid); thingRemoved(uid); } } } // Informs the system of removed players by using the thingRemoved method. private void removedPlayers() { HashMap<String, HeosPlayer> removedPlayerMap = new HashMap<>(); removedPlayerMap = bridge.getRemovedPlayer(); if (!removedPlayerMap.isEmpty()) { for (String key : removedPlayerMap.keySet()) { // The same as above! ThingUID uid = new ThingUID(THING_TYPE_PLAYER, removedPlayerMap.get(key).getPid()); logger.info("Removed HEOS Player: " + uid); thingRemoved(uid); } } } @Override protected void startBackgroundDiscovery() { logger.trace("Start HEOS Player background discovery"); if (scanningJob == null || scanningJob.isCancelled()) { this.scanningJob = AbstractDiscoveryService.scheduler.scheduleWithFixedDelay(this.scanningRunnable, INITIAL_DELAY, SCAN_INTERVAL, TimeUnit.SECONDS); } logger.trace("scanningJob active"); // Debug // System.out.println("start background discover"); } @Override protected void stopBackgroundDiscovery() { logger.debug("Stop HEOS Player background discovery"); if (scanningJob != null && !scanningJob.isCancelled()) { scanningJob.cancel(true); scanningJob = null; } } @Override protected synchronized void stopScan() { super.stopScan(); removeOlderResults(getTimestampOfLastScan()); } public void scanForNewPlayers() { scanningRunnable.run(); // Debug: does not work.... // removeOlderResults(getTimestampOfLastScan()); } public class PlayerScan implements Runnable { @Override public void run() { startScan(); } } }
package org.spongepowered.common.event.tracking.phase.general; import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; import net.minecraft.world.WorldServer; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.entity.Entity; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.event.tracking.IPhaseState; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.PhaseData; import org.spongepowered.common.event.tracking.TrackingUtil; import org.spongepowered.common.event.tracking.phase.TrackingPhases; import org.spongepowered.common.event.tracking.phase.block.BlockPhase; import java.util.ArrayList; import java.util.List; final class PostState extends GeneralState<UnwindingPhaseContext> { @Override public UnwindingPhaseContext createPhaseContext() { throw new UnsupportedOperationException("Use UnwindingPhaseContext#unwind(IPhaseState, PhaseContext)! Cannot create a context based on Post state!"); } @Override public boolean canSwitchTo(IPhaseState state) { return state.getPhase() == TrackingPhases.GENERATION || state.getPhase() == TrackingPhases.PLUGIN || state == BlockPhase.State.RESTORING_BLOCKS // Plugins can call commands during event listeners. || state == GeneralPhase.State.COMMAND // Decay can be caused when a block is performing a lot of // changes in place || state == BlockPhase.State.BLOCK_DECAY; } @Override public boolean requiresPost() { return false; } @Override public boolean ignoresBlockUpdateTick(PhaseData phaseData) { return true; } @Override public boolean ignoresScheduledUpdates() { return true; } @Override public boolean alreadyCapturingEntitySpawns() { return true; } @Override public boolean alreadyCapturingEntityTicks() { return true; } @Override public boolean alreadyCapturingTileTicks() { return true; } @Override public boolean alreadyCapturingItemSpawns() { return true; } @SuppressWarnings("unchecked") @Override public void appendContextPreExplosion(ExplosionContext explosionContext, UnwindingPhaseContext context) { final IPhaseState phaseState = context.getUnwindingState(); final PhaseContext<?> unwinding = context.getUnwindingContext(); phaseState.appendContextPreExplosion(explosionContext, unwinding); } @SuppressWarnings("unchecked") @Override public void associateNeighborStateNotifier(UnwindingPhaseContext context, BlockPos sourcePos, Block block, BlockPos notifyPos, WorldServer minecraftWorld, PlayerTracker.Type notifier) { final IPhaseState<?> unwindingState = context.getUnwindingState(); final PhaseContext<?> unwindingContext = context.getUnwindingContext(); ((IPhaseState) unwindingState).associateNeighborStateNotifier(unwindingContext, sourcePos, block, notifyPos, minecraftWorld, notifier); } @SuppressWarnings("unchecked") @Override public void unwind(UnwindingPhaseContext context) { final IPhaseState unwindingState = context.getUnwindingState(); final PhaseContext<?> unwindingContext = context.getUnwindingContext(); this.postDispatch(unwindingState, unwindingContext, context); } @SuppressWarnings("unchecked") @Override public void postDispatch(IPhaseState<?> unwindingState, PhaseContext<?> unwindingContext, UnwindingPhaseContext postContext) { final List<BlockSnapshot> contextBlocks = postContext.getCapturedBlocksOrEmptyList(); final List<Entity> contextEntities = postContext.getCapturedEntitiesOrEmptyList(); final List<Entity> contextItems = (List<Entity>) (List<?>) postContext.getCapturedItemsOrEmptyList(); if (contextBlocks.isEmpty() && contextEntities.isEmpty() && contextItems.isEmpty()) { return; } if (!contextBlocks.isEmpty()) { final List<BlockSnapshot> blockSnapshots = new ArrayList<>(contextBlocks); contextBlocks.clear(); GeneralPhase.processBlockTransactionListsPost(postContext, blockSnapshots, this, unwindingContext); } if (!contextEntities.isEmpty()) { final ArrayList<Entity> entities = new ArrayList<>(contextEntities); contextEntities.clear(); ((IPhaseState) unwindingState).postProcessSpawns(unwindingContext, entities); } if (!contextItems.isEmpty()) { final ArrayList<Entity> items = new ArrayList<>(contextItems); contextItems.clear(); TrackingUtil.splitAndSpawnEntities(items); } } @Override public boolean spawnEntityOrCapture(UnwindingPhaseContext context, Entity entity, int chunkX, int chunkZ) { return context.getCapturedEntities().add(entity); } }
package com.xpn.xwiki.web; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.XWikiLock; /** * Action used for saving and proceeding to view the saved page. * Used as a generic action for saving documents. * * @version $Id$ */ public class SaveAction extends PreviewAction { /** The identifier of the save action. */ public static final String ACTION_NAME = "save"; /** * Saves the current document, updated according to the parameters sent in the request. * * @param context The current request {@link XWikiContext context}. * @return <code>true</code> if there was an error and the response needs to render an error page, * <code>false</code> if the document was correctly saved. * @throws XWikiException If an error occured: cannot communicate with the storage module, or cannot update the * document because the request contains invalid parameters. */ public boolean save(XWikiContext context) throws XWikiException { XWiki xwiki = context.getWiki(); XWikiRequest request = context.getRequest(); XWikiDocument doc = context.getDoc(); XWikiForm form = context.getForm(); // This is pretty useless, since contexts aren't shared between threads. // It just slows down execution. String title = doc.getTitle(); // Check save session int sectionNumber = 0; if (request.getParameter("section") != null && xwiki.hasSectionEdit(context)) { sectionNumber = Integer.parseInt(request.getParameter("section")); } // We need to clone this document first, since a cached storage would return the same object for the // following requests, so concurrent request might get a partially modified object, or worse, if an error // occurs during the save, the cached object will not reflect the actual document at all. doc = (XWikiDocument) doc.clone(); String language = ((EditForm) form).getLanguage(); // FIXME Which one should be used: doc.getDefaultLanguage or // form.getDefaultLanguage()? // String defaultLanguage = ((EditForm) form).getDefaultLanguage(); XWikiDocument tdoc; if (doc.isNew() || (language == null) || (language.equals("")) || (language.equals("default")) || (language.equals(doc.getDefaultLanguage()))) { // Need to save parent and defaultLanguage if they have changed tdoc = doc; } else { tdoc = doc.getTranslatedDocument(language, context); if ((tdoc == doc) && xwiki.isMultiLingual(context)) { tdoc = new XWikiDocument(doc.getSpace(), doc.getName()); tdoc.setLanguage(language); tdoc.setStore(doc.getStore()); } else if (tdoc != doc) { // Same as above, clone the object retrieved from the store cache. tdoc = (XWikiDocument) tdoc.clone(); } tdoc.setTranslation(1); } if (doc.isNew()) { doc.setLanguage(""); if ((doc.getDefaultLanguage() == null) || (doc.getDefaultLanguage().equals(""))) { doc.setDefaultLanguage(context.getWiki().getLanguagePreference(context)); } } try { tdoc.readFromTemplate(((EditForm) form).getTemplate(), context); } catch (XWikiException e) { if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) { context.put("exception", e); return true; } } if (sectionNumber != 0) { XWikiDocument sectionDoc = (XWikiDocument) tdoc.clone(); sectionDoc.readFromForm((EditForm) form, context); String sectionContent = sectionDoc.getContent() + "\n"; String content = doc.updateDocumentSection(sectionNumber, sectionContent); tdoc.setContent(content); tdoc.setTitle(title); tdoc.setComment(sectionDoc.getComment()); tdoc.setMinorEdit(sectionDoc.isMinorEdit()); } else { tdoc.readFromForm((EditForm) form, context); } // TODO: handle Author String username = context.getUser(); tdoc.setAuthor(username); if (tdoc.isNew()) { tdoc.setCreator(username); } // Make sure we have at least the meta data dirty status tdoc.setMetaDataDirty(true); // Validate the document if we have xvalidate=1 in the request if ("1".equals(request.getParameter("xvalidate"))) { boolean validationResult = tdoc.validate(context); // if the validation fails we should show the inline action if (validationResult == false) { // Set display context to 'edit' context.put("display", "edit"); // Set the action to inline context.setAction("inline"); // Set the document in the context VelocityContext vcontext = (VelocityContext) context.get("vcontext"); context.put("doc", doc); context.put("cdoc", tdoc); context.put("tdoc", tdoc); Document vdoc = tdoc.newDocument(context); vcontext.put("doc", doc.newDocument(context)); vcontext.put("cdoc", vdoc); vcontext.put("tdoc", vdoc); return true; } } // We get the comment to be used from the document // It was read using readFromForm xwiki.saveDocument(tdoc, tdoc.getComment(), tdoc.isMinorEdit(), context); XWikiLock lock = tdoc.getLock(context); if (lock != null) { tdoc.removeLock(context); } return false; } /** * {@inheritDoc} * * @see XWikiAction#action(XWikiContext) */ @Override public boolean action(XWikiContext context) throws XWikiException { if (save(context)) { return true; } // forward to view if (Utils.isAjaxRequest(context)) { context.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT); } else { sendRedirect(context.getResponse(), Utils.getRedirect("view", context)); } return false; } /** * {@inheritDoc} * * @see XWikiAction#render(XWikiContext) */ @Override public String render(XWikiContext context) throws XWikiException { XWikiException e = (XWikiException) context.get("exception"); if ((e != null) && (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY)) { return "docalreadyexists"; } return "exception"; } }
package tv.floe.metronome.deeplearning.dbn.model.evaluation; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.mahout.math.Matrix; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tv.floe.metronome.berkley.Pair; import tv.floe.metronome.deeplearning.datasets.DataSet; import tv.floe.metronome.deeplearning.datasets.iterator.BaseDatasetIterator; import tv.floe.metronome.deeplearning.datasets.iterator.impl.MnistDataSetIterator; import tv.floe.metronome.deeplearning.neuralnetwork.core.BaseMultiLayerNeuralNetworkVectorized; import tv.floe.metronome.eval.Evaluation; public class ModelTester { private static Logger log = LoggerFactory.getLogger(ModelTester.class); public static void evaluateModel( BaseDatasetIterator iterator, BaseMultiLayerNeuralNetworkVectorized model ) throws IOException { Evaluation eval = new Evaluation(); //BaseMultiLayerNeuralNetworkVectorized load = BaseMultiLayerNeuralNetworkVectorized.loadFromFile(new FileInputStream(new File(modelLocation))); while (iterator.hasNext()) { DataSet inputs = iterator.next(); Matrix in = inputs.getFirst(); Matrix outcomes = inputs.getSecond(); Matrix predicted = model.predict(in); eval.eval( outcomes, predicted ); } log.warn( "evaluateModel" ); log.info( eval.stats() ); //writeReportToDisk( eval, pathForReport ); } public static void evaluateModel( Matrix inputs, Matrix labels, BaseMultiLayerNeuralNetworkVectorized model ) throws IOException { Evaluation eval = new Evaluation(); //BaseMultiLayerNeuralNetworkVectorized load = BaseMultiLayerNeuralNetworkVectorized.loadFromFile(new FileInputStream(new File(modelLocation))); // while (iterator.hasNext()) { // DataSet inputs = iterator.next(); // Matrix in = inputs.getFirst(); // Matrix outcomes = inputs.getSecond(); Matrix predicted = model.predict(inputs); eval.eval( labels, predicted ); log.warn( "evaluateModel" ); log.info( eval.stats() ); //writeReportToDisk( eval, pathForReport ); } public static void evaluateSavedModel( BaseDatasetIterator iterator, String modelLocation, String pathForReport ) throws IOException { Evaluation eval = new Evaluation(); BaseMultiLayerNeuralNetworkVectorized load = BaseMultiLayerNeuralNetworkVectorized.loadFromFile(new FileInputStream(new File(modelLocation))); while (iterator.hasNext()) { DataSet inputs = iterator.next(); Matrix in = inputs.getFirst(); Matrix outcomes = inputs.getSecond(); Matrix predicted = load.predict(in); eval.eval( outcomes, predicted ); } log.info( eval.stats() ); writeReportToDisk( eval, pathForReport ); } public static void writeReportToDisk( Evaluation eval, String fileLocation ) throws IOException { // open files somewhere File yourFile = new File(fileLocation); if(!yourFile.exists()) { yourFile.createNewFile(); } FileOutputStream oFile = new FileOutputStream(fileLocation, false); oFile.write(eval.stats().getBytes() ); oFile.close(); } /** * @param args * @throws IOException */ /* public static void main(String[] args) throws IOException { MnistDataSetIterator iter = new MnistDataSetIterator(10, 60000); Evaluation eval = new Evaluation(); BaseMultiLayerNeuralNetworkVectorized load = BaseMultiLayerNeuralNetworkVectorized.loadFromFile(new FileInputStream(new File(args[0]))); while (iter.hasNext()) { DataSet inputs = iter.next(); Matrix in = inputs.getFirst(); Matrix outcomes = inputs.getSecond(); Matrix predicted = load.predict(in); eval.eval( outcomes, predicted ); } log.info( eval.stats() ); } */ }
package i5.las2peer.services.codeGenerationService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Properties; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import i5.cae.simpleModel.SimpleModel; import i5.las2peer.p2p.LocalNode; import i5.las2peer.security.ServiceAgent; import i5.las2peer.services.codeGenerationService.generators.Generator; import i5.las2peer.services.codeGenerationService.generators.exception.GitHubException; /** * * Central test class for the CAE-Code-Generation-Service. * */ public class CodeGenerationServiceTest { private static LocalNode node; private static final String codeGenerationService = CodeGenerationService.class.getCanonicalName(); private static SimpleModel model1; private static SimpleModel model2; private static SimpleModel model3; private static ServiceAgent testService; private static String gitHubOrganization = null; private static String gitHubUser = null; private static String gitHubPassword = null; @SuppressWarnings("unused") private static String gitHubUserMail = null; @SuppressWarnings("unused") private static String templateRepository = null; /** * * Called before the tests start. Sets up the node and loads test models for later usage. * * @throws Exception * */ @BeforeClass public static void startServer() throws Exception { // load models String modelPath1 = "./testModels/My First Testservice.model"; String modelPath2 = "./testModels/My First Testservice without DB.model"; String modelPath3 = "./testModels/minimal widget test.model"; Properties properties = new Properties(); String propertiesFile = "./etc/i5.las2peer.services.codeGenerationService.CodeGenerationService.properties"; try { InputStream file1 = new FileInputStream(modelPath1); InputStream buffer1 = new BufferedInputStream(file1); ObjectInput input1 = new ObjectInputStream(buffer1); model1 = (SimpleModel) input1.readObject(); InputStream file2 = new FileInputStream(modelPath2); InputStream buffer2 = new BufferedInputStream(file2); ObjectInput input2 = new ObjectInputStream(buffer2); model2 = (SimpleModel) input2.readObject(); InputStream file3 = new FileInputStream(modelPath3); InputStream buffer3 = new BufferedInputStream(file3); ObjectInput input3 = new ObjectInputStream(buffer3); model3 = (SimpleModel) input3.readObject(); input1.close(); input2.close(); input3.close(); FileReader reader = new FileReader(propertiesFile); properties.load(reader); gitHubUser = properties.getProperty("gitHubUser"); gitHubUserMail = properties.getProperty("gitHubUserMail"); gitHubOrganization = properties.getProperty("gitHubOrganization"); templateRepository = properties.getProperty("templateRepository"); gitHubPassword = properties.getProperty("gitHubPassword"); } catch (IOException ex) { fail("Error reading test models and configuration file!"); } // start node node = LocalNode.newNode(); node.launch(); testService = ServiceAgent.generateNewAgent(codeGenerationService, "a pass"); testService.unlockPrivateKey("a pass"); node.registerReceiver(testService); // waiting here not needed because no connector is running! } /** * * Called after the tests have finished. Deletes all test repositories and shuts down the server. * Just comment out repositories you want to check on after the tests. * * @throws Exception * */ @AfterClass public static void shutDownServer() throws Exception { String model1GitHubName = "microservice-" + model1.getName().replace(" ", "-"); String model2GitHubName = "microservice-" + model2.getName().replace(" ", "-"); String model3GitHubName = "frontendComponent-" + model3.getName().replace(" ", "-"); try { Generator.deleteRemoteRepository(model1GitHubName, gitHubOrganization, gitHubUser, gitHubPassword); } catch (GitHubException e) { e.printStackTrace(); // that's ok, maybe some error / failure in previous tests caused this // catch this, to make sure that every other repository gets deleted } try { Generator.deleteRemoteRepository(model2GitHubName, gitHubOrganization, gitHubUser, gitHubPassword); } catch (GitHubException e) { e.printStackTrace(); // that's ok, maybe some error / failure in previous tests caused this // catch this, to make sure that every other repository gets deleted } try { Generator.deleteRemoteRepository(model3GitHubName, gitHubOrganization, gitHubUser, gitHubPassword); } catch (GitHubException e) { e.printStackTrace(); // that's ok, maybe some error / failure in previous tests caused this // catch this, to make sure that every other repository gets deleted } node.shutDown(); node = null; LocalNode.reset(); } /** * * Posts a new microservice model to the service. * */ @Test public void testCreateMicroservice() { Serializable[] parameters = {(Serializable) model1}; try { String returnMessage = (String) node.invokeLocally(testService.getId(), "i5.las2peer.services.codeGenerationService.CodeGenerationService", "createFromModel", parameters); assertEquals("done", returnMessage); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * * Posts a new frontend component model to the service. * */ @Test public void testCreateFrontendComponent() { Serializable[] parameters = {(Serializable) model3}; try { String returnMessage = (String) node.invokeLocally(testService.getId(), "i5.las2peer.services.codeGenerationService.CodeGenerationService", "createFromModel", parameters); assertEquals("done", returnMessage); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * * Posts a new model to the service and then tries to delete it. * */ @Test public void testDeleteModel() { Serializable[] parameters = {(Serializable) model2}; try { String returnMessage = (String) node.invokeLocally(testService.getId(), "i5.las2peer.services.codeGenerationService.CodeGenerationService", "createFromModel", parameters); assertEquals("done", returnMessage); returnMessage = (String) node.invokeLocally(testService.getId(), "i5.las2peer.services.codeGenerationService.CodeGenerationService", "deleteRepositoryOfModel", parameters); assertEquals("done", returnMessage); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } /** * * Posts a new model to the service and then tries to update it (with the same model). * */ @Test public void testUpdate() { Serializable[] parameters = {(Serializable) model2}; try { String returnMessage = (String) node.invokeLocally(testService.getId(), "i5.las2peer.services.codeGenerationService.CodeGenerationService", "createFromModel", parameters); assertEquals("done", returnMessage); returnMessage = (String) node.invokeLocally(testService.getId(), "i5.las2peer.services.codeGenerationService.CodeGenerationService", "updateRepositoryOfModel", parameters); assertEquals("done", returnMessage); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }
package com.jetbrains.python; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.testFramework.TestDataFile; import com.intellij.testFramework.TestDataPath; import com.jetbrains.python.codeInsight.PyCodeInsightSettings; import com.jetbrains.python.documentation.DocStringFormat; import com.jetbrains.python.documentation.PyDocumentationSettings; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.inspections.*; import com.jetbrains.python.psi.LanguageLevel; import org.jetbrains.annotations.NonNls; @TestDataPath("$CONTENT_ROOT/../testData/inspections/") public class PyQuickFixTest extends PyTestCase { public void testAddImport() { doInspectionTest(new String[] { "AddImport.py", "ImportTarget.py" }, PyUnresolvedReferencesInspection.class, PyBundle.message("ACT.NAME.use.import"), true, true); } public void testAddImportDoc() { doInspectionTest(new String[] { "AddImportDoc.py", "ImportTarget.py" }, PyUnresolvedReferencesInspection.class, PyBundle.message("ACT.NAME.use.import"), true, true); } public void testAddImportDocComment() { // PY-728 doInspectionTest(new String[] { "AddImportDocComment.py", "ImportTarget.py" }, PyUnresolvedReferencesInspection.class, PyBundle.message("ACT.NAME.use.import"), true, true); } public void testImportFromModule() { doInspectionTest(new String[] { "importFromModule/foo/bar.py", "importFromModule/foo/baz.py", "importFromModule/foo/__init__.py" }, PyUnresolvedReferencesInspection.class, PyBundle.message("ACT.NAME.use.import"), true, true); } public void testImportFromModuleStar() { // PY-6302 myFixture.enableInspections(PyUnresolvedReferencesInspection.class); myFixture.copyDirectoryToProject("importFromModuleStar", ""); myFixture.configureFromTempProjectFile("source.py"); myFixture.checkHighlighting(true, false, false); final IntentionAction intentionAction = myFixture.findSingleIntention(PyBundle.message("ACT.NAME.use.import")); assertNotNull(intentionAction); myFixture.launchAction(intentionAction); myFixture.checkResultByFile("importFromModuleStar/source_after.py"); } public void testQualifyByImport() { final PyCodeInsightSettings settings = PyCodeInsightSettings.getInstance(); boolean oldPreferFrom = settings.PREFER_FROM_IMPORT; boolean oldHighlightUnused = settings.HIGHLIGHT_UNUSED_IMPORTS; settings.PREFER_FROM_IMPORT = false; settings.HIGHLIGHT_UNUSED_IMPORTS = false; try { doInspectionTest(new String[]{"QualifyByImport.py", "QualifyByImportFoo.py"}, PyUnresolvedReferencesInspection.class, PyBundle.message("ACT.qualify.with.module"), true, true); } finally { settings.PREFER_FROM_IMPORT = oldPreferFrom; settings.HIGHLIGHT_UNUSED_IMPORTS = oldHighlightUnused; } } public void testAddToImportFromList() { final PyCodeInsightSettings settings = PyCodeInsightSettings.getInstance(); boolean oldHighlightUnused = settings.HIGHLIGHT_UNUSED_IMPORTS; settings.HIGHLIGHT_UNUSED_IMPORTS = false; try { doInspectionTest(new String[]{"AddToImportFromList.py", "AddToImportFromFoo.py"}, PyUnresolvedReferencesInspection.class, PyBundle.message("ACT.NAME.use.import"), true, true); } finally { settings.HIGHLIGHT_UNUSED_IMPORTS = oldHighlightUnused; } } // TODO: add a test for multiple variants of above // TODO: add tests for stub indexes-based autoimport of unimported somehow. public void testAddSelf() { doInspectionTest("AddSelf.py", PyMethodParametersInspection.class, PyBundle.message("QFIX.add.parameter.self", "self"), true, true); } public void testAddSelfFunction() { //PY-4556 doInspectionTest("AddSelfFunction.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference", "get_a"), true, true); } public void testAddCls() { doInspectionTest("AddCls.py", PyMethodParametersInspection.class, PyBundle.message("QFIX.add.parameter.self", "cls"), true, true); } public void testRenameToSelf() { doInspectionTest("RenameToSelf.py", PyMethodParametersInspection.class, PyBundle.message("QFIX.rename.parameter.to.$0", "self"), true, true); } public void testAddFieldFromMethod() { doInspectionTest("AddFieldFromMethod.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.field.$0.to.class.$1", "y", "A"), true, true); } public void testAddFieldFromInstance() { doInspectionTest("AddFieldFromInstance.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.field.$0.to.class.$1", "y", "A"), true, true); } public void testAddFieldAddConstructor() { doInspectionTest("AddFieldAddConstructor.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.field.$0.to.class.$1", "x", "B"), true, true); } public void testAddFieldNewConstructor() { doInspectionTest("AddFieldNewConstructor.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.field.$0.to.class.$1", "x", "B"), true, true); } public void testAddMethodFromInstance() { doInspectionTest("AddMethodFromInstance.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.method.$0.to.class.$1", "y", "A"), true, true); } public void testAddMethodFromMethod() { doInspectionTest("AddMethodFromMethod.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.method.$0.to.class.$1", "y", "A"), true, true); } public void testRemoveTrailingSemicolon() { doInspectionTest("RemoveTrailingSemicolon.py", PyTrailingSemicolonInspection.class, PyBundle.message("QFIX.remove.trailing.semicolon"), true, true); } public void testDictCreation() { doInspectionTest("DictCreation.py", PyDictCreationInspection.class, PyBundle.message("QFIX.dict.creation"), true, true); } public void testDictCreationTuple() { //PY-6283 doInspectionTest("DictCreationTuple.py", PyDictCreationInspection.class, PyBundle.message("QFIX.dict.creation"), true, true); } public void testTransformClassicClass() { doInspectionTest("TransformClassicClass.py", PyClassicStyleClassInspection.class, PyBundle.message("QFIX.classic.class.transform"), true, true); } public void testAddGlobalQuickFix() { doInspectionTest("AddGlobalStatement.py", PyUnboundLocalVariableInspection.class, PyBundle.message("QFIX.add.global"), true, true); } public void testAddGlobalExistingQuickFix() { doInspectionTest("AddGlobalExistingStatement.py", PyUnboundLocalVariableInspection.class, PyBundle.message("QFIX.add.global"), true, true); } public void testSimplifyBooleanCheckQuickFix() { doInspectionTest("SimplifyBooleanCheck.py", PySimplifyBooleanCheckInspection.class, PyBundle.message("QFIX.simplify.$0", "b"), true, true); } public void testFromFutureImportQuickFix() { doInspectionTest("MoveFromFutureImport.py", PyFromFutureImportInspection.class, PyBundle.message("QFIX.move.from.future.import"), true, true); } public void testComparisonWithNoneQuickFix() { doInspectionTest("ComparisonWithNone.py", PyComparisonWithNoneInspection.class, PyBundle.message("QFIX.replace.equality"), true, true); } public void testAddClassFix() { doInspectionTest("AddClass.py", PyUnresolvedReferencesInspection.class, "Create class 'Xyzzy'", true, true); } public void testFieldFromUnusedParameter() { // PY-1398 doInspectionTest("FieldFromUnusedParameter.py", PyUnusedLocalInspection.class, "Add field 'foo' to class A", true, true); } public void testFieldFromUnusedParameterKeyword() { // PY-1602 doInspectionTest("FieldFromUnusedParameterKeyword.py", PyUnusedLocalInspection.class, "Add field 'foo' to class A", true, true); } public void testAddFunctionToModule() { // PY-1602 doInspectionTest( "AddFunctionToModule.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.NAME.add.function.$0.to.module.$1", "frob", "AddFunctionToModule.py"), true, true ); } public void testRedundantParentheses() { // PY-1470 String[] testFiles = new String[]{"RedundantParentheses.py"}; myFixture.enableInspections(PyRedundantParenthesesInspection.class); myFixture.configureByFiles(testFiles); myFixture.checkHighlighting(true, false, true); final IntentionAction intentionAction = myFixture.findSingleIntention(PyBundle.message("QFIX.redundant.parentheses")); assertNotNull(intentionAction); myFixture.launchAction(intentionAction); myFixture.checkResultByFile(graftBeforeExt(testFiles[0], "_after")); } public void testRedundantParenthesesBoolean() { // PY-3095 doInspectionTest("RedundantParenthesesBoolean.py", PyRedundantParenthesesInspection.class, PyBundle.message("QFIX.redundant.parentheses"), true, true); } public void testRedundantParenthesesMore() { // PY-3239 doInspectionTest("RedundantParenthesesMore.py", PyRedundantParenthesesInspection.class, PyBundle.message("QFIX.redundant.parentheses"), true, true); } public void testAugmentAssignment() { // PY-1415 doInspectionTest("AugmentAssignment.py", PyAugmentAssignmentInspection.class, PyBundle.message("QFIX.augment.assignment"), true, true); } public void testAugmentAssignmentWithContext() { // PY-2481 doInspectionTest("AugmentAssignmentWithContext.py", PyAugmentAssignmentInspection.class, PyBundle.message("QFIX.augment.assignment"), true, true); } public void testAugmentAssignmentPerc() { // PY-3197 doInspectionTest("AugmentAssignmentPerc.py", PyAugmentAssignmentInspection.class, PyBundle.message("QFIX.augment.assignment"), true, true); } public void testAugmentAssignment1() { // PY-5037 doInspectionTest("AugmentAssignment1.py", PyAugmentAssignmentInspection.class, PyBundle.message("QFIX.augment.assignment"), true, true); } public void testAugmentAssignment2() { // PY-6331 doInspectionTest("AugmentAssignment2.py", PyAugmentAssignmentInspection.class, PyBundle.message("QFIX.augment.assignment"), true, true); } public void testAugmentAssignmentFunction() { // PY-6678 doInspectionTest("AugmentAssignmentFunction.py", PyAugmentAssignmentInspection.class, PyBundle.message("QFIX.augment.assignment"), true, true); } public void testChainedComparisons() { // PY-1020 doInspectionTest("ChainedComparisons.py", PyChainedComparisonsInspection.class, PyBundle.message("QFIX.chained.comparison"), true, true); } public void testChainedComparison1() { // PY-3126 doInspectionTest("ChainedComparison1.py", PyChainedComparisonsInspection.class, PyBundle.message("QFIX.chained.comparison"), true, true); } public void testChainedComparison2() { // PY-3126 doInspectionTest("ChainedComparison2.py", PyChainedComparisonsInspection.class, PyBundle.message("QFIX.chained.comparison"), true, true); } public void testChainedComparison3() { // PY-3126 doInspectionTest("ChainedComparison3.py", PyChainedComparisonsInspection.class, PyBundle.message("QFIX.chained.comparison"), true, true); } public void testChainedComparison4() { // PY-5623 doInspectionTest("ChainedComparison4.py", PyChainedComparisonsInspection.class, PyBundle.message("QFIX.chained.comparison"), true, true); } public void testChainedComparison5() { // PY-6467 doInspectionTest("ChainedComparison5.py", PyChainedComparisonsInspection.class, PyBundle.message("QFIX.chained.comparison"), true, true); } public void testStatementEffect() { // PY-1362, PY-2585 doInspectionTest("StatementEffect.py", PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect"), true, true); } public void testStatementEffectIntroduceVariable() { // PY-1265 doInspectionTest("StatementEffectIntroduceVariable.py", PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect.introduce.variable"), true, true); } public void testUnresolvedWith() { // PY-2083 setLanguageLevel(LanguageLevel.PYTHON25); doInspectionTest("UnresolvedWith.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference.add.future"), true, true); } public void testUnresolvedRefCreateFunction() { // PY-2092 doInspectionTest("UnresolvedRefCreateFunction.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference.create.function.$0", "ref"), true, true); } public void testReplaceNotEqOperator() { doInspectionTest("ReplaceNotEqOperator.py", PyCompatibilityInspection.class, PyBundle.message("INTN.replace.noteq.operator"), true, true); } public void testListCreation() { doInspectionTest("ListCreation.py", PyListCreationInspection.class, PyBundle.message("QFIX.list.creation"), true, true); } public void testConvertSingleQuotedDocstring() { //PY-1445 doInspectionTest("ConvertSingleQuotedDocstring.py", PySingleQuotedDocstringInspection.class, PyBundle.message("QFIX.convert.single.quoted.docstring"), true, true); } public void testDefaultArgument() { //PY-3127 doInspectionTest("DefaultArgument.py", PyDefaultArgumentInspection.class, PyBundle.message("QFIX.default.argument"), true, true); } public void testPyArgumentEqualDefault() { //PY-3125 doInspectionTest("ArgumentEqualDefault.py", PyArgumentEqualDefaultInspection.class, PyBundle.message("QFIX.remove.argument.equal.default"), true, true); } public void testAddCallSuper() { //PY-3315 doInspectionTest("AddCallSuper.py", PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); } public void testAddCallSuper1() { //PY-4017 doInspectionTest("AddCallSuper1.py", PyMissingConstructorInspection.class, PyBundle.message("QFIX.add.super"), true, true); } public void testAddEncoding() { //PY-491 doInspectionTest("AddEncoding.py", PyMandatoryEncodingInspection.class, PyBundle.message("QFIX.add.encoding"), true, true); } public void testRemoveDecorator() { //PY-3348 doInspectionTest("RemoveDecorator.py", PyDecoratorInspection.class, PyBundle.message("QFIX.remove.decorator"), true, true); } public void testAddParameter() { doInspectionTest("AddParameter.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference.add.param.$0", "test"), true, true); } public void testMoveDocstring() { //PY-4398 doInspectionTest("MoveDocstring.py", PyStatementEffectInspection.class, PyBundle.message("QFIX.statement.effect.move.docstring"), true, true); } public void testSetFunctionToLiteral() { //PY-3120 setLanguageLevel(LanguageLevel.PYTHON27); doInspectionTest("SetFunctionToLiteral.py", PySetFunctionToLiteralInspection.class, PyBundle.message("QFIX.replace.function.set.with.literal"), true, true); } public void testDocstringParams() { //PY-3394 PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(myFixture.getProject()); documentationSettings.setFormat(DocStringFormat.EPYTEXT); try { doInspectionTest("DocstringParams.py", PyDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "b"), true, true); } finally { documentationSettings.setFormat(DocStringFormat.PLAIN); } } public void testDocstringParams1() { PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(myFixture.getProject()); documentationSettings.setFormat(DocStringFormat.EPYTEXT); try { doInspectionTest("DocstringParams1.py", PyDocstringInspection.class, PyBundle.message("QFIX.docstring.remove.$0", "c"), true, true); } finally { documentationSettings.setFormat(DocStringFormat.PLAIN); } } public void testDocstringParams2() { //PY-4964 PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(myFixture.getProject()); documentationSettings.setFormat(DocStringFormat.EPYTEXT); try { doInspectionTest("DocstringParams2.py", PyDocstringInspection.class, PyBundle.message("QFIX.docstring.add.$0", "ham"), true, true); } finally { documentationSettings.setFormat(DocStringFormat.PLAIN); } } public void testUnnecessaryBackslash() { String[] testFiles = new String[]{"UnnecessaryBackslash.py"}; myFixture.enableInspections(PyUnnecessaryBackslashInspection.class); myFixture.configureByFiles(testFiles); myFixture.checkHighlighting(true, false, true); IntentionAction intentionAction = myFixture.getAvailableIntention(PyBundle.message("QFIX.remove.unnecessary.backslash")); myFixture.launchAction(intentionAction); myFixture.checkResultByFile(graftBeforeExt(testFiles[0], "_after")); } public void testUnresolvedRefTrueFalse() { //PY-3051 doInspectionTest("UnresolvedRefTrueFalse.py", PyUnresolvedReferencesInspection.class, PyBundle.message("QFIX.unresolved.reference.replace.$0", "True"), true, true); } public void testUnnecessaryBackslashInArgumentList() { String[] testFiles = new String[]{"UnnecessaryBackslashInArguments.py"}; myFixture.enableInspections(PyUnnecessaryBackslashInspection.class); myFixture.configureByFiles(testFiles); myFixture.checkHighlighting(true, false, true); IntentionAction intentionAction = myFixture.getAvailableIntention(PyBundle.message("QFIX.remove.unnecessary.backslash")); myFixture.launchAction(intentionAction); myFixture.checkResultByFile(graftBeforeExt(testFiles[0], "_after")); } @Override @NonNls protected String getTestDataPath() { return PythonTestUtil.getTestDataPath() + "/inspections/"; } protected void doInspectionTest(@TestDataFile @NonNls String testFileName, final Class inspectionClass, @NonNls String quickFixName, boolean applyFix, boolean available) { doInspectionTest(new String[]{testFileName}, inspectionClass, quickFixName, applyFix, available); } /** * Runs daemon passes and looks for given fix within infos. * * @param testFiles names of files to participate; first is used for inspection and then for check by "_after". * @param inspectionClass what inspection to run * @param quickFixName how the resulting fix should be named (the human-readable name users see) * @param applyFix true if the fix needs to be applied * @param available true if the fix should be available, false if it should be explicitly not available. * @throws Exception */ protected void doInspectionTest(@NonNls String[] testFiles, final Class inspectionClass, @NonNls String quickFixName, boolean applyFix, boolean available) { myFixture.enableInspections(inspectionClass); myFixture.configureByFiles(testFiles); myFixture.checkHighlighting(true, false, false); final IntentionAction intentionAction = myFixture.findSingleIntention(quickFixName); if (available) { assertNotNull(intentionAction); if (applyFix) { myFixture.launchAction(intentionAction); myFixture.checkResultByFile(graftBeforeExt(testFiles[0], "_after")); } } else { assertNull(intentionAction); } } // Turns "name.ext" to "name_insertion.ext" @NonNls private static String graftBeforeExt(String name, String insertion) { int dotpos = name.indexOf('.'); if (dotpos < 0) dotpos = name.length(); return name.substring(0, dotpos) + insertion + name.substring(dotpos, name.length()); } }
package com.brightsparklabs.asanti.decoder.builtin; import com.brightsparklabs.asanti.common.DecodeException; import com.brightsparklabs.asanti.model.data.DecodedAsnData; import com.google.common.base.Charsets; import org.junit.Test; import static org.junit.Assert.*; /** * Units tests for {@link BitStringDecoder} * * @author brightSPARK Labs */ public class BitStringDecoderTest { // FIXTURES /** instance under test */ private static final BitStringDecoder instance = BitStringDecoder.getInstance(); // TESTS @Test public void testDecode() throws Exception { { // TODO (ASN-120 review) - here is my interpretation of how we should be able to decode. byte[] bytes = { (byte)0x05, (byte)0xE0 }; assertEquals("111", instance.decode(bytes)); bytes = new byte [] { (byte)0x04, (byte)0xE0 }; assertEquals("1110", instance.decode(bytes)); bytes = new byte [] { (byte)0x00, (byte)0xFF }; assertEquals("11111111", instance.decode(bytes)); // showing how the length octect forces to ignore trailing bits of last octet bytes = new byte [] { (byte)0x07, (byte)0xFF }; assertEquals("1", instance.decode(bytes)); bytes = new byte [] { (byte)0x07, (byte)0x00 }; assertEquals("0", instance.decode(bytes)); bytes = new byte [] { (byte)0x06, (byte)0xAA, (byte)0x80 }; assertEquals("1010101010", instance.decode(bytes)); // empty string bytes = new byte [] { (byte)0x00 }; assertEquals("", instance.decode(bytes)); // I think this should throw (ie not validate) try { bytes = new byte[] {}; instance.decode(bytes); fail("DecodeException not thrown"); } catch (DecodeException e) { } } // test valid single byte values byte[] bytes = new byte[1]; for (int b = Byte.MAX_VALUE; b >= Byte.MIN_VALUE; b { bytes[0] = (byte) b; final String binaryString = String.format("%8s", Integer.toBinaryString(b & 0xFF)) .replace(' ', '0'); assertEquals(binaryString, instance.decode(bytes)); } // test valid - two bytes (minimum/maximum) bytes = new byte[] { (byte) 0b11000010, (byte) 0b10000000 }; assertEquals("1100001010000000", instance.decode(bytes)); bytes = new byte[] { (byte) 0b11011111, (byte) 0b10111111 }; assertEquals("1101111110111111", instance.decode(bytes)); // test valid - three bytes (minimum/maximum) bytes = new byte[] { (byte) 0b11100010, (byte) 0b10000000, (byte) 0b10000000 }; assertEquals("111000101000000010000000", instance.decode(bytes)); bytes = new byte[] { (byte) 0b11101111, (byte) 0b10111111, (byte) 0b10111111 }; assertEquals("111011111011111110111111", instance.decode(bytes)); // test valid - four bytes (minimum/maximum) bytes = new byte[] { (byte) 0b11110010, (byte) 0b10000000, (byte) 0b10000000, (byte) 0b10000000 }; assertEquals("11110010100000001000000010000000", instance.decode(bytes)); bytes = new byte[] { (byte) 0b11110000, (byte) 0b10111111, (byte) 0b10111111, (byte) 0b10111111 }; assertEquals("11110000101111111011111110111111", instance.decode(bytes)); //test null try { instance.decode(null); fail("DecodeException not thrown"); } catch (DecodeException ex) { } } @Test public void testDecodeAsString() throws Exception { // test valid single byte values byte[] bytes = new byte[1]; for (int b = Byte.MAX_VALUE; b >= Byte.MIN_VALUE; b { bytes[0] = (byte) b; final String binaryString = String.format("%8s", Integer.toBinaryString(b & 0xFF)) .replace(' ', '0'); assertEquals(binaryString, instance.decodeAsString(bytes)); } // test valid - two bytes (minimum/maximum) bytes = new byte[] { (byte) 0b11000010, (byte) 0b10000000 }; assertEquals("1100001010000000", instance.decodeAsString(bytes)); bytes = new byte[] { (byte) 0b11011111, (byte) 0b10111111 }; assertEquals("1101111110111111", instance.decodeAsString(bytes)); // test valid - three bytes (minimum/maximum) bytes = new byte[] { (byte) 0b11100010, (byte) 0b10000000, (byte) 0b10000000 }; assertEquals("111000101000000010000000", instance.decodeAsString(bytes)); bytes = new byte[] { (byte) 0b11101111, (byte) 0b10111111, (byte) 0b10111111 }; assertEquals("111011111011111110111111", instance.decodeAsString(bytes)); // test valid - four bytes (minimum/maximum) bytes = new byte[] { (byte) 0b11110010, (byte) 0b10000000, (byte) 0b10000000, (byte) 0b10000000 }; assertEquals("11110010100000001000000010000000", instance.decodeAsString(bytes)); bytes = new byte[] { (byte) 0b11110000, (byte) 0b10111111, (byte) 0b10111111, (byte) 0b10111111 }; assertEquals("11110000101111111011111110111111", instance.decodeAsString(bytes)); // test null try { instance.decodeAsString(null); fail("DecodeException not thrown"); } catch (DecodeException ex) { } } }
package org.zalando.nakadi.service.subscription.state; import org.junit.BeforeClass; import org.junit.Test; import org.zalando.nakadi.domain.ConsumedEvent; import org.zalando.nakadi.domain.NakadiCursor; import org.zalando.nakadi.domain.Storage; import org.zalando.nakadi.domain.Timeline; import org.zalando.nakadi.repository.kafka.KafkaCursor; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PartitionDataTest { private static Timeline firstTimeline = mock(Timeline.class); private static final Comparator<NakadiCursor> COMP = Comparator.comparing(NakadiCursor::getOffset); @BeforeClass public static void initTimeline() { when(firstTimeline.getStorage()).thenReturn(new Storage("", Storage.Type.KAFKA)); } private static NakadiCursor createCursor(final long offset) { return new KafkaCursor("x", 0, offset).toNakadiCursor(firstTimeline); } @Test public void onNewOffsetsShouldSupportRollback() { final PartitionData pd = new PartitionData(COMP, null, createCursor(100L), System.currentTimeMillis()); final PartitionData.CommitResult cr = pd.onCommitOffset(createCursor(90L)); assertEquals(0L, cr.committedCount); assertEquals(true, cr.seekOnKafka); assertEquals(90L, Long.parseLong(pd.getSentOffset().getOffset())); assertEquals(0L, pd.getUnconfirmed()); } @Test public void onNewOffsetsShouldSupportCommitInFuture() { final PartitionData pd = new PartitionData(COMP, null, createCursor(100L), System.currentTimeMillis()); final PartitionData.CommitResult cr = pd.onCommitOffset(createCursor(110L)); assertEquals(0L, cr.committedCount); assertEquals(true, cr.seekOnKafka); assertEquals(110L, Long.parseLong(pd.getSentOffset().getOffset())); assertEquals(0L, pd.getUnconfirmed()); } @Test public void normalOperationShouldNotReconfigureKafkaConsumer() { final PartitionData pd = new PartitionData(COMP, null, createCursor(100L), System.currentTimeMillis()); for (long i = 0; i < 100; ++i) { pd.addEvent(new ConsumedEvent(("test_" + i).getBytes(), createCursor(100L + i + 1))); } // Now say to it that it was sent pd.takeEventsToStream(currentTimeMillis(), 1000, 0L); assertEquals(100L, pd.getUnconfirmed()); for (long i = 0; i < 10; ++i) { final PartitionData.CommitResult cr = pd.onCommitOffset(createCursor(110L + i * 10L)); assertEquals(10L, cr.committedCount); assertFalse(cr.seekOnKafka); assertEquals(90L - i * 10L, pd.getUnconfirmed()); } } @Test public void keepAliveCountShouldIncreaseOnEachEmptyCall() { final PartitionData pd = new PartitionData(COMP, null, createCursor(100L), System.currentTimeMillis()); for (int i = 0; i < 100; ++i) { pd.takeEventsToStream(currentTimeMillis(), 10, 0L); assertEquals(i + 1, pd.getKeepAliveInARow()); } pd.addEvent(new ConsumedEvent("".getBytes(), createCursor(101L))); assertEquals(100, pd.getKeepAliveInARow()); pd.takeEventsToStream(currentTimeMillis(), 10, 0L); assertEquals(0, pd.getKeepAliveInARow()); pd.takeEventsToStream(currentTimeMillis(), 10, 0L); assertEquals(1, pd.getKeepAliveInARow()); } @Test public void eventsShouldBeStreamedOnTimeout() { final long timeout = TimeUnit.SECONDS.toMillis(1); long currentTime = System.currentTimeMillis(); final PartitionData pd = new PartitionData(COMP, null, createCursor(100L), currentTime); for (int i = 0; i < 100; ++i) { pd.addEvent(new ConsumedEvent("test".getBytes(), createCursor(i + 100L + 1))); } List<ConsumedEvent> data = pd.takeEventsToStream(currentTime, 1000, timeout); assertNull(data); assertEquals(0, pd.getKeepAliveInARow()); currentTime += timeout + 1; data = pd.takeEventsToStream(currentTime, 1000, timeout); assertNotNull(data); assertEquals(100, data.size()); for (int i = 100; i < 200; ++i) { pd.addEvent(new ConsumedEvent("test".getBytes(), createCursor(i + 100L + 1))); } data = pd.takeEventsToStream(currentTime, 1000, timeout); assertNull(data); assertEquals(0, pd.getKeepAliveInARow()); currentTime += timeout + 1; data = pd.takeEventsToStream(currentTime, 1000, timeout); assertNotNull(data); assertEquals(100, data.size()); } @Test public void eventsShouldBeStreamedOnBatchSize() { final long timeout = TimeUnit.SECONDS.toMillis(1); final PartitionData pd = new PartitionData(COMP, null, createCursor(100L), System.currentTimeMillis()); for (int i = 0; i < 100; ++i) { pd.addEvent(new ConsumedEvent("test".getBytes(), createCursor(i + 100L + 1))); } assertNull(pd.takeEventsToStream(currentTimeMillis(), 1000, timeout)); final List<ConsumedEvent> eventsToStream = pd.takeEventsToStream(currentTimeMillis(), 99, timeout); assertNotNull(eventsToStream); assertEquals(99, eventsToStream.size()); } }
import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.event.*; import java.util.HashSet; public class dlgAddCategory extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTextField txtCategoryName; private JList lstCategoryValues; private JButton btnAdd; private JButton btnRemove; private JLabel lblCategoryName; private JTable tblCategoryValues; public dlgAddCategory() { setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); this.setTitle("Add experimental category"); initCategoryModel(); initEventListeners(); // TODO Disable the OK button until at least a title and value have been added. // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } // TODO Better name than not sure here. public enum DialogResult { NOTSURE, OK, CANCEL } public DialogResult Result = DialogResult.NOTSURE; public SampleCategory ProvidedCategory; private void initCategoryModel() { DefaultTableModel model = new DefaultTableModel(); model.addColumn("Value"); tblCategoryValues.setModel(model); } private void initEventListeners() { buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onCancel(); } }); btnAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Ideally the row would be highlighted and the user could start editing immediately after pressing "Add". ((DefaultTableModel)tblCategoryValues.getModel()).addRow(new Object[] {"TODO Value here"}); } }); // TODO Fix form scaling positioning. // TODO Disable the OK button until needed info is filled in. btnRemove.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int[] categoryValues = tblCategoryValues.getSelectedRows(); for (int categoryValue : categoryValues) { ((DefaultTableModel)tblCategoryValues.getModel()).removeRow(categoryValue); } } }); } private void onOK() { // TODO Just write a function for converting from the UI to an object as I'm doing here. HashSet<String> validValues = new HashSet<>(); for (int value = 0; value < tblCategoryValues.getRowCount(); value++) { validValues.add((String) tblCategoryValues.getValueAt(value, 0)); } ProvidedCategory = new SampleCategory(txtCategoryName.getText(), validValues); Result = DialogResult.OK; dispose(); } private void onCancel() { Result = DialogResult.CANCEL; dispose(); } public DialogResult Display() { pack(); // TODO Make an extension method or similar to center a form. // TODO This is not working. // Center the dialog on-screen. setLocationRelativeTo(null); setVisible(true); return Result; } }
package com.markupartist.sthlmtraveling; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.markupartist.sthlmtraveling.provider.TransportMode; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.BusDeparture; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.Departures; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.DisplayRow; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.GroupOfLine; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.MetroDeparture; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.TrainDeparture; import com.markupartist.sthlmtraveling.provider.departure.DeparturesStore.TramDeparture; import com.markupartist.sthlmtraveling.utils.DateTimeUtil; import com.markupartist.sthlmtraveling.utils.ViewHelper; import com.markupartist.sthlmtraveling.utils.text.TextDrawable; import java.util.List; public class DepartureAdapter extends SectionedAdapter { private Context mContext; public DepartureAdapter(Context context) { mContext = context; } @Override protected View getHeaderView(Section section, int index, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.row_section, parent, false); } ((TextView) convertView.findViewById(R.id.text1)).setText(section.caption); return convertView; } public void fillDepartures(Departures departures, int transportType) { //TextView emptyResultView = (TextView) findViewById(R.id.departures_empty_result); //emptyResultView.setVisibility(View.GONE); this.clear(); String directionString = mContext.getString(R.string.direction); switch (transportType) { case TransportMode.METRO_INDEX: if (departures.metros.isEmpty()) { //emptyResultView.setVisibility(View.VISIBLE); } else { for (MetroDeparture metroDeparture: departures.metros) { for (GroupOfLine gol : metroDeparture.groupOfLines) { if (gol.direction1.size() > 0) { this.addSection(0, directionString + " 1", createAdapter(gol.direction1, transportType)); } if (gol.direction2.size() > 0) { this.addSection(0, directionString + " 2", createAdapter(gol.direction2, transportType)); } } } } break; case TransportMode.BUS_INDEX: if (departures.buses.isEmpty()) { //emptyResultView.setVisibility(View.VISIBLE); } else { for (BusDeparture busDeparture : departures.buses) { this.addSection(0, busDeparture.stopAreaName, createAdapter(busDeparture.departures, transportType)); } } break; case TransportMode.TRAIN_INDEX: if (departures.trains.isEmpty()) { //emptyResultView.setVisibility(View.VISIBLE); } else { for (TrainDeparture trainDeparture : departures.trains) { if (trainDeparture.direction1.size() > 0) { this.addSection(0, trainDeparture.stopAreaName + ", " + directionString + " 1", createAdapter(trainDeparture.direction1, transportType)); } if (trainDeparture.direction2.size() > 0) { this.addSection(0, trainDeparture.stopAreaName + ", " + directionString + " 2", createAdapter(trainDeparture.direction2, transportType)); } } } break; case TransportMode.TRAM_INDEX: if (departures.trams.isEmpty()) { //emptyResultView.setVisibility(View.VISIBLE); } else { for (TramDeparture tramDeparture : departures.trams) { if (tramDeparture.direction1.size() > 0) { this.addSection(0, tramDeparture.stopAreaName + ", " + directionString + " 1", createAdapter(tramDeparture.direction1, transportType)); } if (tramDeparture.direction2.size() > 0) { this.addSection(0, tramDeparture.stopAreaName + ", " + directionString + " 2", createAdapter(tramDeparture.direction2, transportType)); } } } break; } this.notifyDataSetChanged(); } public static class DisplayRowAdapter extends ArrayAdapter<DisplayRow> { private final int mTransportType; public DisplayRowAdapter(Context context, List<DisplayRow> displayRows, int transportType) { super(context, R.layout.departures_row, displayRows); mTransportType = transportType; } @Override public View getView(int position, View convertView, ViewGroup parent) { DisplayRow displayRow = getItem(position); ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(getContext()) .inflate(R.layout.departures_row, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } TextDrawable d = TextDrawable.builder(getContext()) .buildRound(displayRow.lineNumber, ViewHelper.getLineColor( getContext().getResources(), mTransportType, displayRow.lineNumber)); holder.lineView.setImageDrawable(d); String destination = displayRow.destination; if (!TextUtils.isEmpty(displayRow.message) && TextUtils.isEmpty(destination)) { destination = displayRow.message; } holder.destinationView.setText(destination); String displayTime = displayRow.displayTime; holder.timeToDisplayView.setText( DateTimeUtil.formatDisplayTime(displayTime, getContext())); return convertView; } } private DisplayRowAdapter createAdapter(final List<DisplayRow> displayRows, int transportType) { return new DisplayRowAdapter(mContext, displayRows, transportType); } public static class ViewHolder { ImageView lineView; TextView destinationView; TextView timeToDisplayView; public ViewHolder(View view) { lineView = (ImageView) view.findViewById(R.id.departure_line); destinationView = (TextView) view.findViewById(R.id.departure_destination); timeToDisplayView = (TextView) view.findViewById(R.id.departure_timeToDisplay); } } }
package org.cytoscape.internal.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import javax.swing.InputMap; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.application.events.SetCurrentNetworkEvent; import org.cytoscape.application.events.SetCurrentNetworkListener; import org.cytoscape.application.events.SetSelectedNetworksEvent; import org.cytoscape.application.events.SetSelectedNetworksListener; import org.cytoscape.application.swing.CyAction; import org.cytoscape.internal.task.DynamicTaskFactoryProvisioner; import org.cytoscape.internal.task.TaskFactoryTunableAction; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.events.NetworkAboutToBeDestroyedEvent; import org.cytoscape.model.events.NetworkAboutToBeDestroyedListener; import org.cytoscape.model.events.NetworkAddedEvent; import org.cytoscape.model.events.NetworkAddedListener; import org.cytoscape.model.events.RowSetRecord; import org.cytoscape.model.events.RowsSetEvent; import org.cytoscape.model.events.RowsSetListener; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.model.subnetwork.CySubNetwork; import org.cytoscape.task.NetworkCollectionTaskFactory; import org.cytoscape.task.NetworkTaskFactory; import org.cytoscape.task.NetworkViewCollectionTaskFactory; import org.cytoscape.task.NetworkViewTaskFactory; import org.cytoscape.util.swing.JTreeTable; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.CyNetworkViewManager; import org.cytoscape.view.model.events.NetworkViewAboutToBeDestroyedEvent; import org.cytoscape.view.model.events.NetworkViewAboutToBeDestroyedListener; import org.cytoscape.view.model.events.NetworkViewAddedEvent; import org.cytoscape.view.model.events.NetworkViewAddedListener; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.swing.DialogTaskManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NetworkPanel extends JPanel implements TreeSelectionListener, SetCurrentNetworkListener, SetSelectedNetworksListener, NetworkAddedListener, NetworkViewAddedListener, NetworkAboutToBeDestroyedListener, NetworkViewAboutToBeDestroyedListener, RowsSetListener { private final static long serialVersionUID = 1213748836763243L; private static final Logger logger = LoggerFactory.getLogger(NetworkPanel.class); static final Color FONT_COLOR = new Color(20, 20, 20); private static final int TABLE_ROW_HEIGHT = 32; private static final Dimension PANEL_SIZE = new Dimension(400, 700); private final JTreeTable treeTable; private final NetworkTreeNode root; private JPanel navigatorPanel; private JSplitPane split; private final NetworkTreeTableModel treeTableModel; private final CyApplicationManager appManager; final CyNetworkManager netmgr; final CyNetworkViewManager networkViewManager; private final DialogTaskManager taskManager; private final DynamicTaskFactoryProvisioner factoryProvisioner; private final JPopupMenu popup; private final Map<TaskFactory, JMenuItem> popupMap; private final Map<TaskFactory, CyAction> popupActions; private final Map<CyTable, CyNetwork> nameTables; private final Map<CyTable, CyNetwork> nodeEdgeTables; private final Map<Long, NetworkTreeNode> treeNodeMap; private final Map<Object, TaskFactory> provisionerMap; private final Map<CyNetwork, NetworkTreeNode> network2nodeMap; private boolean ignoreTreeSelectionEvents; /** * * @param applicationManager * @param netmgr * @param networkViewManager * @param bird * @param taskManager */ public NetworkPanel(final CyApplicationManager applicationManager, final CyNetworkManager netmgr, final CyNetworkViewManager networkViewManager, final BirdsEyeViewHandler bird, final DialogTaskManager taskManager) { super(); this.treeNodeMap = new HashMap<Long, NetworkTreeNode>(); this.provisionerMap = new HashMap<Object, TaskFactory>(); this.appManager = applicationManager; this.netmgr = netmgr; this.networkViewManager = networkViewManager; this.taskManager = taskManager; this.factoryProvisioner = new DynamicTaskFactoryProvisioner(appManager); root = new NetworkTreeNode("Network Root", null); treeTableModel = new NetworkTreeTableModel(this, root); treeTable = new JTreeTable(treeTableModel); initialize(); // create and populate the popup window popup = new JPopupMenu(); popupMap = new WeakHashMap<TaskFactory, JMenuItem>(); popupActions = new WeakHashMap<TaskFactory, CyAction>(); nameTables = new WeakHashMap<CyTable, CyNetwork>(); nodeEdgeTables = new WeakHashMap<CyTable, CyNetwork>(); this.network2nodeMap = new WeakHashMap<CyNetwork, NetworkTreeNode>(); setNavigator(bird.getBirdsEyeView()); /* * Remove CTR-A for enabling select all function in the main window. */ for (KeyStroke listener : treeTable.getRegisteredKeyStrokes()) { if (listener.toString().equals("ctrl pressed A")) { final InputMap map = treeTable.getInputMap(); map.remove(listener); treeTable.setInputMap(WHEN_FOCUSED, map); treeTable.setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, map); } } } protected void initialize() { setLayout(new BorderLayout()); setPreferredSize(PANEL_SIZE); setSize(PANEL_SIZE); treeTable.getTree().addTreeSelectionListener(this); treeTable.getTree().setRootVisible(false); ToolTipManager.sharedInstance().registerComponent(treeTable); treeTable.getTree().setCellRenderer(new TreeCellRenderer(treeTable)); treeTable.setBackground(Color.white); treeTable.setSelectionBackground(new Color(200, 200, 200, 150)); treeTable.getColumn("Network").setPreferredWidth(250); treeTable.getColumn("Nodes").setPreferredWidth(45); treeTable.getColumn("Edges").setPreferredWidth(45); treeTable.setBackground(Color.WHITE); treeTable.setRowHeight(TABLE_ROW_HEIGHT); treeTable.setForeground(FONT_COLOR); treeTable.setSelectionForeground(FONT_COLOR); treeTable.setCellSelectionEnabled(false); treeTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); treeTable.getTree().setSelectionModel(new DefaultTreeSelectionModel()); navigatorPanel = new JPanel(); navigatorPanel.setLayout(new BorderLayout()); navigatorPanel.setPreferredSize(new Dimension(280, 280)); navigatorPanel.setSize(new Dimension(280, 280)); navigatorPanel.setBackground(Color.white); JScrollPane scroll = new JScrollPane(treeTable); split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scroll, navigatorPanel); split.setResizeWeight(1); split.setDividerLocation(400); add(split); // this mouse listener listens for the right-click event and will show // the pop-up window when that occurrs treeTable.addMouseListener(new PopupListener()); } private void addFactory(TaskFactory factory, CyAction action) { final JMenuItem item = new JMenuItem(action); popupMap.put(factory, item); popupActions.put(factory, action); popup.add(item); popup.addPopupMenuListener(action); } private void removeFactory(TaskFactory factory) { JMenuItem item = popupMap.remove(factory); if (item != null) popup.remove(item); CyAction action = popupActions.remove(factory); if (action != null) popup.removePopupMenuListener(action); } public void addTaskFactory(TaskFactory factory, @SuppressWarnings("rawtypes") Map props) { addFactory(factory, new TaskFactoryTunableAction(taskManager, factory, props, appManager, networkViewManager)); } public void removeTaskFactory(TaskFactory factory, @SuppressWarnings("rawtypes") Map props) { removeFactory(factory); } public void addNetworkCollectionTaskFactory(NetworkCollectionTaskFactory factory, Map props) { TaskFactory provisioner = factoryProvisioner.createFor(factory); provisionerMap.put(factory, provisioner); addFactory(provisioner, new TaskFactoryTunableAction(taskManager, provisioner, props, appManager, networkViewManager)); } public void removeNetworkCollectionTaskFactory(NetworkCollectionTaskFactory factory, Map props) { removeFactory(provisionerMap.remove(factory)); } public void addNetworkViewCollectionTaskFactory(NetworkViewCollectionTaskFactory factory, Map props) { TaskFactory provisioner = factoryProvisioner.createFor(factory); provisionerMap.put(factory, provisioner); addFactory(provisioner, new TaskFactoryTunableAction(taskManager, provisioner, props, appManager, networkViewManager)); } public void removeNetworkViewCollectionTaskFactory(NetworkViewCollectionTaskFactory factory, Map props) { removeFactory(provisionerMap.remove(factory)); } public void addNetworkTaskFactory(NetworkTaskFactory factory, @SuppressWarnings("rawtypes") Map props) { TaskFactory provisioner = factoryProvisioner.createFor(factory); provisionerMap.put(factory, provisioner); addFactory(provisioner, new TaskFactoryTunableAction(taskManager, provisioner, props, appManager, networkViewManager)); } public void removeNetworkTaskFactory(NetworkTaskFactory factory, @SuppressWarnings("rawtypes") Map props) { removeFactory(provisionerMap.remove(factory)); } public void addNetworkViewTaskFactory(final NetworkViewTaskFactory factory, @SuppressWarnings("rawtypes") Map props) { TaskFactory provisioner = factoryProvisioner.createFor(factory); provisionerMap.put(factory, provisioner); addFactory(provisioner, new TaskFactoryTunableAction(taskManager, provisioner, props, appManager, networkViewManager)); } public void removeNetworkViewTaskFactory(NetworkViewTaskFactory factory, @SuppressWarnings("rawtypes") Map props) { removeFactory(provisionerMap.remove(factory)); } public void setNavigator(final Component comp) { this.navigatorPanel.removeAll(); this.navigatorPanel.add(comp, BorderLayout.CENTER); } /** * This is used by Session writer. * * @return */ public JTreeTable getTreeTable() { return treeTable; } public JPanel getNavigatorPanel() { return navigatorPanel; } /** * Remove a network from the panel. * * @param networkId */ private void removeNetwork(final CyNetwork network) { final NetworkTreeNode node = this.network2nodeMap.get(network); if (node == null) return; final Enumeration<?> children = node.children(); if (children.hasMoreElements()) { final List<NetworkTreeNode> removedChildren = new ArrayList<NetworkTreeNode>(); while (children.hasMoreElements()) removedChildren.add((NetworkTreeNode) children.nextElement()); for (NetworkTreeNode child : removedChildren) { child.removeFromParent(); root.add(child); } } final NetworkTreeNode parentNode = (NetworkTreeNode) node.getParent(); node.removeFromParent(); if (parentNode.isLeaf()) { // Remove from root node parentNode.removeFromParent(); } treeTable.getTree().updateUI(); treeTable.repaint(); } // // Event handlers ///// @Override public void handleEvent(final NetworkAboutToBeDestroyedEvent nde) { SwingUtilities.invokeLater(new Runnable() { public void run() { final CyNetwork net = nde.getNetwork(); logger.debug("Network about to be destroyed " + net.getSUID()); ignoreTreeSelectionEvents = true; removeNetwork(net); ignoreTreeSelectionEvents = false; nameTables.remove(net.getDefaultNetworkTable()); nodeEdgeTables.remove(net.getDefaultNodeTable()); nodeEdgeTables.remove(net.getDefaultEdgeTable()); } }); } @Override public void handleEvent(final NetworkAddedEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { final CyNetwork net = e.getNetwork(); logger.debug("Got NetworkAddedEvent. Model ID = " + net.getSUID()); ignoreTreeSelectionEvents = true; addNetwork(net); ignoreTreeSelectionEvents = false; nameTables.put(net.getDefaultNetworkTable(), net); nodeEdgeTables.put(net.getDefaultNodeTable(), net); nodeEdgeTables.put(net.getDefaultEdgeTable(), net); } }); } @Override public void handleEvent(final RowsSetEvent e) { final Collection<RowSetRecord> payload = e.getPayloadCollection(); if (payload.size() == 0) return; final RowSetRecord record = e.getPayloadCollection().iterator().next(); if (record == null) return; final CyTable table = e.getSource(); final CyNetwork updateNetworkName = nameTables.get(table); // Case 1: Network name/title updated if (updateNetworkName != null && record.getColumn().equals(CyNetwork.NAME)) { final CyRow row = payload.iterator().next().getRow(); final String newTitle = row.get(CyNetwork.NAME, String.class); final NetworkTreeNode node = this.network2nodeMap.get(updateNetworkName); final String oldTitle = treeTableModel.getValueAt(node, 0).toString(); if (newTitle.equals(oldTitle) == false) { SwingUtilities.invokeLater(new Runnable() { public void run() { treeTableModel.setValueAt(newTitle, node, 0); treeTable.repaint(); } }); } return; } final CyNetwork updateSelected = nodeEdgeTables.get(table); // Case 2: Selection updated. if (updateSelected != null && record.getColumn().equals(CyNetwork.SELECTED)) { SwingUtilities.invokeLater(new Runnable() { public void run() { treeTable.repaint(); } }); } } @Override public void handleEvent(final SetCurrentNetworkEvent e) { final CyNetwork cnet = e.getNetwork(); if (cnet == null) { logger.debug("Got null for current network."); return; } final NetworkTreeNode node = (NetworkTreeNode) treeTable.getTree().getLastSelectedPathComponent(); final CyNetwork selectedNet = node != null ? node.getNetwork() : null; if (!cnet.equals(selectedNet)) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateNetworkTreeSelection(true); } }); } } @Override public void handleEvent(final SetSelectedNetworksEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateNetworkTreeSelection(false); } }); } @Override public void handleEvent(final NetworkViewAboutToBeDestroyedEvent nde) { SwingUtilities.invokeLater(new Runnable() { public void run() { final CyNetworkView netView = nde.getNetworkView(); logger.debug("Network view about to be destroyed " + netView.getModel().getSUID()); treeNodeMap.get(netView.getModel().getSUID()).setNodeColor(Color.red); treeTable.repaint(); } }); } @Override public void handleEvent(final NetworkViewAddedEvent nde) { SwingUtilities.invokeLater(new Runnable() { public void run() { final CyNetworkView netView = nde.getNetworkView(); logger.debug("Network view added to NetworkPanel: " + netView.getModel().getSUID()); treeNodeMap.get(netView.getModel().getSUID()).setNodeColor(Color.black); treeTable.repaint(); } }); } private void addNetwork(final CyNetwork network) { // first see if it is not in the tree already if (this.network2nodeMap.get(network) == null) { NetworkTreeNode parentTreeNode = null; CyRootNetwork parentNetwork = null; // In current version, ALL networks are created as Subnetworks. // So, this should be always true. if (network instanceof CySubNetwork) { parentNetwork = ((CySubNetwork) network).getRootNetwork(); parentTreeNode = this.treeNodeMap.get(parentNetwork.getSUID()); } if (parentTreeNode == null) parentTreeNode = new NetworkTreeNode("", null); // Actual tree node for this network String netName = network.getRow(network).get(CyNetwork.NAME, String.class); if (netName == null) { logger.error("Network name is null--SUID=" + network.getSUID()); netName = "? (SUID: " + network.getSUID() + ")"; } final NetworkTreeNode dmtn = new NetworkTreeNode(netName, network); network2nodeMap.put(network, dmtn); parentTreeNode.add(dmtn); if (treeNodeMap.values().contains(parentTreeNode) == false) root.add(parentTreeNode); // Register top-level node to map if (parentNetwork != null) this.treeNodeMap.put(parentNetwork.getSUID(), parentTreeNode); if (networkViewManager.viewExists(network)) dmtn.setNodeColor(Color.black); this.treeNodeMap.put(network.getSUID(), dmtn); // apparently this doesn't fire valueChanged treeTable.getTree().collapsePath(new TreePath(new TreeNode[] { root })); treeTable.getTree().updateUI(); final TreePath path = new TreePath(dmtn.getPath()); treeTable.getTree().expandPath(path); treeTable.getTree().scrollPathToVisible(path); treeTable.doLayout(); } } /** * Update selected row. */ private final void updateNetworkTreeSelection(final boolean singleSet) { final List<CyNetwork> selectedNetworks = appManager.getSelectedNetworks(); // Phase 1: Add selected path from GUI status final List<TreePath> paths = new ArrayList<TreePath>(); // Phase 2: add selected networks from app manager for (final CyNetwork network : selectedNetworks) { final NetworkTreeNode node = this.network2nodeMap.get(network); if (node != null) { final TreePath tp = new TreePath(node.getPath()); paths.add(tp); } } ignoreTreeSelectionEvents = true; treeTable.getTree().getSelectionModel().setSelectionPaths(paths.toArray(new TreePath[paths.size()])); ignoreTreeSelectionEvents = false; int maxRow = 0; for (final TreePath tp : paths) { final int row = treeTable.getTree().getRowForPath(tp); maxRow = Math.max(maxRow, row); } treeTable.getTree().scrollRowToVisible(maxRow); treeTable.repaint(); } /** * This method highlights a network in the NetworkPanel. */ @Override public void valueChanged(final TreeSelectionEvent e) { if (ignoreTreeSelectionEvents) return; final JTree tree = treeTable.getTree(); // Sets the "current" network based on last node in the tree selected final NetworkTreeNode node = (NetworkTreeNode) tree.getLastSelectedPathComponent(); if (node == null || node.getUserObject() == null) return; final CyNetwork net = node.getNetwork(); // This is a "network set" node. if (net == null) { // When selecting root node all of the subnetworks // are selected. CyRootNetwork root = ((CySubNetwork) ((NetworkTreeNode) node.getFirstChild()).getNetwork()) .getRootNetwork(); List<CySubNetwork> subNetworkList = root.getSubNetworkList(); List<CyNetwork> networkList = new LinkedList<CyNetwork>(); for (CySubNetwork sn : subNetworkList) networkList.add(sn); if (networkList.size() > 0) { appManager.setCurrentNetwork(((NetworkTreeNode) node.getFirstChild()).getNetwork()); appManager.setSelectedNetworks(networkList); final List<CyNetworkView> selectedViews = new ArrayList<CyNetworkView>(); for (final CyNetwork network : networkList) { final Collection<CyNetworkView> views = networkViewManager.getNetworkViews(network); if (views.size() != 0) selectedViews.addAll(views); } appManager.setSelectedNetworkViews(selectedViews); } return; } // No need to set the same network again. It should prevent infinite // loops. // Also check if the network still exists (it could have been removed by // another thread). if (netmgr.networkExists(net.getSUID()) && !net.equals(appManager.getCurrentNetwork())) appManager.setCurrentNetwork(net); // creates a list of all selected networks List<CyNetwork> networkList = new LinkedList<CyNetwork>(); try { for (int i = tree.getMinSelectionRow(); i <= tree.getMaxSelectionRow(); i++) { NetworkTreeNode n = (NetworkTreeNode) tree.getPathForRow(i).getLastPathComponent(); if (n != null && n.getUserObject() != null && tree.isRowSelected(i)) networkList.add(n.getNetwork()); } } catch (Exception ex) { ex.printStackTrace(); } if (networkList.size() > 0) { appManager.setSelectedNetworks(networkList); final List<CyNetworkView> selectedViews = new ArrayList<CyNetworkView>(); for (final CyNetwork network : networkList) { final Collection<CyNetworkView> views = networkViewManager.getNetworkViews(network); if (views.size() != 0) selectedViews.addAll(views); } appManager.setSelectedNetworkViews(selectedViews); } } /** * This class listens to mouse events from the TreeTable, if the mouse event * is one that is canonically associated with a popup menu (ie, a right * click) it will pop up the menu with option for destroying view, creating * view, and destroying network (this is platform specific apparently) */ private final class PopupListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } /** * if the mouse press is of the correct type, this function will maybe * display the popup */ private final void maybeShowPopup(final MouseEvent e) { // Ignore if not valid trigger. if (!e.isPopupTrigger()) return; // get the row where the mouse-click originated final int row = treeTable.rowAtPoint(e.getPoint()); if (row == -1) return; final JTree tree = treeTable.getTree(); final TreePath treePath = tree.getPathForRow(row); Long networkID = -1L; try { networkID = ((NetworkTreeNode) treePath.getLastPathComponent()).getNetwork().getSUID(); } catch (NullPointerException nullExp) { // The tree root does not represent a network, ignore it. return; } final CyNetwork cyNetwork = netmgr.getNetwork(networkID); if (cyNetwork != null) { // enable/disable any actions based on state of system for (CyAction action : popupActions.values()) action.updateEnableState(); // then popup menu popup.show(e.getComponent(), e.getX(), e.getY()); } } } }
package railo.runtime.tag; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import railo.commons.lang.StringUtil; import railo.commons.sql.SQLUtil; import railo.runtime.PageContext; import railo.runtime.config.Constants; import railo.runtime.db.DataSource; import railo.runtime.db.DataSourceManager; import railo.runtime.db.DatasourceConnection; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.DatabaseException; import railo.runtime.exp.PageException; import railo.runtime.ext.tag.TagImpl; import railo.runtime.listener.ApplicationContextPro; import railo.runtime.op.Caster; import railo.runtime.timer.Stopwatch; import railo.runtime.type.Array; import railo.runtime.type.ArrayImpl; import railo.runtime.type.Collection; import railo.runtime.type.Collection.Key; import railo.runtime.type.KeyImpl; import railo.runtime.type.Query; import railo.runtime.type.QueryColumn; import railo.runtime.type.QueryImpl; import railo.runtime.type.SVArray; import railo.runtime.type.Struct; import railo.runtime.type.StructImpl; import railo.runtime.type.util.KeyConstants; /** * Handles all interactions with files. The attributes you use with cffile depend on the value of the action attribute. * For example, if the action = "write", use the attributes associated with writing a text file. * * * **/ public final class DBInfo extends TagImpl { private static final Key TABLE_NAME = KeyImpl.intern("TABLE_NAME"); private static final Key COLUMN_NAME = KeyImpl.intern("COLUMN_NAME"); private static final Key IS_PRIMARYKEY = KeyImpl.intern("IS_PRIMARYKEY"); private static final Key IS_FOREIGNKEY = KeyImpl.intern("IS_FOREIGNKEY"); private static final Key COLUMN_DEF = KeyImpl.intern("COLUMN_DEF"); private static final Key COLUMN_DEFAULT_VALUE = KeyImpl.intern("COLUMN_DEFAULT_VALUE"); private static final Key COLUMN_DEFAULT = KeyImpl.intern("COLUMN_DEFAULT"); private static final Key REFERENCED_PRIMARYKEY = KeyImpl.intern("REFERENCED_PRIMARYKEY"); private static final Key REFERENCED_PRIMARYKEY_TABLE = KeyImpl.intern("REFERENCED_PRIMARYKEY_TABLE"); private static final Key USER = KeyImpl.intern("USER"); private static final Key TABLE_SCHEM = KeyImpl.intern("TABLE_SCHEM"); private static final Key DECIMAL_DIGITS = KeyImpl.intern("DECIMAL_DIGITS"); private static final Key DATABASE_NAME = KeyImpl.intern("database_name"); private static final Key TABLE_CAT = KeyImpl.intern("TABLE_CAT"); private static final Key PROCEDURE = KeyImpl.intern("procedure"); private static final Key CATALOG = KeyImpl.intern("catalog"); private static final Key SCHEMA = KeyImpl.intern("schema"); private static final Key DATABASE_PRODUCTNAME = KeyImpl.intern("DATABASE_PRODUCTNAME"); private static final Key DATABASE_VERSION = KeyImpl.intern("DATABASE_VERSION"); private static final Key DRIVER_NAME = KeyImpl.intern("DRIVER_NAME"); private static final Key DRIVER_VERSION = KeyImpl.intern("DRIVER_VERSION"); private static final Key JDBC_MAJOR_VERSION = KeyImpl.intern("JDBC_MAJOR_VERSION"); private static final Key JDBC_MINOR_VERSION = KeyImpl.intern("JDBC_MINOR_VERSION"); private static final int TYPE_NONE=0; private static final int TYPE_DBNAMES=1; private static final int TYPE_TABLES=2; private static final int TYPE_TABLE_COLUMNS = 3; private static final int TYPE_VERSION = 4; private static final int TYPE_PROCEDURES = 5; private static final int TYPE_PROCEDURE_COLUMNS = 6; private static final int TYPE_FOREIGNKEYS = 7; private static final int TYPE_INDEX = 8; private static final int TYPE_USERS = 9; private static final int TYPE_TERMS = 10; private static final Collection.Key CARDINALITY = KeyImpl.init("CARDINALITY"); //private static final String[] ALL_TABLE_TYPES = {"TABLE", "VIEW", "SYSTEM TABLE", "SYNONYM"}; private String datasource; private String name; private int type; private String dbname; private String password; private String pattern; private String table; private String procedure; private String username; private String strType; @Override public void release() { super.release(); datasource=null; name=null; type=TYPE_NONE; dbname=null; password=null; pattern=null; table=null; procedure=null; username=null; } /** * @param procedure the procedure to set */ public void setProcedure(String procedure) { this.procedure = procedure; } /** * @param datasource the datasource to set */ public void setDatasource(String datasource) { this.datasource = datasource; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @param type the type to set * @throws ApplicationException */ public void setType(String strType) throws ApplicationException { this.strType=strType; strType=strType.toLowerCase().trim(); if("dbnames".equals(strType)) this.type=TYPE_DBNAMES; else if("dbname".equals(strType)) this.type=TYPE_DBNAMES; else if("tables".equals(strType)) this.type=TYPE_TABLES; else if("table".equals(strType)) this.type=TYPE_TABLES; else if("columns".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("column".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("version".equals(strType)) this.type=TYPE_VERSION; else if("procedures".equals(strType)) this.type=TYPE_PROCEDURES; else if("procedure".equals(strType)) this.type=TYPE_PROCEDURES; else if("table_columns".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("table_column".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("column_table".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("column_tables".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("tablecolumns".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("tablecolumn".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("columntable".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("columntables".equals(strType)) this.type=TYPE_TABLE_COLUMNS; else if("procedure_columns".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("procedure_column".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("column_procedure".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("column_procedures".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("procedurecolumns".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("procedurecolumn".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("columnprocedure".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("columnprocedures".equals(strType)) this.type=TYPE_PROCEDURE_COLUMNS; else if("foreignkeys".equals(strType)) this.type=TYPE_FOREIGNKEYS; else if("foreignkey".equals(strType)) this.type=TYPE_FOREIGNKEYS; else if("index".equals(strType)) this.type=TYPE_INDEX; else if("users".equals(strType)) this.type=TYPE_USERS; else if("user".equals(strType)) this.type=TYPE_USERS; else if("term".equals(strType)) this.type=TYPE_TERMS; else if("terms".equals(strType)) this.type=TYPE_TERMS; else throw new ApplicationException("invalid value for attribute type ["+strType+"]", "valid values are [dbname,tables,columns,version,procedures,foreignkeys,index,users]"); } /** * @param dbname the dbname to set */ public void setDbname(String dbname) { this.dbname = dbname; } public void setDbnames(String dbname) { this.dbname = dbname; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @param pattern the pattern to set */ public void setPattern(String pattern) { this.pattern = pattern; } /** * @param table the table to set */ public void setTable(String table) { this.table = table; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } @Override public int doStartTag() throws PageException { Object ds=getDatasource(pageContext, datasource); DataSourceManager manager = pageContext.getDataSourceManager(); DatasourceConnection dc=ds instanceof DataSource? manager.getConnection(pageContext,(DataSource)ds,username,password): manager.getConnection(pageContext,Caster.toString(ds),username,password); try { if(type==TYPE_TABLE_COLUMNS) typeColumns(dc.getConnection().getMetaData()); else if(type==TYPE_DBNAMES) typeDBNames(dc.getConnection().getMetaData()); else if(type==TYPE_FOREIGNKEYS) typeForeignKeys(dc.getConnection().getMetaData()); else if(type==TYPE_INDEX) typeIndex(dc.getConnection().getMetaData()); else if(type==TYPE_PROCEDURES) typeProcedures(dc.getConnection().getMetaData()); else if(type==TYPE_PROCEDURE_COLUMNS)typeProcedureColumns(dc.getConnection().getMetaData()); else if(type==TYPE_TERMS) typeTerms(dc.getConnection().getMetaData()); else if(type==TYPE_TABLES) typeTables(dc.getConnection().getMetaData()); else if(type==TYPE_VERSION) typeVersion(dc.getConnection().getMetaData()); else if(type==TYPE_USERS) typeUsers(dc.getConnection().getMetaData()); } catch(SQLException sqle) { throw new DatabaseException(sqle,dc); } finally { manager.releaseConnection(pageContext,dc); } return SKIP_BODY; } private void typeColumns(DatabaseMetaData metaData) throws PageException, SQLException { required("table",table); Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); table=setCase(metaData, table); pattern=setCase(metaData, pattern); if(StringUtil.isEmpty(pattern,true)) pattern=null; String schema=null; int index=table.indexOf('.'); if(index>0) { schema=table.substring(0,index); table=table.substring(index+1); } checkTable(metaData); ResultSet columns = metaData.getColumns(dbname, schema, table, pattern); Query qry = new QueryImpl(columns,"query",pageContext.getTimeZone()); columns.close(); int len=qry.getRecordcount(); if(qry.getColumn(COLUMN_DEF,null) != null) qry.rename(COLUMN_DEF,COLUMN_DEFAULT_VALUE); else if(qry.getColumn(COLUMN_DEFAULT,null) != null) qry.rename(COLUMN_DEFAULT,COLUMN_DEFAULT_VALUE); // make sure decimal digits exists QueryColumn col = qry.getColumn(DECIMAL_DIGITS,null); if(col==null){ Array arr=new ArrayImpl(); for(int i=1;i<=len;i++) { arr.append(railo.runtime.op.Constants.DOUBLE_ZERO); } qry.addColumn(DECIMAL_DIGITS, arr); } // add is primary Map primaries = new HashMap(); String tblName; Array isPrimary=new ArrayImpl(); Set set; Object o; for(int i=1;i<=len;i++) { // decimal digits o=qry.getAt(DECIMAL_DIGITS, i,null); if(o==null)qry.setAtEL(DECIMAL_DIGITS, i,railo.runtime.op.Constants.DOUBLE_ZERO); set=(Set) primaries.get(tblName=(String) qry.getAt(TABLE_NAME, i)); if(set==null) { ResultSet pks = metaData.getPrimaryKeys(dbname, null, tblName); set=toSet(pks,"COLUMN_NAME"); pks.close(); primaries.put(tblName,set); } isPrimary.append(set.contains(qry.getAt(COLUMN_NAME, i))?"YES":"NO"); } qry.addColumn(IS_PRIMARYKEY, isPrimary); // add is foreignkey Map foreigns = new HashMap(); Array isForeign=new ArrayImpl(); Array refPrim=new ArrayImpl(); Array refPrimTbl=new ArrayImpl(); //Map map,inner; Map<String, Map<String, SVArray>> map; Map<String, SVArray> inner; for(int i=1;i<=len;i++) { map=(Map) foreigns.get(tblName=(String) qry.getAt(TABLE_NAME, i)); if(map==null) { ResultSet keys = metaData.getImportedKeys(dbname, schema, table); map=toMap(keys,"FKCOLUMN_NAME",new String[]{"PKCOLUMN_NAME","PKTABLE_NAME"}); keys.close(); foreigns.put(tblName, map); } inner = map.get(qry.getAt(COLUMN_NAME, i)); if(inner!=null) { isForeign.append("YES"); refPrim.append(inner.get("PKCOLUMN_NAME")); refPrimTbl.append(inner.get("PKTABLE_NAME")); } else { isForeign.append("NO"); refPrim.append("N/A"); refPrimTbl.append("N/A"); } } qry.addColumn(IS_FOREIGNKEY, isForeign); qry.addColumn(REFERENCED_PRIMARYKEY, refPrim); qry.addColumn(REFERENCED_PRIMARYKEY_TABLE, refPrimTbl); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private Map<String,Map<String, SVArray>> toMap(ResultSet result,String columnName,String[] additional) throws SQLException { Map<String,Map<String, SVArray>> map=new HashMap<String,Map<String, SVArray>>(); Map<String, SVArray> inner; String col; SVArray item; while(result.next()){ col=result.getString(columnName); inner=map.get(col); if(inner!=null) { for(int i=0;i<additional.length;i++) { item=inner.get(additional[i]); item.add(result.getString(additional[i])); item.setPosition(item.size()); } } else { inner=new HashMap<String, SVArray>(); map.put(col, inner); for(int i=0;i<additional.length;i++) { item=new SVArray(); item.add(result.getString(additional[i])); inner.put(additional[i], item); } } } return map; } private Set<String> toSet(ResultSet result,String columnName) throws SQLException { Set<String> set = new HashSet<String>(); while(result.next()){ set.add(result.getString(columnName)); } return set; } private void typeDBNames(DatabaseMetaData metaData) throws PageException, SQLException { Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); railo.runtime.type.Query catalogs = new QueryImpl(metaData.getCatalogs(),"query",pageContext.getTimeZone()); railo.runtime.type.Query scheme = new QueryImpl(metaData.getSchemas(),"query",pageContext.getTimeZone()); Pattern p=null; if(pattern!=null && !"%".equals(pattern)) p=SQLUtil.pattern(pattern, true); String[] columns=new String[]{"database_name","type"}; String[] types=new String[]{"VARCHAR","VARCHAR"}; railo.runtime.type.Query qry=new QueryImpl(columns,types,0,"query"); int row=1,len=catalogs.getRecordcount(); String value; // catalog for(int i=1;i<=len;i++) { value=(String) catalogs.getAt(TABLE_CAT, i); if(!matchPattern(value,p)) continue; qry.addRow(); qry.setAt(DATABASE_NAME, row, value); qry.setAt(KeyConstants._type, row, "CATALOG"); row++; } // scheme len=scheme.getRecordcount(); for(int i=1;i<=len;i++) { value=(String) scheme.getAt(TABLE_SCHEM, i); if(!matchPattern(value,p)) continue; qry.addRow(); qry.setAt(DATABASE_NAME, row, value); qry.setAt(KeyConstants._type, row, "SCHEMA"); row++; } qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void typeForeignKeys(DatabaseMetaData metaData) throws PageException, SQLException { required("table",table); Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); table=setCase(metaData, table); int index=table.indexOf('.'); String schema=null; if(index>0) { schema=table.substring(0,index); table=table.substring(index+1); } checkTable(metaData); ResultSet columns = metaData.getExportedKeys(dbname, schema, table); railo.runtime.type.Query qry = new QueryImpl(columns,"query",pageContext.getTimeZone()); columns.close(); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void checkTable(DatabaseMetaData metaData) throws SQLException, ApplicationException { ResultSet tables =null; try { tables = metaData.getTables(null, null, setCase(metaData,table), null); if(!tables.next()) throw new ApplicationException("there is no table that match the following pattern ["+table+"]"); } finally { if(tables!=null) tables.close(); } } private String setCase(DatabaseMetaData metaData, String id) throws SQLException { if(id==null) return null; if(metaData.storesLowerCaseIdentifiers()) return id.toLowerCase(); if(metaData.storesUpperCaseIdentifiers()) return id.toUpperCase(); return id; } private void typeIndex(DatabaseMetaData metaData) throws PageException, SQLException { required("table",table); Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); table=setCase(metaData, table); int index=table.indexOf('.'); String schema=null; if(index>0) { schema=table.substring(0,index); table=table.substring(index+1); } checkTable(metaData); ResultSet tables = metaData.getIndexInfo(dbname, schema, table, false, true); railo.runtime.type.Query qry = new QueryImpl(tables,"query",pageContext.getTimeZone()); // type int 2 string int rows = qry.getRecordcount(); String strType; int type,card; for(int row=1;row<=rows;row++){ // type switch(type=Caster.toIntValue(qry.getAt(KeyConstants._type,row))){ case 0: strType="Table Statistic"; break; case 1: strType="Clustered Index"; break; case 2: strType="Hashed Index"; break; case 3: strType="Other Index"; break; default: strType=Caster.toString(type); } qry.setAt(KeyConstants._type, row, strType); // CARDINALITY card=Caster.toIntValue(qry.getAt(CARDINALITY,row),0); qry.setAt(CARDINALITY, row, Caster.toDouble(card)); } qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void typeProcedures(DatabaseMetaData metaData) throws SQLException, PageException { Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); String schema=null; pattern=setCase(metaData, pattern); if(StringUtil.isEmpty(pattern,true)) { pattern=null; } ResultSet tables = metaData.getProcedures(dbname, schema, pattern); railo.runtime.type.Query qry = new QueryImpl(tables,"query",pageContext.getTimeZone()); tables.close(); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void typeProcedureColumns(DatabaseMetaData metaData) throws SQLException, PageException { required("procedure",procedure); Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); procedure=setCase(metaData, procedure); pattern=setCase(metaData, pattern); if(StringUtil.isEmpty(pattern,true)) pattern=null; String schema=null; int index=procedure.indexOf('.'); if(index>0) { schema=procedure.substring(0,index); procedure=procedure.substring(index+1); } ResultSet tables = metaData.getProcedureColumns(dbname, schema, procedure, pattern); railo.runtime.type.Query qry = new QueryImpl(tables,"query",pageContext.getTimeZone()); tables.close(); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void typeTerms(DatabaseMetaData metaData) throws SQLException, PageException { Struct sct=new StructImpl(); sct.setEL(PROCEDURE, metaData.getProcedureTerm()); sct.setEL(CATALOG, metaData.getCatalogTerm()); sct.setEL(SCHEMA, metaData.getSchemaTerm()); pageContext.setVariable(name, sct); } private void typeTables(DatabaseMetaData metaData) throws PageException, SQLException { Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); pattern=setCase(metaData, pattern); ResultSet tables = metaData.getTables(dbname, null, pattern, null); railo.runtime.type.Query qry = new QueryImpl(tables,"query",pageContext.getTimeZone()); tables.close(); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void typeVersion(DatabaseMetaData metaData) throws PageException, SQLException { Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); Key[] columns=new Key[]{DATABASE_PRODUCTNAME,DATABASE_VERSION,DRIVER_NAME,DRIVER_VERSION,JDBC_MAJOR_VERSION,JDBC_MINOR_VERSION}; String[] types=new String[]{"VARCHAR","VARCHAR","VARCHAR","VARCHAR","DOUBLE","DOUBLE"}; railo.runtime.type.Query qry=new QueryImpl(columns,types,1,"query"); qry.setAt(DATABASE_PRODUCTNAME,1,metaData.getDatabaseProductName()); qry.setAt(DATABASE_VERSION,1,metaData.getDatabaseProductVersion()); qry.setAt(DRIVER_NAME,1,metaData.getDriverName()); qry.setAt(DRIVER_VERSION,1,metaData.getDriverVersion()); qry.setAt(JDBC_MAJOR_VERSION,1,new Double(metaData.getJDBCMajorVersion())); qry.setAt(JDBC_MINOR_VERSION,1,new Double(metaData.getJDBCMinorVersion())); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void typeUsers(DatabaseMetaData metaData) throws PageException, SQLException { Stopwatch stopwatch=new Stopwatch(Stopwatch.UNIT_NANO); stopwatch.start(); checkTable(metaData); ResultSet result = metaData.getSchemas(); Query qry = new QueryImpl(result,"query",pageContext.getTimeZone()); qry.rename(TABLE_SCHEM,USER); qry.setExecutionTime(stopwatch.time()); pageContext.setVariable(name, qry); } private void required(String name, String value) throws ApplicationException { if(value==null) throw new ApplicationException("Missing attribute ["+name+"]. The type ["+strType+"] requires the attribute [" + name + "]."); } private static boolean matchPattern(String value, Pattern pattern) { if(pattern==null) return true; return SQLUtil.match(pattern, value); } @Override public int doEndTag() { return EVAL_PAGE; } public static Object getDatasource(PageContext pageContext, String datasource) throws ApplicationException { if(StringUtil.isEmpty(datasource)){ Object ds=((ApplicationContextPro)pageContext.getApplicationContext()).getDefDataSource(); if(StringUtil.isEmpty(ds)) throw new ApplicationException( "attribute [datasource] is required, when 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\";)"); return ds; } return datasource; } }
package org.jboss.as.web.deployment; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.PrivateSubDeploymentMarker; import org.jboss.as.server.deployment.module.ModuleRootMarker; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.as.server.deployment.module.MountHandle; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.server.deployment.module.TempFileProviderService; import org.jboss.logging.Logger; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.vfs.VFS; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import org.jboss.vfs.VisitorAttributes; import org.jboss.vfs.util.SuffixMatchFilter; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Create and mount classpath entries in the .war deployment. * * @author Emanuel Muckenhuber */ public class WarStructureDeploymentProcessor implements DeploymentUnitProcessor { private static final Logger logger = Logger.getLogger(WarStructureDeploymentProcessor.class); public static final String WEB_INF_LIB = "WEB-INF/lib"; public static final String WEB_INF_CLASSES = "WEB-INF/classes"; private static final ResourceRoot[] NO_ROOTS = new ResourceRoot[0]; public static final VirtualFileFilter DEFAULT_WEB_INF_LIB_FILTER = new SuffixMatchFilter(".jar", VisitorAttributes.DEFAULT); private final WebMetaData sharedWebMetaData; private final List<TldMetaData> sharedTldsMetaData; public WarStructureDeploymentProcessor(final WebMetaData sharedWebMetaData, final List<TldMetaData> sharedTldsMetaData) { this.sharedWebMetaData = sharedWebMetaData; this.sharedTldsMetaData = sharedTldsMetaData; } /** * {@inheritDoc} */ public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } final ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); final VirtualFile deploymentRoot = deploymentResourceRoot.getRoot(); if (deploymentRoot == null) { return; } // set the child first behavoiur final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); if (moduleSpecification == null) { return; } moduleSpecification.setPrivateModule(true); // other sub deployments should not have access to classes in the war module PrivateSubDeploymentMarker.mark(deploymentUnit); // we do not want to index the resource root, only WEB-INF/classes and WEB-INF/lib deploymentResourceRoot.putAttachment(Attachments.INDEX_RESOURCE_ROOT, false); // Make sure the root does not end up in the module ModuleRootMarker.mark(deploymentResourceRoot, false); // TODO: This needs to be ported to add additional resource roots the standard way final MountHandle mountHandle = deploymentResourceRoot.getMountHandle(); try { // add standard resource roots, this should eventually replace ClassPathEntry final List<ResourceRoot> resourceRoots = createResourceRoots(deploymentRoot, mountHandle); for (ResourceRoot root : resourceRoots) { deploymentUnit.addToAttachmentList(Attachments.RESOURCE_ROOTS, root); } } catch (Exception e) { throw new DeploymentUnitProcessingException(e); } // Add the war metadata final WarMetaData warMetaData = new WarMetaData(); warMetaData.setSharedWebMetaData(sharedWebMetaData); deploymentUnit.putAttachment(WarMetaData.ATTACHMENT_KEY, warMetaData); // Add the shared TLDs metadata final TldsMetaData tldsMetaData = new TldsMetaData(); tldsMetaData.setSharedTlds(sharedTldsMetaData); deploymentUnit.putAttachment(TldsMetaData.ATTACHMENT_KEY, tldsMetaData); } public void undeploy(final DeploymentUnit context) { } /** * Create the resource roots for a .war deployment * * @param deploymentRoot the deployment root * @param mountHandle the root mount handle * @return the resource roots * @throws IOException for any error */ private List<ResourceRoot> createResourceRoots(final VirtualFile deploymentRoot, MountHandle mountHandle) throws IOException, DeploymentUnitProcessingException { final List<ResourceRoot> entries = new ArrayList<ResourceRoot>(); // WEB-INF classes final ResourceRoot webInfClassesRoot = new ResourceRoot(deploymentRoot.getChild(WEB_INF_CLASSES).getName(), deploymentRoot .getChild(WEB_INF_CLASSES), null); ModuleRootMarker.mark(webInfClassesRoot); entries.add(webInfClassesRoot); // WEB-INF lib createWebInfLibResources(deploymentRoot, entries); return entries; } /** * Create the ResourceRoots for .jars in the WEB-INF/lib folder. * * @param deploymentRoot the deployment root * @throws IOException for any error */ void createWebInfLibResources(final VirtualFile deploymentRoot, List<ResourceRoot> entries) throws IOException, DeploymentUnitProcessingException { final VirtualFile webinfLib = deploymentRoot.getChild(WEB_INF_LIB); if (webinfLib.exists()) { final List<VirtualFile> archives = webinfLib.getChildren(DEFAULT_WEB_INF_LIB_FILTER); for (final VirtualFile archive : archives) { try { final Closeable closable = VFS.mountZip(archive, archive, TempFileProviderService.provider()); final ResourceRoot webInfArchiveRoot = new ResourceRoot(archive.getName(), archive, new MountHandle(closable)); ModuleRootMarker.mark(webInfArchiveRoot); entries.add(webInfArchiveRoot); } catch (IOException e) { throw new DeploymentUnitProcessingException("failed to process " + archive, e); } } } } }
package com.nityankhanna.androidutils.system; import android.annotation.TargetApi; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.ContextWrapper; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.nfc.NfcAdapter; import android.os.Build; import android.provider.Settings; /** * A ServiceManager providing methods to determine certain service connectivity. */ public class ServiceManager extends ContextWrapper { private static ServiceManager sharedInstance; private Context context; private ServiceManager(Context context) { super(context); this.context = context; } /** * Returns a shared instance of the ServiceManager class. * * @param context The application context. * * @return Returns a shared instance of the ServiceManager class. */ public static ServiceManager getInstance(Context context) { synchronized (ServiceManager.class) { if (sharedInstance == null) { sharedInstance = new ServiceManager(context); } } return sharedInstance; } /** * Determines if airplane mode is enabled on the current device. * * @return Returns true if airplane mode is enabled. */ public boolean isAirplaneModeOn() { return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } /** * Determines if Android Beam is available on the current device. * * @return Returns true if Android Beam is available. * * @throws ServiceUnavailableException If the device does not support Android beam. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean isAndroidBeamAvailable() throws ServiceUnavailableException { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context); if (nfcAdapter == null) { throw new ServiceUnavailableException("The device does not support NFC."); } else { return nfcAdapter.isNdefPushEnabled(); } } /** * Determines if Bluetooth is available on the current device. * * @return Returns true if bluetooth is available. * * @throws ServiceUnavailableException If the device does not support bluetooth. */ public boolean isBluetoothAvailable() throws ServiceUnavailableException { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { throw new ServiceUnavailableException("The device does not support Bluetooth."); } else { return bluetoothAdapter.isEnabled(); } } /** * Determines if GPS is enabled. * * @return Returns true if GPS is enabled. */ public boolean isGPSEnabled() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } /** * Determines if there is internet connectivity. * * @return Returns true if there is internet connectivity. */ public boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return (activeNetworkInfo != null && activeNetworkInfo.isConnected()); } /** * Determines if Network Provider is available. * * @return Returns true if Network Provider is available. */ public boolean isNetworkProviderAvailable() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } /** * Determines if NFC is available on the current device. * * @return Returns true if NFC is available. * * @throws ServiceUnavailableException If the device does not support NFC. */ public boolean isNFCAvailable() throws ServiceUnavailableException { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context); if (nfcAdapter == null) { throw new ServiceUnavailableException("The device does not support NFC."); } else { return nfcAdapter.isEnabled(); } } /** * Determines if the user is connected Wi-Fi. * * @return Returns true if the user is connected to Wi-Fi. */ public boolean isOnWiFi() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return wifi.isConnected(); } /** * Determines if the device is running JellyBean or higher. * * @return Returns true if the device is running JellyBean or higher. */ public boolean isJellyBeanOrHigher() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; } /** * Determines if the device is running IceCreamSandwich or higher. * * @return Returns true if the device is running IceCreamSandwich or higher. */ public boolean isICSOrHigher() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; } /** * Determines if the device is running HoneyComb or higher. * * @return Returns true if the device is running HoneyComb or higher. */ public boolean isHoneycombOrHigher() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } /** * Determines if the device is running Gingerbread or higher. * * @return Returns true if the device is running Gingerbread or higher. */ public boolean isGingerbreadOrHigher() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; } /** * Determines if the device is running Froyo or higher. * * @return Returns true if the device is running Froyo or higher. */ public boolean isFroyoOrHigher() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; } /** * Determines if the device is a GoogleTV. * * @return Returns true if the device is a GoogleTV. */ public boolean isGoogleTV(Context context) { return context.getPackageManager().hasSystemFeature("com.google.android.tv"); } }
package uk.ac.ucl.excites.sapelli.storage.queries.constraints; import uk.ac.ucl.excites.sapelli.storage.model.Record; /** * Disjunction of Constraints. * * @author mstevens */ public class OrConstraint extends CompositeConstraint { public OrConstraint(Constraint... constraints) { super(constraints); } /* (non-Javadoc) * @see uk.ac.ucl.excites.sapelli.storage.queries.constraints.Constraint#_isValid(uk.ac.ucl.excites.sapelli.storage.model.Record) */ @Override protected boolean _isValid(Record record) { for(Constraint subConstraint : constraints) if(subConstraint._isValid(record)) return true; return !hasSubConstraints(); // if we do not have subConstraints then any record is valid, if we *do* have subconstraints then reaching this line means none of them caused us to return true above, so return false. } /* (non-Javadoc) * @see uk.ac.ucl.excites.sapelli.storage.queries.constraints.Constraint#accept(uk.ac.ucl.excites.sapelli.storage.queries.constraints.ConstraintVisitor) */ @Override public void accept(ConstraintVisitor visitor) { visitor.visit(this); } @Override protected boolean isAssociative() { return true; } }
package com.lukekorth.android_500px.services; import android.app.IntentService; import android.app.WallpaperManager; import android.content.Intent; import android.graphics.Bitmap; import android.os.PowerManager; import android.os.SystemClock; import com.lukekorth.android_500px.WallpaperApplication; import com.lukekorth.android_500px.helpers.Settings; import com.lukekorth.android_500px.helpers.Utils; import com.lukekorth.android_500px.models.Photos; import com.lukekorth.android_500px.models.WallpaperChangedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class WallpaperService extends IntentService { public static final String SLEEP_KEY = "sleep"; public WallpaperService() { super("WallpaperService"); } @Override protected void onHandleIntent(Intent intent) { Logger logger = LoggerFactory.getLogger("WallpaperService"); if (Settings.isEnabled(this)) { PowerManager.WakeLock wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "500pxApiService"); wakeLock.acquire(); WallpaperManager wallpaperManager = WallpaperManager.getInstance(this); int width = wallpaperManager.getDesiredMinimumWidth(); int height = wallpaperManager.getDesiredMinimumHeight(); if (Utils.supportsParallax(this) && !Settings.useParallax(this)) { width = width / 2; } logger.debug("Setting wallpaper to " + width + "px wide by " + height + "px tall"); try { if (intent.getBooleanExtra(SLEEP_KEY, false)) { SystemClock.sleep(10000); } Photos photo = Photos.getNextPhoto(this); if (photo != null) { Bitmap bitmap = WallpaperApplication.getPicasso(this) .load(photo.imageUrl) .centerCrop() .resize(width, height) .get(); wallpaperManager.setBitmap(bitmap); } else { logger.debug("Next photo was null"); } } catch (IOException e) { logger.error(e.getMessage()); } if (Utils.needMorePhotos(this)) { logger.debug("Getting more photos via ApiService"); startService(new Intent(this, ApiService.class)); } Settings.setUpdated(this); WallpaperApplication.getBus().post(new WallpaperChangedEvent()); wakeLock.release(); } else { logger.debug("App not enabled"); } } }
package ch.hearc.pokerface.gui.gamescreen.table; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.FontFormatException; import java.awt.GridLayout; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import net.miginfocom.swing.MigLayout; import ch.hearc.pokerface.gameengine.cards.Card; import ch.hearc.pokerface.gameengine.gamecore.GameEngine; import ch.hearc.pokerface.gui.gamescreen.player.PlayerComponent; import ch.hearc.pokerface.gui.tools.ButtonTools; import ch.hearc.pokerface.gui.tools.ColorShop; import ch.hearc.pokerface.gui.tools.ImagePanel; public class JPanelGameArea extends ImagePanel { private List<PlayerComponent> playerComponents; private GameEngine gameEngine; private BoardCardsPanel boardCardsPanel; private JLabel potBet; private JLabel potTurnTotal; private JLabel potStateTotal; private JLabel currentState; public JPanelGameArea(GameEngine gameEngine) throws IOException { super(ImageIO.read(ClassLoader.getSystemResource("resources/table/misc/background.png"))); setDoubleBuffered(true); this.gameEngine = gameEngine; playerComponents = new ArrayList<PlayerComponent>(); // BOARD & STATS boardCardsPanel = new BoardCardsPanel(); potBet = new JLabel(); potStateTotal = new JLabel(); potTurnTotal = new JLabel(); currentState = new JLabel(); currentState.setForeground(ColorShop.PF_RED); stylePotLabel(potBet); stylePotLabel(potStateTotal); stylePotLabel(potTurnTotal); stylePotLabel(currentState); JPanel currentStatePanel = new JPanel(); currentStatePanel.setOpaque(false); currentStatePanel.setLayout(new GridLayout(0,1)); currentStatePanel.add(new JLabel()); currentStatePanel.add(currentState); currentStatePanel.add(new JLabel()); JPanel containerCurrentStatePanel = new JPanel(); containerCurrentStatePanel.setOpaque(false); containerCurrentStatePanel.setLayout(new BoxLayout(containerCurrentStatePanel,BoxLayout.X_AXIS)); containerCurrentStatePanel.setPreferredSize(new Dimension(100,100)); containerCurrentStatePanel.add(currentStatePanel); JPanel panelPot = new JPanel(); panelPot.setOpaque(false); panelPot.setLayout(new GridLayout(0,1)); potBet.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, ColorShop.PF_GOLD_COLOR)); panelPot.add(potBet); panelPot.add(potTurnTotal); potStateTotal.setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, ColorShop.PF_GOLD_COLOR)); panelPot.add(potStateTotal); JPanel containerPanelPot = new JPanel(); containerPanelPot.setOpaque(false); containerPanelPot.setLayout(new BoxLayout(containerPanelPot,BoxLayout.X_AXIS)); containerPanelPot.setPreferredSize(new Dimension(260,140)); containerPanelPot.add(panelPot); JPanel panelBoard = new JPanel(); panelBoard.setOpaque(false); panelBoard.setLayout(new BoxLayout(panelBoard,BoxLayout.X_AXIS)); panelBoard.add(containerPanelPot); panelBoard.add(boardCardsPanel); panelBoard.add(containerCurrentStatePanel); setLayout(new BorderLayout()); JPanel panelPlayer = new JPanel(); panelPlayer.setLayout(new MigLayout()); panelPlayer.setOpaque(false); panelPlayer.setBorder(new EmptyBorder(50, 10, 50, 10)); // inside padding int nbPlayers = this.gameEngine.getPlayers().size(); for(int i = 0; i < nbPlayers; ++i) { playerComponents.add(new PlayerComponent(this.gameEngine.getPlayers().get(i))); } switch(nbPlayers) { case 10: panelPlayer.add(playerComponents.get(9), "pos 0.75al 0.9al"); case 9: panelPlayer.add(playerComponents.get(8), "pos 0.95al 0.05al"); case 8: panelPlayer.add(playerComponents.get(7), "pos 0.95al 0.75al"); case 7: panelPlayer.add(playerComponents.get(6), "pos 0.75al 0-pref/5"); case 6: panelPlayer.add(playerComponents.get(5), "pos 0.5al 0-pref/5"); case 5: panelPlayer.add(playerComponents.get(4), "pos 0.25al 0-pref/5"); case 4: panelPlayer.add(playerComponents.get(3), "pos 0.05al 0.05al"); case 3: panelPlayer.add(playerComponents.get(2), "pos 0.05al 0.75al"); panelPlayer.add(playerComponents.get(1), "pos 0.25al 0.9al"); panelPlayer.add(playerComponents.get(0), "pos 0.5al 0.9al"); break; case 2: panelPlayer.add(playerComponents.get(1), "pos 0.5al 0-pref/5"); panelPlayer.add(playerComponents.get(0), "pos 0.5al 0.9al"); break; } panelPlayer.add(panelBoard, "pos container.w/2-pref/2 container.h/2-pref+pref/10"); //Centered add(panelPlayer, BorderLayout.CENTER); } private void stylePotLabel(JLabel potString) { Font font = potString.getFont(); try { font = Font.createFont(Font.TRUETYPE_FONT, ClassLoader.getSystemResourceAsStream(ButtonTools.BUTTON_FONT_NAME)); } catch (FontFormatException | IOException e) { e.printStackTrace(); } font = font.deriveFont(25f); potString.setFont(font); } public void updateGUI() { if (!gameEngine.getIsFinished()) { Card[] cards = gameEngine.getUnorderedBoard(); boardCardsPanel.setCards(cards); boolean everyoneAllin = false; if (gameEngine.getAllInPlayer() == gameEngine.getUnfoldedPlayer()) { everyoneAllin = true; } boolean hasSomeoneWon = false; for(PlayerComponent playerComponent:playerComponents) { if (playerComponent.getPlayer().getHasWon()) { hasSomeoneWon = true; break; } } for(PlayerComponent playerComponent:playerComponents) { playerComponent.updateGUI(); if (playerComponent.getPlayer().getHasWon()) { playerComponent.setHasWonGraphics(true); } else { playerComponent.setHasWonGraphics(false); } if (!hasSomeoneWon && playerComponent.getPlayer() == gameEngine.getCurrentPlayer()) { playerComponent.setCurrentlyPlayingGraphics(true); } else { playerComponent.setCurrentlyPlayingGraphics(false); } if (everyoneAllin) { playerComponent.setAllinShow(true); } } potBet.setText("<html><font color=black>Current bet</font> : $" + gameEngine.getBet() + "</html>"); potTurnTotal.setText("<html><font color=black>Turn total</font> : $" + gameEngine.getTurnTotal() + "</html>"); potStateTotal.setText("<html><font color=black>State total</font> : $" + gameEngine.getStateTotal() + "</html>"); switch (gameEngine.getOldState()) { case BettingState: currentState.setText("Betting"); break; case FlopState: currentState.setText("Flop"); break; case PreFlopState: currentState.setText("Preflop"); break; case RiverState: currentState.setText("River"); break; case ShowdownState: currentState.setText("Showdown"); break; case TurnState: currentState.setText("Turn"); break; } } } }
package org.requs.syntax; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import javax.validation.constraints.NotNull; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.TokenStream; import org.requs.ontology.XeOntology; import org.xembly.Directives; import org.xembly.ImpossibleModificationException; import org.xembly.Xembler; /** * Syntax analysis. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ public final class AntlrSpec { /** * Text to parse. */ private final transient String text; /** * Public ctor. * @param content The text to parse */ public AntlrSpec(@NotNull final String content) { this.text = content; } /** * Get all clauses found in the text. * @return Clauses found */ public XML xml() { final CharStream input = new ANTLRInputStream(this.text); final SpecLexer lexer = new SpecLexer(input); final TokenStream tokens = new CommonTokenStream(lexer); final SpecParser parser = new SpecParser(tokens); final Errors errors = new Errors(); parser.removeErrorListeners(); parser.addErrorListener(errors); final XeOntology onto = new XeOntology(); parser.setOntology(onto); try { parser.clauses(); } catch (final RecognitionException ex) { throw new IllegalArgumentException(ex); } try { return new XMLDocument( new Xembler(new Directives().append(onto).append(errors)).xml() ); } catch (final ImpossibleModificationException ex) { throw new IllegalStateException(ex); } } }
package net.runelite.api; import com.jagex.oldscape.pub.OAuthApi; import java.awt.Canvas; import java.awt.Dimension; import java.util.EnumSet; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.runelite.api.annotations.VarCInt; import net.runelite.api.annotations.VarCStr; import net.runelite.api.annotations.Varbit; import net.runelite.api.annotations.VisibleForDevtools; import net.runelite.api.clan.ClanChannel; import net.runelite.api.clan.ClanID; import net.runelite.api.clan.ClanSettings; import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.WorldPoint; import net.runelite.api.hooks.Callbacks; import net.runelite.api.hooks.DrawCallbacks; import net.runelite.api.vars.AccountType; import net.runelite.api.widgets.ItemQuantityMode; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetConfig; import net.runelite.api.widgets.WidgetInfo; import org.intellij.lang.annotations.MagicConstant; /** * Represents the RuneScape client. */ public interface Client extends OAuthApi, GameEngine { /** * The injected client invokes these callbacks to send events to us */ Callbacks getCallbacks(); /** * The injected client invokes these callbacks for scene drawing, which is * used by the gpu plugin to override the client's normal scene drawing code */ DrawCallbacks getDrawCallbacks(); void setDrawCallbacks(DrawCallbacks drawCallbacks); String getBuildID(); /** * Gets a list of all valid players from the player cache. * * @return a list of all players */ List<Player> getPlayers(); /** * Gets a list of all valid NPCs from the NPC cache. * * @return a list of all NPCs */ List<NPC> getNpcs(); /** * Gets an array of all cached NPCs. * * @return cached NPCs */ NPC[] getCachedNPCs(); /** * Gets an array of all cached players. * * @return cached players */ Player[] getCachedPlayers(); /** * Gets the current modified level of a skill. * * @param skill the skill * @return the modified skill level */ int getBoostedSkillLevel(Skill skill); /** * Gets the real level of a skill. * * @param skill the skill * @return the skill level */ int getRealSkillLevel(Skill skill); /** * Calculates the total level from real skill levels. * * @return the total level */ int getTotalLevel(); /** * Adds a new chat message to the chatbox. * * @param type the type of message * @param name the name of the player that sent the message * @param message the message contents * @param sender the sender/channel name * @return the message node for the message */ MessageNode addChatMessage(ChatMessageType type, String name, String message, String sender); /** * Adds a new chat message to the chatbox. * * @param type the type of message * @param name the name of the player that sent the message * @param message the message contents * @param sender the sender/channel name * @param postEvent whether to post the chat message event * @return the message node for the message */ MessageNode addChatMessage(ChatMessageType type, String name, String message, String sender, boolean postEvent); /** * Gets the current game state. * * @return the game state */ GameState getGameState(); /** * Sets the current game state * * @param gameState */ void setGameState(GameState gameState); /** * Causes the client to shutdown. It is faster than * {@link java.applet.Applet#stop()} because it doesn't wait for 4000ms. * This will call {@link System#exit} when it is done */ void stopNow(); /** * DEPRECATED. See getAccountHash instead. * Gets the current logged in username. * * @return the logged in username * @see OAuthApi#getAccountHash() */ @Deprecated String getUsername(); /** * Sets the current logged in username. * * @param name the logged in username */ void setUsername(String name); /** * Sets the password on login screen. * * @param password the login screen password */ void setPassword(String password); /** * Sets the 6 digit pin used for authenticator on login screen. * * @param otp one time password */ void setOtp(String otp); /** * Gets currently selected login field. 0 is username, and 1 is password. * * @return currently selected login field */ int getCurrentLoginField(); /** * Gets index of current login state. 2 is username/password form, 4 is authenticator form * * @return current login state index */ int getLoginIndex(); /** * Gets the account type of the logged in player. * * @return the account type */ AccountType getAccountType(); @Override Canvas getCanvas(); /** * Gets the current FPS (frames per second). * * @return the FPS */ int getFPS(); /** * Gets the x-axis coordinate of the camera. * <p> * This value is a local coordinate value similar to * {@link #getLocalDestinationLocation()}. * * @return the camera x coordinate */ int getCameraX(); /** * Gets the y-axis coordinate of the camera. * <p> * This value is a local coordinate value similar to * {@link #getLocalDestinationLocation()}. * * @return the camera y coordinate */ int getCameraY(); /** * Gets the z-axis coordinate of the camera. * <p> * This value is a local coordinate value similar to * {@link #getLocalDestinationLocation()}. * * @return the camera z coordinate */ int getCameraZ(); /** * Gets the actual pitch of the camera. * <p> * The value returned by this method is measured in JAU, or Jagex * Angle Unit, which is 1/1024 of a revolution. * * @return the camera pitch */ int getCameraPitch(); /** * Gets the yaw of the camera. * * @return the camera yaw */ int getCameraYaw(); /** * Gets the current world number of the logged in player. * * @return the logged in world number */ int getWorld(); /** * Gets the canvas height * @return */ int getCanvasHeight(); /** * Gets the canvas width * @return */ int getCanvasWidth(); /** * Gets the height of the viewport. * * @return the viewport height */ int getViewportHeight(); /** * Gets the width of the viewport. * * @return the viewport width */ int getViewportWidth(); /** * Gets the x-axis offset of the viewport. * * @return the x-axis offset */ int getViewportXOffset(); /** * Gets the y-axis offset of the viewport. * * @return the y-axis offset */ int getViewportYOffset(); /** * Gets the scale of the world (zoom value). * * @return the world scale */ int getScale(); /** * Gets the current position of the mouse on the canvas. * * @return the mouse canvas position */ Point getMouseCanvasPosition(); /** * Gets a 3D array containing the heights of tiles in the * current scene. * * @return the tile heights */ int[][][] getTileHeights(); /** * Gets a 3D array containing the settings of tiles in the * current scene. * * @return the tile settings */ byte[][][] getTileSettings(); /** * Gets the current plane the player is on. * <p> * This value indicates the current map level above ground level, where * ground level is 0. For example, going up a ladder in Lumbridge castle * will put the player on plane 1. * <p> * Note: This value will never be below 0. Basements and caves below ground * level use a tile offset and are still considered plane 0 by the game. * * @return the plane */ int getPlane(); /** * Get the max plane being rendered on the scene. This is usually the max plane, 3, unless roofs are hidden, * where it will be the current plane. * @return */ int getSceneMaxPlane(); /** * Gets the current scene */ Scene getScene(); /** * Gets the logged in player instance. * * @return the logged in player */ Player getLocalPlayer(); /** * Get the local player's follower, such as a pet * @return */ @Nullable NPC getFollower(); /** * Gets the item composition corresponding to an items ID. * * @param id the item ID * @return the corresponding item composition * @see ItemID */ @Nonnull ItemComposition getItemDefinition(int id); /** * Creates an item icon sprite with passed variables. * * @param itemId the item ID * @param quantity the item quantity * @param border whether to draw a border * @param shadowColor the shadow color * @param stackable whether the item is stackable * @param noted whether the item is noted * @param scale the scale of the sprite * @return the created sprite */ @Nullable SpritePixels createItemSprite(int itemId, int quantity, int border, int shadowColor, @MagicConstant(valuesFromClass = ItemQuantityMode.class) int stackable, boolean noted, int scale); /** * Get the item model cache. These models are used for drawing widgets of type {@link net.runelite.api.widgets.WidgetType#MODEL} * and inventory item icons * @return */ NodeCache getItemModelCache(); /** * Get the item sprite cache. These are 2d SpritePixels which are used to raster item images on the inventory and * on widgets of type {@link net.runelite.api.widgets.WidgetType#GRAPHIC} * @return */ NodeCache getItemSpriteCache(); /** * Loads and creates the sprite images of the passed archive and file IDs. * * @param source the sprite index * @param archiveId the sprites archive ID * @param fileId the sprites file ID * @return the sprite image of the file */ @Nullable SpritePixels[] getSprites(IndexDataBase source, int archiveId, int fileId); /** * Gets the sprite index. */ IndexDataBase getIndexSprites(); /** * Gets the script index. */ IndexDataBase getIndexScripts(); /** * Gets the config index. */ IndexDataBase getIndexConfig(); /** * Gets an index by id */ IndexDataBase getIndex(int id); /** * Returns the x-axis base coordinate. * <p> * This value is the x-axis world coordinate of tile (0, 0) in * the current scene (ie. the bottom-left most coordinates in the scene). * * @return the base x-axis coordinate */ int getBaseX(); /** * Returns the y-axis base coordinate. * <p> * This value is the y-axis world coordinate of tile (0, 0) in * the current scene (ie. the bottom-left most coordinates in the scene). * * @return the base y-axis coordinate */ int getBaseY(); /** * Gets the current mouse button that is pressed. * * @return the pressed mouse button */ int getMouseCurrentButton(); /** * Gets the currently selected tile. (ie. last right clicked tile) * * @return the selected tile */ @Nullable Tile getSelectedSceneTile(); /** * Checks whether a widget is currently being dragged. * * @return true if dragging a widget, false otherwise */ boolean isDraggingWidget(); /** * Gets the widget currently being dragged. * * @return the dragged widget, null if not dragging any widget */ @Nullable Widget getDraggedWidget(); /** * Gets the widget that is being dragged on. * <p> * The widget being dragged has the {@link net.runelite.api.widgets.WidgetConfig#DRAG_ON} * flag set, and is the widget currently under the dragged widget. * * @return the dragged on widget, null if not dragging any widget */ @Nullable Widget getDraggedOnWidget(); /** * Sets the widget that is being dragged on. * * @param widget the new dragged on widget */ void setDraggedOnWidget(Widget widget); /** * Get the number of client cycles the current dragged widget * has been dragged for. * * @return */ int getDragTime(); /** * Gets Interface ID of the root widget */ int getTopLevelInterfaceId(); /** * Gets the root widgets. * * @return the root widgets */ Widget[] getWidgetRoots(); /** * Gets a widget corresponding to the passed widget info. * * @param widget the widget info * @return the widget */ @Nullable Widget getWidget(WidgetInfo widget); /** * Gets a widget by its raw group ID and child ID. * <p> * Note: Use {@link #getWidget(WidgetInfo)} for a more human-readable * version of this method. * * @param groupId the group ID * @param childId the child widget ID * @return the widget corresponding to the group and child pair */ @Nullable Widget getWidget(int groupId, int childId); /** * Gets a widget by it's packed ID. * * <p> * Note: Use {@link #getWidget(WidgetInfo)} or {@link #getWidget(int, int)} for * a more readable version of this method. */ @Nullable Widget getWidget(int packedID); /** * Gets an array containing the x-axis canvas positions * of all widgets. * * @return array of x-axis widget coordinates */ int[] getWidgetPositionsX(); /** * Gets an array containing the y-axis canvas positions * of all widgets. * * @return array of y-axis widget coordinates */ int[] getWidgetPositionsY(); /** * Gets the current run energy of the logged in player. * * @return the run energy */ int getEnergy(); /** * Gets the current weight of the logged in player. * * @return the weight */ int getWeight(); /** * Gets an array of options that can currently be used on other players. * <p> * For example, if the player is in a PVP area the "Attack" option * will become available in the array. Otherwise, it won't be there. * * @return an array of options */ String[] getPlayerOptions(); /** * Gets an array of whether an option is enabled or not. * * @return the option priorities */ boolean[] getPlayerOptionsPriorities(); /** * Gets an array of player menu types. * * @return the player menu types */ int[] getPlayerMenuTypes(); /** * Gets a list of all RuneScape worlds. * * @return world list */ World[] getWorldList(); /** * Create a new menu entry * @param idx the index to create the menu entry at. Accepts negative indexes eg. -1 inserts at the end. * @return the newly created menu entry */ MenuEntry createMenuEntry(int idx); /** * Gets an array of currently open right-click menu entries that can be * clicked and activated. * * @return array of open menu entries */ MenuEntry[] getMenuEntries(); /** * Sets the array of open menu entries. * <p> * This method should typically be used in the context of the {@link net.runelite.api.events.MenuOpened} * event, since setting the menu entries will be overwritten the next frame * * @param entries new array of open menu entries */ void setMenuEntries(MenuEntry[] entries); /** * Checks whether a right-click menu is currently open. * * @return true if a menu is open, false otherwise */ boolean isMenuOpen(); /** * Get the menu x location. Only valid if the menu is open. * * @return the menu x location */ int getMenuX(); /** * Get the menu y location. Only valid if the menu is open. * * @return the menu y location */ int getMenuY(); /** * Get the menu height. Only valid if the menu is open. * * @return the menu height */ int getMenuHeight(); /** * Get the menu width. Only valid if the menu is open. * * @return the menu width */ int getMenuWidth(); /** * Gets the angle of the map, or target camera yaw. * * @return the map angle */ int getMapAngle(); /** * Set the target camera yaw * * @param cameraYawTarget */ void setCameraYawTarget(int cameraYawTarget); /** * Checks whether the client window is currently resized. * * @return true if resized, false otherwise */ boolean isResized(); /** * Gets the client revision number. * * @return the revision */ int getRevision(); /** * Gets an array of map region IDs that are currently loaded. * * @return the map regions */ int[] getMapRegions(); /** * Contains a 3D array of template chunks for instanced areas. * <p> * The array returned is of format [z][x][y], where z is the * plane, x and y the x-axis and y-axis coordinates of a tile * divided by the size of a chunk. * <p> * The bits of the int value held by the coordinates are -1 if there is no data, * structured in the following format: * <pre>{@code * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | |rot| y chunk coord | x chunk coord |pln| | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * }</pre> * @return the array of instance template chunks * @see Constants#CHUNK_SIZE * @see InstanceTemplates */ int[][][] getInstanceTemplateChunks(); /** * Returns a 2D array containing XTEA encryption keys used to decrypt * map region files. * <p> * The array maps the region keys at index {@code n} to the region * ID held in {@link #getMapRegions()} at {@code n}. * <p> * The array of keys for the region make up a 128-bit encryption key * spread across 4 integers. * * @return the XTEA encryption keys */ int[][] getXteaKeys(); /** * Gets an array of all client varplayers. * * @return local player variables */ @VisibleForDevtools int[] getVarps(); @VisibleForDevtools int[] getServerVarps(); /** * Gets an array of all client variables. */ @VisibleForDevtools Map<Integer, Object> getVarcMap(); /** * Gets the value corresponding to the passed player variable. * * @param varPlayer the player variable * @return the value * @see Client#getVarpValue(VarPlayer) */ @Deprecated int getVar(VarPlayer varPlayer); /** * Gets the value corresponding to the passed player variable. * * @param varPlayer the player variable * @return the value */ int getVarpValue(VarPlayer varPlayer); /** * Gets a value corresponding to the passed varbit. * * @param varbit the varbit id * @return the value * @see Client#getVarbitValue(int) */ @Deprecated int getVar(@Varbit int varbit); /** * Gets the value of the given varbit. * * @param varbit the varbit id * @return the value */ int getVarbitValue(@Varbit int varbit); /** * Gets the value of the given varbit. * This returns the server's idea of the value, not the client's. This is * specifically the last value set by the server regardless of changes to * the var by the client. * @param varbit the varbit id * @return the value */ int getServerVarbitValue(@Varbit int varbit); /** * Gets the value of a given VarPlayer. * * @param varpId the VarPlayer id * @return the value */ int getVarpValue(int varpId); /** * Gets the value of a given VarPlayer. * This returns the server's idea of the value, not the client's. This is * specifically the last value set by the server regardless of changes to * the var by the client. * * @param varpId the VarPlayer id * @return the value */ int getServerVarpValue(int varpId); /** * Gets the value of a given VarClientInt * * @param var the {@link VarClientInt} * @return the value */ int getVarcIntValue(@VarCInt int var); /** * Gets the value of a given VarClientStr * * @param var the {@link VarClientStr} * @return the value */ String getVarcStrValue(@VarCStr int var); /** * Sets a VarClientString to the passed value * * @param var the {@link VarClientStr} * @param value the new value */ void setVarcStrValue(@VarCStr int var, String value); /** * Sets a VarClientInt to the passed value * * @param var the {@link VarClientInt} * @param value the new value */ void setVarcIntValue(@VarCInt int var, int value); /** * Sets the value of a varbit * * @param varbit the varbit id * @param value the new value */ void setVarbit(@Varbit int varbit, int value); /** * Gets the varbit composition for a given varbit id * * @param id * @return */ @VisibleForDevtools @Nullable VarbitComposition getVarbit(int id); /** * Gets the value of a given variable. * * @param varps passed varbits * @param varbitId the variable ID * @return the value * @see Varbits */ @VisibleForDevtools int getVarbitValue(int[] varps, @Varbit int varbitId); /** * Sets the value of a given variable. * * @param varps passed varbits * @param varbit the variable * @param value the value * @see Varbits */ @VisibleForDevtools void setVarbitValue(int[] varps, @Varbit int varbit, int value); /** * Mark the given varp as changed, causing var listeners to be * triggered next tick * @param varp */ void queueChangedVarp(int varp); /** * Gets the widget flags table. * * @return the widget flags table */ HashTable<IntegerNode> getWidgetFlags(); /** * Gets the widget node component table. * * @return the widget node component table * @see WidgetNode */ HashTable<WidgetNode> getComponentTable(); /** * Gets an array of current grand exchange offers. * * @return all grand exchange offers */ GrandExchangeOffer[] getGrandExchangeOffers(); /** * Checks whether or not a prayer is currently active. * * @param prayer the prayer * @return true if the prayer is active, false otherwise */ boolean isPrayerActive(Prayer prayer); /** * Gets the current experience towards a skill. * * @param skill the skill * @return the experience */ int getSkillExperience(Skill skill); /** * Get the total experience of the player * * @return */ long getOverallExperience(); /** * Refreshes the chat. */ void refreshChat(); /** * Gets the map of chat buffers. * * @return the chat buffers */ Map<Integer, ChatLineBuffer> getChatLineMap(); /** * Map of message node id to message node * * @return the map */ IterableHashTable<MessageNode> getMessages(); /** * Gets the object composition corresponding to an objects ID. * * @param objectId the object ID * @return the corresponding object composition * @see ObjectID */ ObjectComposition getObjectDefinition(int objectId); /** * Gets the NPC composition corresponding to an NPCs ID. * * @param npcId the npc ID * @return the corresponding NPC composition * @see NpcID */ NPCComposition getNpcDefinition(int npcId); /** * Gets the {@link StructComposition} for a given struct ID * * @see StructID */ StructComposition getStructComposition(int structID); /** * Gets the client's cache of in memory struct compositions */ NodeCache getStructCompositionCache(); /** * Gets a entry out of a DBTable Row */ Object getDBTableField(int rowID, int column, int tupleIndex, int fieldIndex); /** * Gets an array of all world areas * * @return the world areas */ MapElementConfig[] getMapElementConfigs(); /** * Gets a sprite of the map scene * * @return the sprite */ IndexedSprite[] getMapScene(); /** * Gets an array of currently drawn mini-map dots. * * @return all mini-map dots */ SpritePixels[] getMapDots(); /** * Gets the local clients game cycle. * <p> * Note: This value is incremented every 20ms. * * @return the game cycle */ int getGameCycle(); /** * Gets an array of current map icon sprites. * * @return the map icons */ SpritePixels[] getMapIcons(); /** * Gets an array of mod icon sprites. * * @return the mod icons */ IndexedSprite[] getModIcons(); /** * Replaces the current mod icons with a new array. * * @param modIcons the new mod icons */ void setModIcons(IndexedSprite[] modIcons); /** * Creates an empty indexed sprite. * * @return the sprite */ IndexedSprite createIndexedSprite(); /** * Creates a sprite image with given width and height containing the * pixels. * * @param pixels the pixels * @param width the width * @param height the height * @return the sprite image */ SpritePixels createSpritePixels(int[] pixels, int width, int height); /** * Gets the location of the local player. * * @return the local player location */ @Nullable LocalPoint getLocalDestinationLocation(); /** * Create a projectile. * @param id projectile/spotanim id * @param plane plane the projectile is on * @param startX local x coordinate the projectile starts at * @param startY local y coordinate the projectile starts at * @param startZ local z coordinate the projectile starts at - includes tile height * @param startCycle cycle the project starts * @param endCycle cycle the projectile ends * @param slope * @param startHeight start height of projectile - excludes tile height * @param endHeight end height of projectile - excludes tile height * @param target optional actor target * @param targetX target x - if an actor target is supplied should be the target x * @param targetY taret y - if an actor target is supplied should be the target y * @return the new projectile */ Projectile createProjectile(int id, int plane, int startX, int startY, int startZ, int startCycle, int endCycle, int slope, int startHeight, int endHeight, @Nullable Actor target, int targetX, int targetY); /** * Gets a list of all projectiles currently spawned. * * @return all projectiles */ Deque<Projectile> getProjectiles(); /** * Gets a list of all graphics objects currently drawn. * * @return all graphics objects */ Deque<GraphicsObject> getGraphicsObjects(); /** * Creates a RuneLiteObject, which is a modified {@link GraphicsObject} */ RuneLiteObject createRuneLiteObject(); /** * Loads an unlit model from the cache. The returned model shares * data such as faces, face colors, face transparencies, and vertex points with * other models. If you want to mutate these you MUST call the relevant {@code cloneX} * method. * * @see ModelData#cloneColors() * * @param id the ID of the model * @return the model or null if it is loading or nonexistent */ @Nullable ModelData loadModelData(int id); ModelData mergeModels(ModelData[] models, int length); ModelData mergeModels(ModelData ...models); /** * Loads and lights a model from the cache * * This is equivalent to {@code loadModelData(id).light()} * * @param id the ID of the model * @return the model or null if it is loading or nonexistent */ @Nullable Model loadModel(int id); /** * Loads a model from the cache and also recolors it * * @param id the ID of the model * @param colorToFind array of hsl color values to find in the model to replace * @param colorToReplace array of hsl color values to replace in the model * @return the model or null if it is loading or nonexistent */ @Nullable Model loadModel(int id, short[] colorToFind, short[] colorToReplace); /** * Loads an animation from the cache * * @param id the ID of the animation. Any int is allowed, but implementations in the client * should be defined in {@link AnimationID} */ Animation loadAnimation(int id); /** * Gets the music volume * @return volume 0-255 inclusive */ int getMusicVolume(); /** * Sets the music volume * @param volume 0-255 inclusive */ void setMusicVolume(int volume); /** * @return true if the current {@link #getMusicCurrentTrackId()} is a Jingle, otherwise its a Track */ boolean isPlayingJingle(); /** * @return Currently playing music/jingle id, or -1 if not playing * @see #isPlayingJingle() */ int getMusicCurrentTrackId(); /** * Play a sound effect at the player's current location. This is how UI, * and player-generated (e.g. mining, woodcutting) sound effects are * normally played. * * @param id the ID of the sound to play. Any int is allowed, but see * {@link SoundEffectID} for some common ones */ void playSoundEffect(int id); /** * Play a sound effect from some point in the world. * * @param id the ID of the sound to play. Any int is allowed, but see * {@link SoundEffectID} for some common ones * @param x the ground coordinate on the x axis * @param y the ground coordinate on the y axis * @param range the number of tiles away that the sound can be heard * from */ void playSoundEffect(int id, int x, int y, int range); /** * Play a sound effect from some point in the world. * * @param id the ID of the sound to play. Any int is allowed, but see * {@link SoundEffectID} for some common ones * @param x the ground coordinate on the x axis * @param y the ground coordinate on the y axis * @param range the number of tiles away that the sound can be heard * from * @param delay the amount of frames before the sound starts playing */ void playSoundEffect(int id, int x, int y, int range, int delay); /** * Plays a sound effect, even if the player's sound effect volume is muted. * * @param id the ID of the sound effect - {@link SoundEffectID} * @param volume the volume to play the sound effect at, see {@link SoundEffectVolume} for values used * in the settings interface. if the sound effect volume is not muted, uses the set volume */ void playSoundEffect(int id, int volume); /** * Gets the clients graphic buffer provider. * * @return the buffer provider */ BufferProvider getBufferProvider(); /** * Gets the amount of client ticks since the last mouse movement occurred. * * @return amount of idle mouse ticks * @see Constants#CLIENT_TICK_LENGTH */ int getMouseIdleTicks(); /** * Gets the time at which the last mouse press occurred in milliseconds since * the UNIX epoch. */ long getMouseLastPressedMillis(); /** * Gets the amount of client ticks since the last keyboard press occurred. * * @return amount of idle keyboard ticks * @see Constants#CLIENT_TICK_LENGTH */ int getKeyboardIdleTicks(); /** * Changes how game behaves based on memory mode. Low memory mode skips * drawing of all floors and renders ground textures in low quality. * * @param lowMemory if we are running in low memory mode or not */ void changeMemoryMode(boolean lowMemory); /** * Get the item container for an inventory. * * @param inventory the inventory type * @return the item container * @see InventoryID */ @Nullable ItemContainer getItemContainer(InventoryID inventory); /** * Get an item container by id * * @param id the inventory id * @return the item container * @see InventoryID */ @Nullable ItemContainer getItemContainer(int id); /** * Get all item containers * @return */ HashTable<ItemContainer> getItemContainers(); /** * Gets the length of the cs2 vm's int stack */ int getIntStackSize(); /** * Sets the length of the cs2 vm's int stack */ void setIntStackSize(int stackSize); /** * Gets the cs2 vm's int stack */ int[] getIntStack(); /** * Gets the length of the cs2 vm's string stack */ int getStringStackSize(); /** * Sets the length of the cs2 vm's string stack */ void setStringStackSize(int stackSize); /** * Gets the cs2 vm's string stack */ String[] getStringStack(); /** * Gets the cs2 vm's active widget * * This is used for all {@code cc_*} operations with a {@code 0} operand */ Widget getScriptActiveWidget(); /** * Gets the cs2 vm's "dot" widget * * This is used for all {@code .cc_*} operations with a {@code 1} operand */ Widget getScriptDotWidget(); /** * Checks whether a player is on the friends list. * * @param name the name of the player * @param mustBeLoggedIn if they player is online * @return true if the player is friends */ boolean isFriended(String name, boolean mustBeLoggedIn); /** * Retrieve the friends chat manager * * @return */ @Nullable FriendsChatManager getFriendsChatManager(); /** * Retrieve the nameable container containing friends * * @return */ FriendContainer getFriendContainer(); /** * Retrieve the nameable container containing ignores * * @return */ NameableContainer<Ignore> getIgnoreContainer(); /** * Gets the clients saved preferences. * * @return the client preferences */ Preferences getPreferences(); /** * Sets whether the camera pitch can exceed the normal limits set * by the RuneScape client. * * @param enabled new camera pitch relaxer value */ void setCameraPitchRelaxerEnabled(boolean enabled); /** * Sets if the moving the camera horizontally should be backwards */ void setInvertYaw(boolean invertYaw); /** * Sets if the moving the camera vertically should be backwards */ void setInvertPitch(boolean invertPitch); /** * Gets the world map overview. * * @return the world map overview */ RenderOverview getRenderOverview(); /** * Checks whether the client is in stretched mode. * * @return true if the client is in stretched mode, false otherwise */ boolean isStretchedEnabled(); /** * Sets the client stretched mode state. * * @param state new stretched mode state */ void setStretchedEnabled(boolean state); /** * Checks whether the client is using fast * rendering techniques when stretching the canvas. * * @return true if stretching is fast rendering, false otherwise */ boolean isStretchedFast(); /** * Sets whether to use fast rendering techniques * when stretching the canvas. * * @param state new fast rendering state */ void setStretchedFast(boolean state); /** * Sets whether to force integer scale factor by rounding scale * factors towards {@code zero} when stretching. * * @param state new integer scaling state */ void setStretchedIntegerScaling(boolean state); /** * Sets whether to keep aspect ratio when stretching. * * @param state new keep aspect ratio state */ void setStretchedKeepAspectRatio(boolean state); /** * Sets the scaling factor when scaling resizable mode. * * @param factor new scaling factor */ void setScalingFactor(int factor); /** * Invalidates cached dimensions that are * used for stretching and scaling. * * @param resize true to tell the game to * resize the canvas on the next frame, * false otherwise. */ void invalidateStretching(boolean resize); /** * Gets the current stretched dimensions of the client. * * @return the stretched dimensions */ Dimension getStretchedDimensions(); /** * Gets the real dimensions of the client before being stretched. * * @return the real dimensions */ Dimension getRealDimensions(); /** * Changes the selected world to log in to. * <p> * Note: this method will have no effect unless {@link GameState} * is {@link GameState#LOGIN_SCREEN}. * * @param world the world to switch to */ void changeWorld(World world); /** * Creates a new instance of a world. */ World createWorld(); /** * Draws an instance map for the current viewed plane. * * @param z the plane * @return the map sprite */ SpritePixels drawInstanceMap(int z); /** * Executes a client script from the cache * * This method must be ran on the client thread and is not reentrant * * This method is shorthand for {@code client.createScriptEvent(args).run()} * * @param args the script id, then any additional arguments to execute the script with * @see ScriptID */ void runScript(Object... args); /** * Creates a blank ScriptEvent for executing a ClientScript2 script * * @param args the script id, then any additional arguments to execute the script with * @see ScriptID */ ScriptEvent createScriptEvent(Object ...args); /** * Checks whether or not there is any active hint arrow. * * @return true if there is a hint arrow, false otherwise */ boolean hasHintArrow(); /** * Gets the type of hint arrow currently displayed. * * @return the hint arrow type */ HintArrowType getHintArrowType(); /** * Clears the current hint arrow. */ void clearHintArrow(); /** * Sets a hint arrow to point to the passed location. * * @param point the location */ void setHintArrow(WorldPoint point); /** * Sets a hint arrow to point to the passed player. * * @param player the player */ void setHintArrow(Player player); /** * Sets a hint arrow to point to the passed NPC. * * @param npc the NPC */ void setHintArrow(NPC npc); /** * Gets the world point that the hint arrow is directed at. * * @return hint arrow target */ WorldPoint getHintArrowPoint(); /** * Gets the player that the hint arrow is directed at. * * @return hint arrow target */ Player getHintArrowPlayer(); /** * Gets the NPC that the hint arrow is directed at. * * @return hint arrow target */ NPC getHintArrowNpc(); /** * Checks whether animation smoothing is enabled for players. * * @return true if player animation smoothing is enabled, false otherwise */ boolean isInterpolatePlayerAnimations(); /** * Sets the animation smoothing state for players. * * @param interpolate the new smoothing state */ void setInterpolatePlayerAnimations(boolean interpolate); /** * Checks whether animation smoothing is enabled for NPC. * * @return true if NPC animation smoothing is enabled, false otherwise */ boolean isInterpolateNpcAnimations(); /** * Sets the animation smoothing state for NPCs. * * @param interpolate the new smoothing state */ void setInterpolateNpcAnimations(boolean interpolate); /** * Checks whether animation smoothing is enabled for objects. * * @return true if object animation smoothing is enabled, false otherwise */ boolean isInterpolateObjectAnimations(); /** * Sets the animation smoothing state for objects. * * @param interpolate the new smoothing state */ void setInterpolateObjectAnimations(boolean interpolate); /** * Checks whether the logged in player is in an instanced region. * * @return true if the player is in instanced region, false otherwise */ boolean isInInstancedRegion(); /** * Get the number of client ticks an item has been pressed * * @return the number of client ticks an item has been pressed */ int getItemPressedDuration(); /** * Gets an array of tile collision data. * <p> * The index into the array is the plane/z-axis coordinate. * * @return the collision data */ @Nullable CollisionData[] getCollisionMaps(); @VisibleForDevtools int[] getBoostedSkillLevels(); @VisibleForDevtools int[] getRealSkillLevels(); @VisibleForDevtools int[] getSkillExperiences(); void queueChangedSkill(Skill skill); /** * Gets a mapping of sprites to override. * <p> * The key value in the map corresponds to the ID of the sprite, * and the value the sprite to replace it with. */ Map<Integer, SpritePixels> getSpriteOverrides(); /** * Gets a mapping of widget sprites to override. * <p> * The key value in the map corresponds to the packed widget ID, * and the value the sprite to replace the widgets sprite with. */ Map<Integer, SpritePixels> getWidgetSpriteOverrides(); /** * Sets the compass sprite. * * @param spritePixels the new sprite */ void setCompass(SpritePixels spritePixels); /** * Returns widget sprite cache, to be used with {@link Client#getSpriteOverrides()} * * @return the cache */ NodeCache getWidgetSpriteCache(); /** * Gets the current server tick count. * * @return the tick count */ int getTickCount(); /** * Sets the current server tick count. * * @param tickCount the new tick count */ void setTickCount(int tickCount); /** * Sets the inventory drag delay in client game cycles (20ms). * * @param delay the number of game cycles to delay dragging */ @Deprecated void setInventoryDragDelay(int delay); /** * Gets a set of current world types that apply to the logged in world. * * @return the types for current world */ EnumSet<WorldType> getWorldType(); /** * Gets the enabled state for the Oculus orb mode */ int getOculusOrbState(); /** * Sets the enabled state for the Oculus orb state * * @param state boolean enabled value */ void setOculusOrbState(int state); /** * Sets the normal moving speed when using oculus orb (default value is 12) */ void setOculusOrbNormalSpeed(int speed); /** * Gets local X coord where the camera is pointing when the Oculus orb is active */ int getOculusOrbFocalPointX(); /** * Gets local Y coord where the camera is pointing when the Oculus orb is active */ int getOculusOrbFocalPointY(); /** * Opens in-game world hopper interface */ void openWorldHopper(); /** * Hops using in-game world hopper widget to another world * @param world target world to hop to */ void hopToWorld(World world); /** * Sets the RGB color of the skybox */ void setSkyboxColor(int skyboxColor); /** * Gets the RGB color of the skybox */ int getSkyboxColor(); boolean isGpu(); void setGpu(boolean gpu); int get3dZoom(); int getCenterX(); int getCenterY(); int getCameraX2(); int getCameraY2(); int getCameraZ2(); TextureProvider getTextureProvider(); void setRenderArea(boolean[][] renderArea); int getRasterizer3D_clipMidX2(); int getRasterizer3D_clipNegativeMidX(); int getRasterizer3D_clipNegativeMidY(); int getRasterizer3D_clipMidY2(); void checkClickbox(Model model, int orientation, int pitchSin, int pitchCos, int yawSin, int yawCos, int x, int y, int z, long hash); /** * Get the if1 widget whose item is being dragged * * @return */ @Deprecated Widget getIf1DraggedWidget(); /** * Get the item index of the item being dragged on an if1 widget * @return */ @Deprecated int getIf1DraggedItemIndex(); /** * Is a widget is in target mode? */ boolean getSpellSelected(); /** * Sets if a widget is in target mode */ void setSpellSelected(boolean selected); /** * Get if an item is selected with "Use" * @return 1 if selected, else 0 */ int getSelectedItem(); /** * If an item is selected, this is the item index in the inventory. * @return */ int getSelectedItemIndex(); /** * Get the selected widget, such as a selected spell or selected item (eg. "Use") * @return the selected widget */ @Nullable Widget getSelectedWidget(); /** * Returns client item composition cache */ NodeCache getItemCompositionCache(); /** * Returns client object composition cache * @return */ NodeCache getObjectCompositionCache(); /** * Returns the array of cross sprites that appear and animate when left-clicking */ SpritePixels[] getCrossSprites(); EnumComposition getEnum(int id); /** * Draws a menu in the 2010 interface style. * * @param alpha background transparency of the menu */ void draw2010Menu(int alpha); /** * Draws a menu in the OSRS interface style. * * @param alpha background transparency of the menu */ void drawOriginalMenu(int alpha); void resetHealthBarCaches(); /** * Returns the max item index + 1 from cache */ int getItemCount(); /** * Makes all widgets behave as if they are {@link WidgetConfig#WIDGET_USE_TARGET} */ void setAllWidgetsAreOpTargetable(boolean value); /** * Sets the result count for GE search */ void setGeSearchResultCount(int count); /** * Sets the array of item ids for GE search */ void setGeSearchResultIds(short[] ids); /** * Sets the starting index in the item id array for GE search */ void setGeSearchResultIndex(int index); /** * Sets the image to be used for the login screen, provided as SpritePixels * If the image is larger than half the width of fixed mode, * it won't get mirrored to the other side of the screen */ void setLoginScreen(SpritePixels pixels); /** * Sets whether the flames on the login screen should be rendered */ void setShouldRenderLoginScreenFire(boolean val); /** * Test if a key is pressed * @param keycode the keycode * @return * @see KeyCode */ boolean isKeyPressed(@MagicConstant(valuesFromClass = KeyCode.class) int keycode); /** * Get the list of message ids for the recently received cross-world messages. The upper 32 bits of the * id is the world id, the lower is a sequence number per-world. * * @return */ long[] getCrossWorldMessageIds(); /** * Get the index of the next message to be inserted in the cross world message id list * * @return */ int getCrossWorldMessageIdsIndex(); /** * Get the primary clan channel the player is in. * @return */ @Nullable ClanChannel getClanChannel(); /** * Get the guest clan channel the player is in. * @return */ @Nullable ClanChannel getGuestClanChannel(); /** * Get clan settings for the clan the user is in. * @return */ @Nullable ClanSettings getClanSettings(); /** * Get the guest clan's settings. * @return */ @Nullable ClanSettings getGuestClanSettings(); /** * Get clan channel by id. * @param clanId the clan id * @return * @see net.runelite.api.clan.ClanID */ @Nullable ClanChannel getClanChannel(@MagicConstant(valuesFromClass = ClanID.class) int clanId); /** * Get clan settings by id * @param clanId the clan id * @return * @see net.runelite.api.clan.ClanID */ @Nullable ClanSettings getClanSettings(@MagicConstant(valuesFromClass = ClanID.class) int clanId); void setUnlockedFps(boolean unlock); void setUnlockedFpsTarget(int fps); /** * Gets the ambient sound effects * @return */ Deque<AmbientSoundEffect> getAmbientSoundEffects(); /** * Set the amount of time until the client automatically logs out due to idle input. * @param ticks client ticks */ void setIdleTimeout(int ticks); /** * Get the amount of time until the client automatically logs out due to idle input. * @return client ticks */ int getIdleTimeout(); }
package com.ibm.bi.dml.runtime.controlprogram.parfor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.Vector; import java.util.Map.Entry; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM; import com.ibm.bi.dml.hops.Hops; import com.ibm.bi.dml.hops.OptimizerUtils; import com.ibm.bi.dml.lops.compile.Recompiler; import com.ibm.bi.dml.packagesupport.ExternalFunctionInvocationInstruction; import com.ibm.bi.dml.parser.DataIdentifier; import com.ibm.bi.dml.parser.ParForStatementBlock; import com.ibm.bi.dml.parser.StatementBlock; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.ValueType; import com.ibm.bi.dml.runtime.controlprogram.ExecutionContext; import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlockCP; import com.ibm.bi.dml.runtime.controlprogram.ForProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.FunctionProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.IfProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.LocalVariableMap; import com.ibm.bi.dml.runtime.controlprogram.ParForProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.Program; import com.ibm.bi.dml.runtime.controlprogram.ProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.SymbolTable; import com.ibm.bi.dml.runtime.controlprogram.WhileProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.ParForProgramBlock.PDataPartitionFormat; import com.ibm.bi.dml.runtime.controlprogram.ParForProgramBlock.PExecMode; import com.ibm.bi.dml.runtime.controlprogram.caching.MatrixObject; import com.ibm.bi.dml.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.ConfigurationManager; import com.ibm.bi.dml.runtime.instructions.CPInstructionParser; import com.ibm.bi.dml.runtime.instructions.Instruction; import com.ibm.bi.dml.runtime.instructions.MRInstructionParser; import com.ibm.bi.dml.runtime.instructions.MRJobInstruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.BooleanObject; import com.ibm.bi.dml.runtime.instructions.CPInstructions.CPInstruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.Data; import com.ibm.bi.dml.runtime.instructions.CPInstructions.DoubleObject; import com.ibm.bi.dml.runtime.instructions.CPInstructions.FunctionCallCPInstruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.IntObject; import com.ibm.bi.dml.runtime.instructions.CPInstructions.ScalarObject; import com.ibm.bi.dml.runtime.instructions.CPInstructions.StringObject; import com.ibm.bi.dml.runtime.instructions.MRInstructions.MRInstruction; import com.ibm.bi.dml.runtime.matrix.MatrixCharacteristics; import com.ibm.bi.dml.runtime.matrix.MatrixFormatMetaData; import com.ibm.bi.dml.runtime.matrix.io.InputInfo; import com.ibm.bi.dml.runtime.matrix.io.OutputInfo; import com.ibm.bi.dml.utils.DMLRuntimeException; import com.ibm.bi.dml.utils.DMLUnsupportedOperationException; import com.ibm.bi.dml.utils.configuration.DMLConfig; /** * Static functionalities for * * creating deep copies of program blocks, instructions, function program blocks * * serializing and parsing of programs, program blocks, functions program blocks * * TODO: CV, EL, ELUse program blocks not considered so far (not for BI 2.0 release) * TODO: rewrite class to instance-based invocation (grown gradually and now inappropriate design) * */ public class ProgramConverter { //use escaped unicodes for separators in order to prevent string conflict public static final String NEWLINE = "\n"; //System.lineSeparator(); public static final String COMPONENTS_DELIM = "\u003b"; public static final String ELEMENT_DELIM = "\u002c"; public static final String DATA_FIELD_DELIM = "\u007c"; public static final String KEY_VALUE_DELIM = "\u003d"; public static final String LEVELIN = "\u007b"; public static final String LEVELOUT = "\u007d"; public static final String EMPTY = "null"; public static final String EXT_FUNCTION = "extfunct"; //public static final String CP_ROOT_THREAD_SEPARATOR = "/";//File.separator; public static final String CP_ROOT_THREAD_ID = "_t0"; public static final String CP_CHILD_THREAD = "_t"; public static final String PARFOR_CDATA_BEGIN = "<![CDATA["; public static final String PARFOR_CDATA_END = " ]]>"; public static final String PARFOR_PROG_BEGIN = " PROG" + LEVELIN; public static final String PARFOR_PROG_END = LEVELOUT; public static final String PARFORBODY_BEGIN = PARFOR_CDATA_BEGIN+"PARFORBODY" + LEVELIN; public static final String PARFORBODY_END = LEVELOUT+PARFOR_CDATA_END; public static final String PARFOR_VARS_BEGIN = "VARS: "; public static final String PARFOR_VARS_END = ""; public static final String PARFOR_PBS_BEGIN = " PBS" + LEVELIN; public static final String PARFOR_PBS_END = LEVELOUT; public static final String PARFOR_INST_BEGIN = " INST: "; public static final String PARFOR_INST_END = ""; public static final String PARFOR_EC_BEGIN = " EC: "; public static final String PARFOR_EC_END = ""; public static final String PARFOR_PB_BEGIN = " PB" + LEVELIN; public static final String PARFOR_PB_END = LEVELOUT; public static final String PARFOR_PB_WHILE = " WHILE" + LEVELIN; public static final String PARFOR_PB_FOR = " FOR" + LEVELIN; public static final String PARFOR_PB_PARFOR = " PARFOR" + LEVELIN; public static final String PARFOR_PB_IF = " IF" + LEVELIN; public static final String PARFOR_PB_FC = " FC" + LEVELIN; public static final String PARFOR_PB_EFC = " EFC" + LEVELIN; //exception msgs public static final String NOT_SUPPORTED_EXTERNALFUNCTION_PB = "Not supported: ExternalFunctionProgramBlock contains MR instructions. " + "(ExternalFunctionPRogramBlockCP can be used)"; public static final String NOT_SUPPORTED_MR_INSTRUCTION = "Not supported: Instructions of type other than CP instructions"; public static final String NOT_SUPPORTED_MR_PARFOR = "Not supported: Nested ParFOR REMOTE_MR due to possible deadlocks." + "(LOCAL can be used for innner ParFOR)"; public static final String NOT_SUPPORTED_PB = "Not supported: type of program block"; public static final String NOT_SUPPORTED_EXECUTION_CONTEXT = "Parsing of external system execution context not supported yet."; // CREATION of DEEP COPIES /** * Creates a deep copy of the given execution context. * For rt_platform=Hadoop, execution context has a symbol table. */ public static ExecutionContext createDeepCopyExecutionContext(ExecutionContext ec, ProgramBlock pb) { ExecutionContext copy_ec = new ExecutionContext(); // Create an empty symbol table according to the nested program structure given by <code>pb</code> SymbolTable copy_symb = pb.createSymbolTable(); // Copy the variables corresponding to top-level program block copy_symb.get_variableMap().putAll(ec.getSymbolTable().get_variableMap()); copy_ec.setSymbolTable(copy_symb); return copy_ec; } /** * This recursively creates a deep copy of program blocks and transparently replaces filenames according to the * specified parallel worker in order to avoid conflicts between parworkers. This happens recursively in order * to support arbitrary control-flow constructs within a parfor. * * @param childBlocks * @param pid * @param plain full deep copy without id replacement * * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ArrayList<ProgramBlock> rcreateDeepCopyProgramBlocks(ArrayList<ProgramBlock> childBlocks, long pid, int IDPrefix, HashSet<String> fnStack, boolean plain) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<ProgramBlock> tmp = new ArrayList<ProgramBlock>(); for( ProgramBlock pb : childBlocks ) { Program prog = pb.getProgram(); ProgramBlock tmpPB = null; if( pb instanceof WhileProgramBlock || pb instanceof ForProgramBlock || pb instanceof ParForProgramBlock || pb instanceof IfProgramBlock ) { if( pb instanceof WhileProgramBlock ) { tmpPB = createDeepCopyWhileProgramBlock((WhileProgramBlock) pb, pid, IDPrefix, prog, fnStack, plain); } else if ( pb instanceof ForProgramBlock && !(pb instanceof ParForProgramBlock) ) { tmpPB = createDeepCopyForProgramBlock((ForProgramBlock) pb, pid, IDPrefix, prog, fnStack, plain ); } else if ( pb instanceof ParForProgramBlock ) { ParForProgramBlock pfpb = (ParForProgramBlock) pb; if( ParForProgramBlock.ALLOW_NESTED_PARALLELISM ) tmpPB = createDeepCopyParForProgramBlock(pfpb, pid, IDPrefix, prog, fnStack, plain); else tmpPB = createDeepCopyForProgramBlock((ForProgramBlock) pb, pid, IDPrefix, prog, fnStack, plain); } else if ( pb instanceof IfProgramBlock ) { tmpPB = createDeepCopyIfProgramBlock((IfProgramBlock) pb, pid, IDPrefix, prog, fnStack, plain); } } else { tmpPB = new ProgramBlock(prog); // general case use for most PBs //for recompile in the master node JVM tmpPB.setStatementBlock(createStatementBlockCopy(pb.getStatementBlock(), pid, plain)); //tmpPB.setStatementBlock(pb.getStatementBlock()); tmpPB.setThreadID(pid); } //copy instructions tmpPB.setInstructions( createDeepCopyInstructionSet(pb.getInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); //copy symbol table //tmpPB.setVariables( pb.getVariables() ); //implicit cloning tmp.add(tmpPB); } return tmp; } /** * * @param wpb * @param pid * @param IDPrefix * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static WhileProgramBlock createDeepCopyWhileProgramBlock(WhileProgramBlock wpb, long pid, int IDPrefix, Program prog, HashSet<String> fnStack, boolean plain) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<Instruction> predinst = createDeepCopyInstructionSet(wpb.getPredicate(), pid, IDPrefix, prog, fnStack, plain, true); WhileProgramBlock tmpPB = new WhileProgramBlock(prog, predinst); tmpPB.setStatementBlock( wpb.getStatementBlock() ); tmpPB.setThreadID(pid); tmpPB.setExitInstructions2( createDeepCopyInstructionSet(wpb.getExitInstructions(), pid, IDPrefix, prog, fnStack, plain, true)); tmpPB.setChildBlocks(rcreateDeepCopyProgramBlocks(wpb.getChildBlocks(), pid, IDPrefix, fnStack, plain)); return tmpPB; } /** * * @param ipb * @param pid * @param IDPrefix * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static IfProgramBlock createDeepCopyIfProgramBlock(IfProgramBlock ipb, long pid, int IDPrefix, Program prog, HashSet<String> fnStack, boolean plain) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<Instruction> predinst = createDeepCopyInstructionSet(ipb.getPredicate(), pid, IDPrefix, prog, fnStack, plain, true); IfProgramBlock tmpPB = new IfProgramBlock(prog, predinst); tmpPB.setStatementBlock( ipb.getStatementBlock() ); tmpPB.setThreadID(pid); tmpPB.setExitInstructions2( createDeepCopyInstructionSet(ipb.getExitInstructions(), pid, IDPrefix, prog, fnStack, plain, true)); tmpPB.setChildBlocksIfBody(rcreateDeepCopyProgramBlocks(ipb.getChildBlocksIfBody(), pid, IDPrefix, fnStack, plain)); tmpPB.setChildBlocksElseBody(rcreateDeepCopyProgramBlocks(ipb.getChildBlocksElseBody(), pid, IDPrefix, fnStack, plain)); return tmpPB; } /** * * @param fpb * @param pid * @param IDPrefix * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ForProgramBlock createDeepCopyForProgramBlock(ForProgramBlock fpb, long pid, int IDPrefix, Program prog, HashSet<String> fnStack, boolean plain) throws DMLRuntimeException, DMLUnsupportedOperationException { ForProgramBlock tmpPB = new ForProgramBlock(prog,fpb.getIterablePredicateVars()); tmpPB.setStatementBlock(fpb.getStatementBlock()); tmpPB.setThreadID(pid); tmpPB.setFromInstructions( createDeepCopyInstructionSet(fpb.getFromInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setToInstructions( createDeepCopyInstructionSet(fpb.getToInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setIncrementInstructions( createDeepCopyInstructionSet(fpb.getIncrementInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setExitInstructions( createDeepCopyInstructionSet(fpb.getExitInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setChildBlocks( rcreateDeepCopyProgramBlocks(fpb.getChildBlocks(), pid, IDPrefix, fnStack, plain) ); return tmpPB; } /** * * @param fpb * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ForProgramBlock createShallowCopyForProgramBlock(ForProgramBlock fpb, Program prog ) throws DMLRuntimeException, DMLUnsupportedOperationException { ForProgramBlock tmpPB = new ForProgramBlock(prog,fpb.getIterablePredicateVars()); tmpPB.setFromInstructions( fpb.getFromInstructions() ); tmpPB.setToInstructions( fpb.getToInstructions() ); tmpPB.setIncrementInstructions( fpb.getIncrementInstructions() ); tmpPB.setExitInstructions( fpb.getExitInstructions() ); tmpPB.setChildBlocks( fpb.getChildBlocks() ); return tmpPB; } /** * * @param pfpb * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ForProgramBlock createShallowCopyParForProgramBlock(ParForProgramBlock pfpb, Program prog ) throws DMLRuntimeException, DMLUnsupportedOperationException { ParForProgramBlock tmpPB = new ParForProgramBlock(prog,pfpb.getIterablePredicateVars(),pfpb.getParForParams()); tmpPB.setStatementBlock( pfpb.getStatementBlock() ); tmpPB.setResultVariables( pfpb.getResultVariables() ); tmpPB.setFromInstructions( pfpb.getFromInstructions() ); tmpPB.setToInstructions( pfpb.getToInstructions() ); tmpPB.setIncrementInstructions( pfpb.getIncrementInstructions() ); tmpPB.setExitInstructions( pfpb.getExitInstructions() ); tmpPB.setChildBlocks( pfpb.getChildBlocks() ); return tmpPB; } /** * * @param pfpb * @param pid * @param IDPrefix * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ParForProgramBlock createDeepCopyParForProgramBlock(ParForProgramBlock pfpb, long pid, int IDPrefix, Program prog, HashSet<String> fnStack, boolean plain) throws DMLRuntimeException, DMLUnsupportedOperationException { ParForProgramBlock tmpPB = null; if( IDPrefix == -1 ) //still on master node tmpPB = new ParForProgramBlock(prog,pfpb.getIterablePredicateVars(),pfpb.getParForParams()); else //child of remote ParWorker at any level tmpPB = new ParForProgramBlock(IDPrefix, prog, pfpb.getIterablePredicateVars(),pfpb.getParForParams()); tmpPB.setStatementBlock( pfpb.getStatementBlock() ); tmpPB.setThreadID(pid); tmpPB.disableOptimization(); //already done in top-level parfor tmpPB.setResultVariables( pfpb.getResultVariables() ); tmpPB.setFromInstructions( createDeepCopyInstructionSet(pfpb.getFromInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setToInstructions( createDeepCopyInstructionSet(pfpb.getToInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setIncrementInstructions( createDeepCopyInstructionSet(pfpb.getIncrementInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); tmpPB.setExitInstructions( createDeepCopyInstructionSet(pfpb.getExitInstructions(), pid, IDPrefix, prog, fnStack, plain, true) ); //NOTE: Normally, no recursive copy because (1) copied on each execution in this PB anyway //and (2) leave placeholders as they are. However, if plain, an explicit deep copy is requested. if( plain ) tmpPB.setChildBlocks( rcreateDeepCopyProgramBlocks(pfpb.getChildBlocks(), pid, IDPrefix, fnStack, plain) ); else tmpPB.setChildBlocks( pfpb.getChildBlocks() ); return tmpPB; } /** * This creates a deep copy of a function program block. The central reference to singletons of function program blocks * poses the need for explicit copies in order to prevent conflicting writes of temporary variables (see ExternalFunctionProgramBlock. * * @param oldName * @param pid * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static void createDeepCopyFunctionProgramBlock(String namespace, String oldName, long pid, int IDPrefix, Program prog, HashSet<String> fnStack, boolean plain) throws DMLRuntimeException, DMLUnsupportedOperationException { FunctionProgramBlock fpb = prog.getFunctionProgramBlock(namespace, oldName); String fnameNew = (plain)? oldName :(oldName+CP_CHILD_THREAD+pid); String fnameNewKey = namespace+Program.KEY_DELIM+fnameNew; if( prog.getFunctionProgramBlocks().containsKey(fnameNewKey) ) return; //prevent redundant deep copy if already existent if( fpb == null ) { throw new DMLRuntimeException("Unable to create a deep copy of the FunctionProgramBlock "+oldName+" because it does not exist."); } //create deep copy FunctionProgramBlock copy = null; Vector<DataIdentifier> tmp1 = new Vector<DataIdentifier>(); Vector<DataIdentifier> tmp2 = new Vector<DataIdentifier>(); if( fpb.getInputParams()!= null ) tmp1.addAll(fpb.getInputParams()); if( fpb.getOutputParams()!= null ) tmp2.addAll(fpb.getOutputParams()); if( fpb instanceof ExternalFunctionProgramBlockCP ) { ExternalFunctionProgramBlockCP efpb = (ExternalFunctionProgramBlockCP) fpb; HashMap<String,String> tmp3 = efpb.getOtherParams(); if( IDPrefix!=-1 ) copy = new ExternalFunctionProgramBlockCP(prog,tmp1,tmp2,tmp3,efpb.getBaseDir().replaceAll(CP_CHILD_THREAD+IDPrefix, CP_CHILD_THREAD+pid)); else copy = new ExternalFunctionProgramBlockCP(prog,tmp1,tmp2,tmp3,efpb.getBaseDir().replaceAll(CP_ROOT_THREAD_ID, CP_CHILD_THREAD+pid)); } else if( fpb instanceof ExternalFunctionProgramBlock ) { ExternalFunctionProgramBlock efpb = (ExternalFunctionProgramBlock) fpb; HashMap<String,String> tmp3 = efpb.getOtherParams(); if( IDPrefix!=-1 ) copy = new ExternalFunctionProgramBlock(prog,tmp1,tmp2,tmp3,efpb.getBaseDir().replaceAll(CP_CHILD_THREAD+IDPrefix, CP_CHILD_THREAD+pid)); else copy = new ExternalFunctionProgramBlock(prog,tmp1,tmp2,tmp3,efpb.getBaseDir().replaceAll(CP_ROOT_THREAD_ID, CP_CHILD_THREAD+pid)); } else { if( !fnStack.contains(fnameNewKey) ) { fnStack.add(fnameNewKey); copy = new FunctionProgramBlock(prog, tmp1, tmp2); copy.setChildBlocks( rcreateDeepCopyProgramBlocks(fpb.getChildBlocks(), pid, IDPrefix, fnStack, plain) ); fnStack.remove(fnameNewKey); } else //stop deep copy for recursive function calls copy = fpb; } //copy.setVariables( (LocalVariableMap) fpb.getVariables() ); //implicit cloning //note: instructions not used by function program block //put prog.addFunctionProgramBlock(namespace, fnameNew, copy); } /** * * @param fpb * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static FunctionProgramBlock createDeepCopyFunctionProgramBlock(FunctionProgramBlock fpb, HashSet<String> fnStack) throws DMLRuntimeException, DMLUnsupportedOperationException { if( fpb == null ) throw new DMLRuntimeException("Unable to create a deep copy of a non-existing FunctionProgramBlock."); //create deep copy FunctionProgramBlock copy = null; Vector<DataIdentifier> tmp1 = new Vector<DataIdentifier>(); Vector<DataIdentifier> tmp2 = new Vector<DataIdentifier>(); if( fpb.getInputParams()!= null ) tmp1.addAll(fpb.getInputParams()); if( fpb.getOutputParams()!= null ) tmp2.addAll(fpb.getOutputParams()); copy = new FunctionProgramBlock(fpb.getProgram(), tmp1, tmp2); copy.setChildBlocks( rcreateDeepCopyProgramBlocks(fpb.getChildBlocks(), 0, -1, fnStack, true) ); //copy.setVariables( (LocalVariableMap) fpb.getVariables() ); //implicit cloning //note: instructions not used by function program block return copy; } /** * Creates a deep copy of an array of instructions and replaces the placeholders of parworker * IDs with the concrete IDs of this parfor instance. This is a helper method uses for generating * deep copies of program blocks. * * @param instSet * @param pid * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ @SuppressWarnings("unchecked") public static ArrayList<Instruction> createDeepCopyInstructionSet(ArrayList<Instruction> instSet, long pid, int IDPrefix, Program prog, HashSet<String> fnStack, boolean plain, boolean cpFunctions) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<Instruction> tmp = (ArrayList<Instruction>) instSet.clone(); for( int i=0; i<instSet.size(); i++ ) { Instruction inst1 = instSet.get(i); if( inst1 instanceof FunctionCallCPInstruction && cpFunctions ) { FunctionCallCPInstruction finst1 = (FunctionCallCPInstruction) inst1; createDeepCopyFunctionProgramBlock( finst1.getNamespace(), finst1.getFunctionName(), pid, IDPrefix, prog, fnStack, plain ); } Instruction inst2 = cloneInstruction( inst1, pid, plain, cpFunctions ); tmp.set(i, inst2); } return tmp; } /** * * @param pid * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ @SuppressWarnings("unchecked") public static Instruction cloneInstruction( Instruction oInst, long pid, boolean plain, boolean cpFunctions ) throws DMLUnsupportedOperationException, DMLRuntimeException { Instruction inst = null; String tmpString = oInst.toString().replaceAll(ProgramConverter.CP_ROOT_THREAD_ID, ProgramConverter.CP_CHILD_THREAD+pid); Class<Instruction> cla = null; Method parse = null; try { cla = (Class) oInst.getClass(); parse = cla.getMethod("parseInstruction", String.class); } catch(Exception ex){} try { if( parse != null ) { if( oInst instanceof FunctionCallCPInstruction && cpFunctions ) { FunctionCallCPInstruction tmp = (FunctionCallCPInstruction) oInst; if( !plain ) tmpString = tmp.toString().replaceAll(tmp.getFunctionName(), tmp.getFunctionName() + CP_CHILD_THREAD+pid); //otherwise: preserve functionname } inst = (Instruction) parse.invoke(null, tmpString); } else if( oInst instanceof CPInstruction ) { CPInstruction tmp = (CPInstruction) oInst; inst = CPInstructionParser.parseSingleInstruction(tmp.getCPInstructionType(), tmpString); } else if( oInst instanceof MRInstruction ) { MRInstruction tmp = (MRInstruction) oInst; inst = MRInstructionParser.parseSingleInstruction(tmp.getMRInstructionType(), tmpString); } else if( oInst instanceof MRJobInstruction ) { MRJobInstruction tmp = (MRJobInstruction)oInst; inst = new MRJobInstruction(tmp, ProgramConverter.CP_ROOT_THREAD_ID, ProgramConverter.CP_CHILD_THREAD+pid); /*MRJobInstruction tmpNew = new MRJobInstruction(tmp.getJobType()); Field[] fields = cla.getDeclaredFields(); for( Field f : fields ) { f.setAccessible(true); if(!Modifier.isStatic(f.getModifiers())) f.set(tmpNew, f.get(tmp)); } String[] in = tmp.getIv_inputs().clone(); String[] out = tmp.getIv_outputs().clone(); String rand = tmp.getIv_randInstructions(); if(in!=null) for( int j=0;j<in.length; j++) if( in[j]!=null ) in[j]=in[j].replaceAll(ProgramConverter.CP_ROOT_THREAD_ID, ProgramConverter.CP_CHILD_THREAD+pid); if(out!=null) for( int j=0;j<out.length; j++) if( out[j]!=null ) out[j]=out[j].replaceAll(ProgramConverter.CP_ROOT_THREAD_ID, ProgramConverter.CP_CHILD_THREAD+pid); rand = rand.replaceAll(ProgramConverter.CP_ROOT_THREAD_ID, ProgramConverter.CP_CHILD_THREAD+pid); tmpNew.setIv_inputs(in); tmpNew.setIv_outputs(out); tmpNew.setRandInstructions(rand); inst = tmpNew;*/ } else throw new DMLUnsupportedOperationException("Unable to clone instruction of type "+cla.toString()); } catch(Exception ex) { throw new DMLRuntimeException(ex); } return inst; } /** * * @param sb * @return * @throws DMLRuntimeException */ public static StatementBlock createStatementBlockCopy( StatementBlock sb, long pid, boolean plain ) throws DMLRuntimeException { StatementBlock ret = null; try { if( OptimizerUtils.ALLOW_PARALLEL_DYN_RECOMPILATION && DMLScript.rtplatform == RUNTIME_PLATFORM.HYBRID && sb != null && Recompiler.requiresRecompilation( sb.get_hops() ) ) { ret = new StatementBlock(); ArrayList<Hops> hops = Recompiler.deepCopyHopsDag( sb.get_hops() ); if( !plain ) Recompiler.updateFunctionNames( hops, pid ); ret.set_hops( hops ); } else { ret = sb; } } catch( Exception ex ) { throw new DMLRuntimeException( ex ); } return ret; } // SERIALIZATION /** * @param body * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static String serializeParForBody( ParForBody body ) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<ProgramBlock> pbs = body.getChildBlocks(); ArrayList<String> rVnames = body.getResultVarNames(); ExecutionContext ec = body.getEc(); if( pbs.size()==0 ) return PARFORBODY_BEGIN + PARFORBODY_END; Program prog = pbs.get( 0 ).getProgram(); StringBuilder sb = new StringBuilder(); sb.append( PARFORBODY_BEGIN ); sb.append( NEWLINE ); //handle DMLScript UUID (propagate original uuid for writing to scratch space) sb.append( DMLScript.getUUID() ); sb.append( COMPONENTS_DELIM ); sb.append( NEWLINE ); //handle DML config sb.append( ConfigurationManager.getConfig().serializeDMLConfig() ); sb.append( COMPONENTS_DELIM ); sb.append( NEWLINE ); //handle program sb.append( PARFOR_PROG_BEGIN ); sb.append( NEWLINE ); sb.append( serializeProgram(prog, pbs) ); sb.append( PARFOR_PROG_END ); sb.append( NEWLINE ); sb.append( COMPONENTS_DELIM ); sb.append( NEWLINE ); //handle result variable names sb.append( serializeStringArrayList( rVnames ) ); sb.append( COMPONENTS_DELIM ); //handle execution context //note: this includes also the symbol table (serialize only the top-level variable map, // (symbol tables for nested/child blocks are created at parse time, on the remote side) sb.append( PARFOR_EC_BEGIN ); sb.append( serializeExecutionContext(ec) ); sb.append( PARFOR_EC_END ); sb.append( NEWLINE ); sb.append( COMPONENTS_DELIM ); sb.append( NEWLINE ); //handle program blocks -- ONLY instructions, not variables. sb.append( PARFOR_PBS_BEGIN ); sb.append( NEWLINE ); sb.append( rSerializeProgramBlocks(pbs) ); sb.append( PARFOR_PBS_END ); sb.append( NEWLINE ); sb.append( PARFORBODY_END ); return sb.toString(); } /** * * @param prog * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static String serializeProgram( Program prog, ArrayList<ProgramBlock> pbs ) throws DMLRuntimeException, DMLUnsupportedOperationException { //note program contains variables, programblocks and function program blocks //but in order to avoid redundancy, we only serialize function program blocks HashMap<String, FunctionProgramBlock> fpb = prog.getFunctionProgramBlocks(); HashSet<String> cand = new HashSet<String>(); rFindSerializationCandidates(pbs, cand); return rSerializeFunctionProgramBlocks( fpb, cand ); } public static void rFindSerializationCandidates( ArrayList<ProgramBlock> pbs, HashSet<String> cand ) { for( ProgramBlock pb : pbs ) { if( pb instanceof WhileProgramBlock ) { WhileProgramBlock wpb = (WhileProgramBlock) pb; rFindSerializationCandidates(wpb.getChildBlocks(), cand); } else if ( pb instanceof ForProgramBlock || pb instanceof ParForProgramBlock ) { ForProgramBlock fpb = (ForProgramBlock) pb; rFindSerializationCandidates(fpb.getChildBlocks(), cand); } else if ( pb instanceof IfProgramBlock ) { IfProgramBlock ipb = (IfProgramBlock) pb; rFindSerializationCandidates(ipb.getChildBlocksIfBody(), cand); if( ipb.getChildBlocksElseBody() != null ) rFindSerializationCandidates(ipb.getChildBlocksElseBody(), cand); } else //all generic program blocks { for( Instruction inst : pb.getInstructions() ) if( inst instanceof FunctionCallCPInstruction ) { FunctionCallCPInstruction fci = (FunctionCallCPInstruction) inst; cand.add( fci.getNamespace() + Program.KEY_DELIM + fci.getFunctionName() ); } } } } /** * * @param vars * @return * @throws DMLRuntimeException */ public static String serializeVariables (LocalVariableMap vars) throws DMLRuntimeException { StringBuilder sb = new StringBuilder(); sb.append( PARFOR_VARS_BEGIN ); sb.append( vars.serialize() ); sb.append( PARFOR_VARS_END ); return sb.toString(); } /** * * @param key * @param dat * @return * @throws DMLRuntimeException */ public static String serializeDataObject(String key, Data dat) throws DMLRuntimeException { // SCHEMA: <name>|<datatype>|<valuetype>|value // (scalars are serialize by value, matrices by filename) StringBuilder sb = new StringBuilder(); //prepare data for serialization String name = key; DataType datatype = dat.getDataType(); ValueType valuetype = dat.getValueType(); String value = null; String[] matrixMetaData = null; switch( datatype ) { case SCALAR: ScalarObject so = (ScalarObject) dat; //name = so.getName(); value = so.getStringValue(); break; case MATRIX: MatrixObject mo = (MatrixObject) dat; MatrixFormatMetaData md = (MatrixFormatMetaData) dat.getMetaData(); MatrixCharacteristics mc = md.getMatrixCharacteristics(); value = mo.getFileName(); PDataPartitionFormat partFormat = (mo.getPartitionFormat()!=null) ? mo.getPartitionFormat() : PDataPartitionFormat.NONE; matrixMetaData = new String[8]; matrixMetaData[0] = String.valueOf( mc.get_rows() ); matrixMetaData[1] = String.valueOf( mc.get_cols() ); matrixMetaData[2] = String.valueOf( mc.get_rows_per_block() ); matrixMetaData[3] = String.valueOf( mc.get_cols_per_block() ); matrixMetaData[4] = String.valueOf( mc.getNonZeros() ); matrixMetaData[5] = InputInfo.inputInfoToString( md.getInputInfo() ); matrixMetaData[6] = OutputInfo.outputInfoToString( md.getOutputInfo() ); matrixMetaData[7] = String.valueOf( partFormat ); break; default: throw new DMLRuntimeException("Unable to serialize datatype "+datatype); } //serialize data sb.append(name); sb.append(DATA_FIELD_DELIM); sb.append(datatype); sb.append(DATA_FIELD_DELIM); sb.append(valuetype); sb.append(DATA_FIELD_DELIM); sb.append(value); if( matrixMetaData != null ) for( int i=0; i<matrixMetaData.length; i++ ) { sb.append(DATA_FIELD_DELIM); sb.append(matrixMetaData[i]); } return sb.toString(); } /** * * @param ec * @return * @throws DMLRuntimeException */ public static String serializeExecutionContext( ExecutionContext ec ) throws DMLRuntimeException { String ret = null; if( ec != null ) { SymbolTable symb = ec.getSymbolTable(); LocalVariableMap vars = symb.get_variableMap(); ret = serializeVariables( vars ); } else { ret = EMPTY; } return ret; } /** * * @param inst * @return * @throws DMLRuntimeException */ @SuppressWarnings("all") public static String serializeInstructions( ArrayList<Instruction> inst ) throws DMLRuntimeException { StringBuilder sb = new StringBuilder(); int count = 0; for( Instruction linst : inst ) { //check that only cp instruction are transmitted if( !( linst instanceof CPInstruction || linst instanceof ExternalFunctionInvocationInstruction ) ) { throw new DMLRuntimeException( NOT_SUPPORTED_MR_INSTRUCTION + " " +linst.getClass().getName() ); } if( count > 0 ) sb.append( ELEMENT_DELIM ); sb.append( checkAndReplaceLiterals( linst.toString() ) ); count++; } return sb.toString(); } /** * Replacement of internal delimiters occurring in literals of instructions * in order to ensure robustness of serialization and parsing. * (e.g. print( "a,b" ) would break the parsing of instruction that internally * are separated with a "," ) * * @param instStr * @return */ public static String checkAndReplaceLiterals( String instStr ) { String tmp = instStr; //1) check own delimiters if( tmp.contains(COMPONENTS_DELIM) ) tmp = tmp.replaceAll(COMPONENTS_DELIM, "."); if( tmp.contains(ELEMENT_DELIM) ) tmp = tmp.replaceAll(ELEMENT_DELIM, "."); if( tmp.contains(LEVELIN) ) tmp = tmp.replaceAll(LEVELIN, "."); if( tmp.contains(LEVELOUT) ) tmp = tmp.replaceAll(LEVELOUT, "."); //NOTE: DATA_FIELD_DELIM and KEY_VALUE_DELIM not required //because those literals cannot occur in critical places. //2) check end tag of CDATA if( tmp.contains(PARFOR_CDATA_END) ) tmp = tmp.replaceAll(PARFOR_CDATA_END, "."); return tmp; } /** * * @param vars * @return */ public static String serializeStringHashMap( HashMap<String,String> vars) { StringBuilder sb = new StringBuilder(); int count=0; for( Entry<String,String> e : vars.entrySet() ) { if(count>0) sb.append( ELEMENT_DELIM ); sb.append( e.getKey() ); sb.append( KEY_VALUE_DELIM ); sb.append( e.getValue() ); count++; } return sb.toString(); } /** * * @param vars * @return */ public static String serializeStringHashSet( HashSet<String> set) { StringBuilder sb = new StringBuilder(); int count=0; for( String s : set ) { if(count>0) sb.append( ELEMENT_DELIM ); sb.append( s ); count++; } return sb.toString(); } /** * * @param vars * @return */ public static String serializeStringArrayList( ArrayList<String> vars) { StringBuilder sb = new StringBuilder(); int count=0; for( String s : vars ) { if(count>0) sb.append( ELEMENT_DELIM ); sb.append( s ); count++; } return sb.toString(); } /** * * @param vars * @return */ public static String serializeStringArray( String[] vars) { StringBuilder sb = new StringBuilder(); int count=0; for( String s : vars ) { if(count>0) sb.append( ELEMENT_DELIM ); if( s != null ) sb.append( s ); else sb.append( "null" ); count++; } return sb.toString(); } /** * * @param var * @return */ public static String serializeDataIdentifiers( ArrayList<DataIdentifier> var) { StringBuilder sb = new StringBuilder(); int count=0; for( DataIdentifier dat : var ) { if(count>0) sb.append( ELEMENT_DELIM ); sb.append( serializeDataIdentifier(dat) ); count++; } return sb.toString(); } /** * * @param dat * @return */ public static String serializeDataIdentifier( DataIdentifier dat ) { // SCHEMA: <name>|<datatype>|<valuetype> StringBuilder sb = new StringBuilder(); sb.append(dat.getName()); sb.append(DATA_FIELD_DELIM); sb.append(dat.getDataType()); sb.append(DATA_FIELD_DELIM); sb.append(dat.getValueType()); return sb.toString(); } /** * * @param pbs * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static String rSerializeFunctionProgramBlocks(HashMap<String,FunctionProgramBlock> pbs, HashSet<String> cand) throws DMLRuntimeException, DMLUnsupportedOperationException { StringBuilder sb = new StringBuilder(); int count = 0; for( Entry<String,FunctionProgramBlock> pb : pbs.entrySet() ) { if( !cand.contains(pb.getKey()) ) //skip function not included in the parfor body continue; if( count>0 ) { sb.append( ELEMENT_DELIM ); sb.append( NEWLINE ); } sb.append( pb.getKey() ); sb.append( KEY_VALUE_DELIM ); sb.append( rSerializeProgramBlock( pb.getValue() ) ); count++; } sb.append(NEWLINE); return sb.toString(); } /** * * @param pbs * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static String rSerializeProgramBlocks(ArrayList<ProgramBlock> pbs) throws DMLRuntimeException, DMLUnsupportedOperationException { StringBuilder sb = new StringBuilder(); int count = 0; for( ProgramBlock pb : pbs ) { if( count>0 ) { sb.append( ELEMENT_DELIM ); sb.append(NEWLINE); } sb.append( rSerializeProgramBlock(pb) ); count++; } return sb.toString(); } /** * * @param pb * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static String rSerializeProgramBlock( ProgramBlock pb) throws DMLRuntimeException, DMLUnsupportedOperationException { StringBuilder sb = new StringBuilder(); //handle header if( pb instanceof WhileProgramBlock ) sb.append( PARFOR_PB_WHILE ); else if ( pb instanceof ForProgramBlock && !(pb instanceof ParForProgramBlock) ) sb.append( PARFOR_PB_FOR ); else if ( pb instanceof ParForProgramBlock ) sb.append( PARFOR_PB_PARFOR ); else if ( pb instanceof IfProgramBlock ) sb.append( PARFOR_PB_IF ); else if ( pb instanceof FunctionProgramBlock && !(pb instanceof ExternalFunctionProgramBlock) ) sb.append( PARFOR_PB_FC ); else if ( pb instanceof ExternalFunctionProgramBlock ) sb.append( PARFOR_PB_EFC ); else //all generic program blocks sb.append( PARFOR_PB_BEGIN ); //handle variables (not required only on top level) /*sb.append( PARFOR_VARS_BEGIN ); sb.append( serializeVariables( ) ); sb.append( PARFOR_VARS_END ); sb.append( COMPONENTS_DELIM ); */ //handle body if( pb instanceof WhileProgramBlock ) { WhileProgramBlock wpb = (WhileProgramBlock) pb; sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( wpb.getPredicate() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( wpb.getExitInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( wpb.getChildBlocks()) ); sb.append( PARFOR_PBS_END ); } else if ( pb instanceof ForProgramBlock && !(pb instanceof ParForProgramBlock ) ) { ForProgramBlock fpb = (ForProgramBlock) pb; sb.append( serializeStringArray(fpb.getIterablePredicateVars()) ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( fpb.getFromInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( fpb.getToInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( fpb.getIncrementInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( fpb.getExitInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( fpb.getChildBlocks()) ); sb.append( PARFOR_PBS_END ); } else if ( pb instanceof ParForProgramBlock ) { ParForProgramBlock pfpb = (ParForProgramBlock) pb; //check for nested remote ParFOR if( PExecMode.valueOf( pfpb.getParForParams().get( ParForStatementBlock.EXEC_MODE )) == PExecMode.REMOTE_MR ) throw new DMLUnsupportedOperationException( NOT_SUPPORTED_MR_PARFOR ); sb.append( serializeStringArray(pfpb.getIterablePredicateVars()) ); sb.append( COMPONENTS_DELIM ); sb.append( serializeStringArrayList( pfpb.getResultVariables()) ); sb.append( COMPONENTS_DELIM ); sb.append( serializeStringHashMap( pfpb.getParForParams()) ); //parameters of nested parfor sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( pfpb.getFromInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( pfpb.getToInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( pfpb.getIncrementInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( pfpb.getExitInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( pfpb.getChildBlocks() ) ); sb.append( PARFOR_PBS_END ); } else if ( pb instanceof IfProgramBlock ) { IfProgramBlock ipb = (IfProgramBlock) pb; sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( ipb.getPredicate() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( ipb.getExitInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( ipb.getChildBlocksIfBody() ) ); sb.append( PARFOR_PBS_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( ipb.getChildBlocksElseBody() ) ); sb.append( PARFOR_PBS_END ); } else if( pb instanceof FunctionProgramBlock && !(pb instanceof ExternalFunctionProgramBlock) ) { FunctionProgramBlock fpb = (FunctionProgramBlock) pb; sb.append( serializeDataIdentifiers( fpb.getInputParams() ) ); sb.append( COMPONENTS_DELIM ); sb.append( serializeDataIdentifiers( fpb.getOutputParams() ) ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( fpb.getInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( fpb.getChildBlocks() ) ); sb.append( PARFOR_PBS_END ); sb.append( COMPONENTS_DELIM ); } else if( pb instanceof ExternalFunctionProgramBlock ) { if( !(pb instanceof ExternalFunctionProgramBlockCP) ) { throw new DMLRuntimeException( NOT_SUPPORTED_EXTERNALFUNCTION_PB ); } ExternalFunctionProgramBlockCP fpb = (ExternalFunctionProgramBlockCP) pb; sb.append( serializeDataIdentifiers( fpb.getInputParams() ) ); sb.append( COMPONENTS_DELIM ); sb.append( serializeDataIdentifiers( fpb.getOutputParams() ) ); sb.append( COMPONENTS_DELIM ); sb.append( serializeStringHashMap( fpb.getOtherParams() ) ); sb.append( COMPONENTS_DELIM ); sb.append( fpb.getBaseDir() ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_INST_BEGIN ); //create on construction anyway //sb.append( serializeInstructions( fpb.getInstructions() ) ); sb.append( PARFOR_INST_END ); sb.append( COMPONENTS_DELIM ); sb.append( PARFOR_PBS_BEGIN ); sb.append( rSerializeProgramBlocks( fpb.getChildBlocks() ) ); sb.append( PARFOR_PBS_END ); } else //all generic program blocks { sb.append( PARFOR_INST_BEGIN ); sb.append( serializeInstructions( pb.getInstructions() ) ); sb.append( PARFOR_INST_END ); } //handle end sb.append( PARFOR_PB_END ); return sb.toString(); } // PARSING /** * * @param in * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ParForBody parseParForBody( String in, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { ParForBody body = new ParForBody(); //header elimination String tmpin = in.replaceAll(NEWLINE, ""); //normalization tmpin = tmpin.substring(PARFORBODY_BEGIN.length(),tmpin.length()-PARFORBODY_END.length()); //remove start/end HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(tmpin, COMPONENTS_DELIM); //handle DMLScript UUID (NOTE: set directly in DMLScript) //(master UUID is used for all nodes (in order to simply cleanup)) DMLScript.setUUID( st.nextToken() ); //handle DML config (NOTE: set directly in ConfigurationManager) String confStr = st.nextToken(); if( !InfrastructureAnalyzer.isLocalMode() ) { DMLConfig config = DMLConfig.parseDMLConfig(confStr); ConfigurationManager.setConfig(config); } //handle program String progStr = st.nextToken(); progStr = progStr.replaceAll(CP_ROOT_THREAD_ID, CP_CHILD_THREAD+id); //replace for all instruction Program prog = parseProgram( progStr, id ); //handle result variable names String rvarStr = st.nextToken(); ArrayList<String> rvars = parseStringArrayList(rvarStr); body.setResultVarNames(rvars); //handle execution context String ecStr = st.nextToken(); ExecutionContext ec = parseExecutionContext( ecStr ); //handle program blocks String spbs = st.nextToken(); spbs = spbs.replaceAll(CP_ROOT_THREAD_ID, CP_CHILD_THREAD+id); //replace for all instruction ArrayList<ProgramBlock> pbs = rParseProgramBlocks(spbs, prog, id); body.setChildBlocks( pbs ); //construct (empty) symbol tables for all the child blocks SymbolTable symb = ec.getSymbolTable(); for(int i=0; i < pbs.size(); i++) { symb.addChildTable(pbs.get(i).createSymbolTable()); } //attach symbol table to execution context ec.setSymbolTable(symb); body.setEc( ec ); return body; } /** * * @param in * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static Program parseProgram( String in, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PROG_BEGIN.length(),in.length()-PARFOR_PROG_END.length()).trim(); Program prog = new Program(); HashMap<String,FunctionProgramBlock> fc = parseFunctionProgramBlocks(lin, prog, id); for( Entry<String,FunctionProgramBlock> e : fc.entrySet() ) { String[] keypart = e.getKey().split( Program.KEY_DELIM ); String namespace = keypart[0]; String name = keypart[1]; prog.addFunctionProgramBlock(namespace, name, e.getValue()); } return prog; } /** * * @param in * @return * @throws DMLRuntimeException */ public static LocalVariableMap parseVariables(String in) throws DMLRuntimeException { String varStr = in.substring( PARFOR_VARS_BEGIN.length(),in.length()-PARFOR_VARS_END.length()).trim(); return LocalVariableMap.deserialize(varStr); } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static HashMap<String,FunctionProgramBlock> parseFunctionProgramBlocks( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { HashMap<String,FunctionProgramBlock> ret = new HashMap<String, FunctionProgramBlock>(); HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer( in, ELEMENT_DELIM ); while( st.hasMoreTokens() ) { String lvar = st.nextToken(); //with ID = CP_CHILD_THREAD+id for current use //put first copy into prog (for direct use) int index = lvar.indexOf( KEY_VALUE_DELIM ); String tmp1 = lvar.substring(0, index); // + CP_CHILD_THREAD+id; String tmp2 = lvar.substring(index + 1); ret.put(tmp1, (FunctionProgramBlock)rParseProgramBlock(tmp2, prog, id)); //put first copy into prog (for future deep copies) //index = lvar2.indexOf("="); //tmp1 = lvar2.substring(0, index); //tmp2 = lvar2.substring(index + 1); //ret.put(tmp1, (FunctionProgramBlock)rParseProgramBlock(tmp2, prog, id)); } return ret; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ArrayList<ProgramBlock> rParseProgramBlocks(String in, Program prog, int id) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<ProgramBlock> pbs = new ArrayList<ProgramBlock>(); String tmpdata = in.substring(PARFOR_PBS_BEGIN.length(),in.length()-PARFOR_PBS_END.length()); ; HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(tmpdata, ELEMENT_DELIM); while( st.hasMoreTokens() ) { String tmp = st.nextToken(); pbs.add( rParseProgramBlock( tmp, prog, id ) ); } return pbs; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ProgramBlock rParseProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { ProgramBlock pb = null; if( in.startsWith( PARFOR_PB_WHILE ) ) pb = rParseWhileProgramBlock( in, prog, id ); else if ( in.startsWith(PARFOR_PB_FOR ) ) pb = rParseForProgramBlock( in, prog, id ); else if ( in.startsWith(PARFOR_PB_PARFOR ) ) pb = rParseParForProgramBlock( in, prog, id ); else if ( in.startsWith(PARFOR_PB_IF ) ) pb = rParseIfProgramBlock( in, prog, id ); else if ( in.startsWith(PARFOR_PB_FC ) ) pb = rParseFunctionProgramBlock( in, prog, id ); else if ( in.startsWith(PARFOR_PB_EFC ) ) pb = rParseExternalFunctionProgramBlock( in, prog, id ); else if ( in.startsWith(PARFOR_PB_BEGIN ) ) pb = rParseGenericProgramBlock( in, prog, id ); else throw new DMLUnsupportedOperationException( NOT_SUPPORTED_PB+" "+in ); return pb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static WhileProgramBlock rParseWhileProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_WHILE.length(),in.length()-PARFOR_PB_END.length()); HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(lin, COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); //predicate instructions ArrayList<Instruction> inst = parseInstructions(st.nextToken()); //exit instructions ArrayList<Instruction> exit = parseInstructions(st.nextToken()); //program blocks ArrayList<ProgramBlock> pbs = rParseProgramBlocks(st.nextToken(), prog, id); WhileProgramBlock wpb = new WhileProgramBlock(prog,inst); wpb.setExitInstructions2(exit); wpb.setChildBlocks(pbs); //wpb.setVariables(vars); return wpb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ForProgramBlock rParseForProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_FOR.length(),in.length()-PARFOR_PB_END.length()); HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(lin, COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); //inputs String[] iterPredVars = parseStringArray(st.nextToken()); //instructions ArrayList<Instruction> from = parseInstructions(st.nextToken()); ArrayList<Instruction> to = parseInstructions(st.nextToken()); ArrayList<Instruction> incr = parseInstructions(st.nextToken()); //exit instructions ArrayList<Instruction> exit = parseInstructions(st.nextToken()); //program blocks ArrayList<ProgramBlock> pbs = rParseProgramBlocks(st.nextToken(), prog, id); ForProgramBlock fpb = new ForProgramBlock(prog, iterPredVars); fpb.setFromInstructions(from); fpb.setToInstructions(to); fpb.setIncrementInstructions(incr); fpb.setExitInstructions(exit); fpb.setChildBlocks(pbs); //fpb.setVariables(vars); return fpb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ParForProgramBlock rParseParForProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_PARFOR.length(),in.length()-PARFOR_PB_END.length()); lin = lin.replaceAll(CP_CHILD_THREAD+id, CP_ROOT_THREAD_ID); // reset placeholder to preinit state (replaced by deep copies of nested parfor pbs) HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(lin, COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); //inputs String[] iterPredVars = parseStringArray(st.nextToken()); ArrayList<String> resultVars = parseStringArrayList(st.nextToken()); HashMap<String,String> params = parseStringHashMap(st.nextToken()); //instructions ArrayList<Instruction> from = parseInstructions(st.nextToken()); ArrayList<Instruction> to = parseInstructions(st.nextToken()); ArrayList<Instruction> incr = parseInstructions(st.nextToken()); //exit instructions ArrayList<Instruction> exit = parseInstructions(st.nextToken()); //program blocks ArrayList<ProgramBlock> pbs = rParseProgramBlocks(st.nextToken(), prog, id); ParForProgramBlock pfpb = new ParForProgramBlock(id, prog, iterPredVars, params); pfpb.disableOptimization(); //already done in top-level parfor pfpb.setResultVariables(resultVars); pfpb.setFromInstructions(from); pfpb.setToInstructions(to); pfpb.setIncrementInstructions(incr); pfpb.setExitInstructions(exit); pfpb.setChildBlocks(pbs); //pfpb.setVariables(vars); return pfpb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static IfProgramBlock rParseIfProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_IF.length(),in.length()-PARFOR_PB_END.length()); HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(lin, COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); //predicate instructions ArrayList<Instruction> inst = parseInstructions(st.nextToken()); //exit instructions ArrayList<Instruction> exit = parseInstructions(st.nextToken()); //program blocks: if and else ArrayList<ProgramBlock> pbs1 = rParseProgramBlocks(st.nextToken(), prog, id); ArrayList<ProgramBlock> pbs2 = rParseProgramBlocks(st.nextToken(), prog, id); IfProgramBlock ipb = new IfProgramBlock(prog,inst); ipb.setExitInstructions2(exit); ipb.setChildBlocksIfBody(pbs1); ipb.setChildBlocksElseBody(pbs2); //ipb.setVariables(vars); return ipb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static FunctionProgramBlock rParseFunctionProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_FC.length(),in.length()-PARFOR_PB_END.length()); HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(lin, COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); //inputs and outputs ArrayList<DataIdentifier> dat1 = parseDataIdentifiers(st.nextToken()); ArrayList<DataIdentifier> dat2 = parseDataIdentifiers(st.nextToken()); //instructions ArrayList<Instruction> inst = parseInstructions(st.nextToken()); //program blocks ArrayList<ProgramBlock> pbs = rParseProgramBlocks(st.nextToken(), prog, id); Vector<DataIdentifier> tmp1 = new Vector<DataIdentifier>(dat1); Vector<DataIdentifier> tmp2 = new Vector<DataIdentifier>(dat2); FunctionProgramBlock fpb = new FunctionProgramBlock(prog, tmp1, tmp2); fpb.setInstructions(inst); fpb.setChildBlocks(pbs); //fpb.setVariables(vars); return fpb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ExternalFunctionProgramBlock rParseExternalFunctionProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_EFC.length(),in.length()-PARFOR_PB_END.length()); HierarchyAwareStringTokenizer st = new HierarchyAwareStringTokenizer(lin, COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); //inputs, outputs and params ArrayList<DataIdentifier> dat1 = parseDataIdentifiers(st.nextToken()); ArrayList<DataIdentifier> dat2 = parseDataIdentifiers(st.nextToken()); HashMap<String,String> dat3 = parseStringHashMap(st.nextToken()); //basedir String basedir = st.nextToken(); //instructions @SuppressWarnings("unused") ArrayList<Instruction> inst = parseInstructions(st.nextToken()); //required for removing INST BEGIN, END //program blocks ArrayList<ProgramBlock> pbs = rParseProgramBlocks(st.nextToken(), prog, id); Vector<DataIdentifier> tmp1 = new Vector<DataIdentifier>(dat1); Vector<DataIdentifier> tmp2 = new Vector<DataIdentifier>(dat2); //only CP external functions, because no nested MR jobs for reblocks ExternalFunctionProgramBlockCP efpb = new ExternalFunctionProgramBlockCP(prog, tmp1, tmp2, dat3, basedir); //efpb.setInstructions(inst); efpb.setChildBlocks(pbs); //efpb.setVariables(vars); return efpb; } /** * * @param in * @param prog * @param id * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ProgramBlock rParseGenericProgramBlock( String in, Program prog, int id ) throws DMLRuntimeException, DMLUnsupportedOperationException { String lin = in.substring( PARFOR_PB_BEGIN.length(),in.length()-PARFOR_PB_END.length()); StringTokenizer st = new StringTokenizer(lin,COMPONENTS_DELIM); //LocalVariableMap vars = parseVariables(st.nextToken()); ArrayList<Instruction> inst = parseInstructions(st.nextToken()); ProgramBlock pb = new ProgramBlock(prog); pb.setInstructions(inst); //pb.setVariables(vars); return pb; } /** * * @param in * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ArrayList<Instruction> parseInstructions( String in ) throws DMLRuntimeException, DMLUnsupportedOperationException { ArrayList<Instruction> insts = new ArrayList<Instruction>(); String lin = in.substring( PARFOR_INST_BEGIN.length(),in.length()-PARFOR_INST_END.length()); StringTokenizer st = new StringTokenizer(lin, ELEMENT_DELIM); while(st.hasMoreTokens()) { //Note that at this point only CP instructions and External function instruction can occur String instStr = st.nextToken(); Instruction tmpinst = CPInstructionParser.parseSingleInstruction(instStr); insts.add( tmpinst ); } return insts; } /** * * @param in * @return */ public static HashMap<String,String> parseStringHashMap( String in ) { HashMap<String,String> vars = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(in,ELEMENT_DELIM); while( st.hasMoreTokens() ) { String lin = st.nextToken(); int index = lin.indexOf( KEY_VALUE_DELIM ); String tmp1 = lin.substring(0, index); String tmp2 = lin.substring(index + 1); vars.put(tmp1, tmp2); } return vars; } /** * * @param in * @return */ public static ArrayList<String> parseStringArrayList( String in ) { ArrayList<String> vars = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(in,ELEMENT_DELIM); while( st.hasMoreTokens() ) { String tmp = st.nextToken(); vars.add(tmp); } return vars; } /** * * @param in * @return */ public static String[] parseStringArray( String in ) { StringTokenizer st = new StringTokenizer(in, ELEMENT_DELIM); int len = st.countTokens(); String[] a = new String[len]; for( int i=0; i<len; i++ ) { String tmp = st.nextToken(); if( tmp.equals("null") ) a[i] = null; else a[i] = tmp; } return a; } /** * * @param in * @return */ public static ArrayList<DataIdentifier> parseDataIdentifiers( String in ) { ArrayList<DataIdentifier> vars = new ArrayList<DataIdentifier>(); StringTokenizer st = new StringTokenizer(in, ELEMENT_DELIM); while( st.hasMoreTokens() ) { String tmp = st.nextToken(); DataIdentifier dat = parseDataIdentifier( tmp ); vars.add(dat); } return vars; } /** * * @param in * @return */ public static DataIdentifier parseDataIdentifier( String in ) { StringTokenizer st = new StringTokenizer(in, DATA_FIELD_DELIM); String name = st.nextToken(); DataType dt = DataType.valueOf(st.nextToken()); ValueType vt = ValueType.valueOf(st.nextToken()); DataIdentifier dat = new DataIdentifier(name); dat.setDataType(dt); dat.setValueType(vt); return dat; } /** * NOTE: MRJobConfiguration cannot be used for the general case because program blocks and * related symbol tables can be hierarchically structured. * * @param in * @return * @throws DMLRuntimeException */ public static Object[] parseDataObject(String in) throws DMLRuntimeException { Object[] ret = new Object[2]; StringTokenizer st = new StringTokenizer(in, DATA_FIELD_DELIM ); String name = st.nextToken(); DataType datatype = DataType.valueOf( st.nextToken() ); ValueType valuetype = ValueType.valueOf( st.nextToken() ); String valString = st.nextToken(); Data dat = null; switch( datatype ) { case SCALAR: { switch ( valuetype ) { case INT: int value1 = Integer.parseInt(valString); dat = new IntObject(name,value1); break; case DOUBLE: double value2 = Double.parseDouble(valString); dat = new DoubleObject(name,value2); break; case BOOLEAN: boolean value3 = Boolean.parseBoolean(valString); dat = new BooleanObject(name,value3); break; case STRING: dat = new StringObject(name,valString); break; default: throw new DMLRuntimeException("Unable to parse valuetype "+valuetype); } break; } case MATRIX: { MatrixObject mo = new MatrixObject(valuetype,valString); long rows = Long.parseLong( st.nextToken() ); long cols = Long.parseLong( st.nextToken() ); int brows = Integer.parseInt( st.nextToken() ); int bcols = Integer.parseInt( st.nextToken() ); long nnz = Long.parseLong( st.nextToken() ); InputInfo iin = InputInfo.stringToInputInfo( st.nextToken() ); OutputInfo oin = OutputInfo.stringToOutputInfo( st.nextToken() ); PDataPartitionFormat partFormat = PDataPartitionFormat.valueOf( st.nextToken() ); MatrixCharacteristics mc = new MatrixCharacteristics(rows, cols, brows, bcols, nnz); MatrixFormatMetaData md = new MatrixFormatMetaData( mc, oin, iin ); mo.setMetaData( md ); mo.setVarName( name ); if( partFormat!=PDataPartitionFormat.NONE ) mo.setPartitioned( partFormat, -1 ); //TODO once we support BLOCKWISE_N we should support it here as well dat = mo; break; } default: throw new DMLRuntimeException("Unable to parse datatype "+datatype); } ret[0] = name; ret[1] = dat; return ret; } /** * * @param in * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static ExecutionContext parseExecutionContext(String in) throws DMLRuntimeException, DMLUnsupportedOperationException { ExecutionContext ec = null; String lin = in.substring(PARFOR_EC_BEGIN.length(),in.length()-PARFOR_EC_END.length()).trim(); if( !lin.equals( EMPTY ) ) { LocalVariableMap vars = parseVariables(lin); SymbolTable symb = new SymbolTable(); symb.set_variableMap( vars ); ec = new ExecutionContext( symb ); } return ec; } /** * Custom StringTokenizer for splitting strings of hierarchies. The basic idea is to * search for delim-Strings on the same hierarchy level, while delims of lower hierarchy * levels are skipped. * */ private static class HierarchyAwareStringTokenizer //extends StringTokenizer { private String _str = null; private String _del = null; private int _off = -1; public HierarchyAwareStringTokenizer( String in, String delim ) { //super(in); _str = in; _del = delim; _off = delim.length(); } public boolean hasMoreTokens() { return (_str.length() > 0); } public String nextToken() { int nextDelim = determineNextSameLevelIndexOf(_str, _del); String token = null; if(nextDelim < 0) { nextDelim = _str.length(); _off = 0; } token = _str.substring(0,nextDelim); _str = _str.substring( nextDelim + _off ); return token; } private int determineNextSameLevelIndexOf( String data, String pattern ) { String tmpdata = data; int index = 0; int count = 0; int off=0,i1,i2,i3,min; while(true) { i1 = tmpdata.indexOf(pattern); i2 = tmpdata.indexOf(LEVELIN); i3 = tmpdata.indexOf(LEVELOUT); if( i1 < 0 ) return i1; //no pattern found at all min = i1; //min >= 0 by definition if( i2 >= 0 ) min = Math.min(min, i2); if( i3 >= 0 ) min = Math.min(min, i3); //stack maintenance if( i1 == min && count == 0 ) return index+i1; else if( i2 == min ) { count++; off = LEVELIN.length(); } else if( i3 == min ) { count off = LEVELOUT.length(); } //prune investigated string index += min+off; tmpdata = tmpdata.substring(min+off); } } } }
package com.whippy.sponge.whipconomy.orchestrator; import java.util.ArrayList; import java.util.List; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.text.format.TextColors; import com.whippy.sponge.whipconomy.beans.Auction; import com.whippy.sponge.whipconomy.beans.Bid; import com.whippy.sponge.whipconomy.beans.StaticsHandler; import com.whippy.sponge.whipconomy.cache.ConfigurationLoader; import com.whippy.sponge.whipconomy.cache.EconomyCache; public class Auctioneer extends Thread { private List<Auction> auctions; private final int maxAuctions; private Auction currentAuction; public Auctioneer(){ this.auctions = new ArrayList<Auction>(); this.maxAuctions = ConfigurationLoader.getMaxAuctions(); } public Auction getCurrentAuction() { return currentAuction; } public void setCurrentAuction(Auction currentAuction) { this.currentAuction = currentAuction; } public List<Auction> getAuctions() { return auctions; } public synchronized void pushAuctionToQueue(Auction auction, Player player){ if(auctions.size()<maxAuctions){ boolean hasAuction = false; for (Auction auctionInQueue : auctions) { if(auctionInQueue.getPlayerId().equals(player.getIdentifier())){ hasAuction=true; } } if(currentAuction!=null){ if(currentAuction.getPlayerId().equals(player.getIdentifier())){ hasAuction=true; } } if(hasAuction){ player.sendMessage(StaticsHandler.buildTextForEcoPlugin("Allready have auction in queue", TextColors.RED)); }else{ auctions.add(auction); StringBuilder auctionNotification = new StringBuilder(); auctionNotification .append("Auction queued number "); auctionNotification .append(auctions.indexOf(auction) + 1); auctionNotification .append(" in line"); player.sendMessage(StaticsHandler.buildTextForEcoPlugin(auctionNotification.toString(), TextColors.BLUE)); } }else{ player.sendMessage(StaticsHandler.buildTextForEcoPlugin("Auction queue is full, please try again later", TextColors.RED)); } } public synchronized void cancel(Player player){ if(currentAuction!=null){ if(currentAuction.getPlayerId().equals(player.getIdentifier())){ if(currentAuction.isCancelable()){ currentAuction.cancelAuction(); StaticsHandler.getGame().getServer().broadcastMessage(StaticsHandler.buildTextForEcoPlugin("Auction Cancelled",TextColors.BLUE)); }else{ player.sendMessage(StaticsHandler.buildTextForEcoPlugin("Auction can not be cancelled at this time",TextColors.RED)); } }else{ cancelFromAllAuctions(player); } }else{ cancelFromAllAuctions(player); } } private void cancelFromAllAuctions(Player player) { //any other auctions to cancel? List<Integer> indexesToRemove = new ArrayList<Integer>(); for (Auction auction : auctions) { if(auction.getPlayerId().equals(player.getIdentifier())){ indexesToRemove.add(auctions.indexOf(auction)); player.sendMessage(StaticsHandler.buildTextForEcoPlugin("Auction Cancelled",TextColors.BLUE)); } } for (int index : indexesToRemove) { auctions.remove(index); } } private synchronized void bid(Bid bid) { synchronized(currentAuction){ if(currentAuction!=null){ if(currentAuction.isBidable()){ if(bid.getMaxBid()>=currentAuction.getStartingBid()){ if(currentAuction.getCurrentBid()==null){ if(bid.getBid()<currentAuction.getStartingBid()){ bid.setBid(currentAuction.getStartingBid()); bid.setCurrentBid(currentAuction.getStartingBid()); } currentAuction.setCurrentBid(bid); sendBidBroadcast(bid); }else if(currentAuction.getCurrentBid().getPlayer().getIdentifier().equals(bid.getPlayer().getIdentifier())){ //Player who is the current bidder is bidding again Bid currentBid = currentAuction.getCurrentBid(); if(currentBid.getMaxBid()<=bid.getMaxBid()){ //player wishes to increase max bid bid.setBid(currentBid.getBid()); bid.setBid(currentBid.getCurrentBid()); currentAuction.setCurrentBid(bid); bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("You have raised your max bid",TextColors.RED)); }else{ bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("You are currently the highest bidder, add a higher max bid to increase your maximum",TextColors.RED)); } }else{ Bid currentBid = currentAuction.getCurrentBid(); double increment =currentAuction.getIncrement(); //They're base bid is higher than the current if(bid.getBid()>currentBid.getCurrentBid()+increment){ //They also have outbid the max bid if(bid.getBid()>currentBid.getMaxBid()){ currentAuction.setCurrentBid(bid); sendBidBroadcast(bid); }else{ //They are lower than the max, how about their max bid? if(bid.getMaxBid()>currentBid.getMaxBid()){ //Their max is higher bid.setBid(currentBid.getCurrentBid()+currentAuction.getIncrement()); bid.setCurrentBid(currentBid.getCurrentBid()+currentAuction.getIncrement()); currentAuction.setCurrentBid(bid); sendBidBroadcast(bid); }else{ //Current max is higher bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("You have been automatically outbid",TextColors.RED)); currentAuction.raiseCurrentBid(bid.getMaxBid()); sendIncreasedBidBroadcast(bid.getMaxBid()); } } //Their bid is too low, however how is their maximum? }else if(bid.getMaxBid()>currentBid.getCurrentBid()+increment){ //New max bid is higher than current max bid if(bid.getMaxBid()>currentBid.getMaxBid()){ //New bid is better, do we need the increment? if(currentBid.getCurrentBid()>currentBid.getMaxBid()-increment){ bid.setBid(currentBid.getCurrentBid()+currentAuction.getIncrement()); bid.setCurrentBid(currentBid.getCurrentBid()+currentAuction.getIncrement()); }else{ bid.setBid(currentBid.getMaxBid()); bid.setCurrentBid(currentBid.getMaxBid()); } currentAuction.setCurrentBid(bid); sendBidBroadcast(bid); }else{ //current max bid is higher, current bid is raised to match max bid bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("You have been automatically outbid",TextColors.RED)); currentAuction.raiseCurrentBid(bid.getMaxBid()); sendIncreasedBidBroadcast(bid.getMaxBid()); } }else{ //The max bid specified does not cover the current bid + increment bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("Bid too low",TextColors.RED)); } } }else{ bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("Bid too low",TextColors.RED)); } }else{ bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("Cannot bid at this time",TextColors.RED)); } }else{ bid.getPlayer().sendMessage(StaticsHandler.buildTextForEcoPlugin("There is no auction currently running",TextColors.RED)); } } } private void sendIncreasedBidBroadcast(double bid){ StringBuilder bidMessage = new StringBuilder(); bidMessage.append("Bid has been raised to "); bidMessage.append(bid); StaticsHandler.getGame().getServer().broadcastMessage(StaticsHandler.buildTextForEcoPlugin(bidMessage.toString(),TextColors.BLUE)); } private void sendBidBroadcast(Bid bid) { StringBuilder bidMessage = new StringBuilder(); bidMessage.append(bid.getPlayer().getName()); bidMessage.append(" bids "); bidMessage.append(bid.getBid()); StaticsHandler.getGame().getServer().broadcastMessage(StaticsHandler.buildTextForEcoPlugin(bidMessage.toString(),TextColors.BLUE)); } public synchronized void bid(Player player, double initialBid) { synchronized (currentAuction){ initialBid = EconomyCache.round(initialBid, ConfigurationLoader.getDecPlaces()); Bid bid = new Bid(player, initialBid, initialBid); bid(bid); } } public synchronized void bid(Player player) { synchronized (currentAuction){ Bid currentBid = currentAuction.getCurrentBid(); double increment = currentAuction.getIncrement(); Bid bid = new Bid(player, currentBid.getMaxBid() + increment, currentBid.getMaxBid() + increment); bid(bid); } } public synchronized void bid(Player player, double initialBid, double max) { if(max>=initialBid){ initialBid = EconomyCache.round(initialBid, ConfigurationLoader.getDecPlaces()); max = EconomyCache.round(max, ConfigurationLoader.getDecPlaces()); Bid bid = new Bid(player, initialBid, max); bid(bid); }else{ player.sendMessage(StaticsHandler.buildTextForEcoPlugin("Max bid can not be lower than intial bid",TextColors.RED)); } } }
package com.exedio.cope.pattern; import java.util.LinkedHashMap; import com.exedio.cope.Field; import com.exedio.cope.Cope; import com.exedio.cope.Feature; import com.exedio.cope.FunctionField; import com.exedio.cope.Item; import com.exedio.cope.ItemField; import com.exedio.cope.Pattern; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.UniqueConstraint; public final class FieldMap<K,V> extends Pattern { private ItemField<? extends Item> parent = null; private final FunctionField<K> key; private UniqueConstraint uniqueConstraint = null; private final FunctionField<V> value; private Type<?> relationType = null; private FieldMap(final FunctionField<K> key, final FunctionField<V> value) { this.key = key; this.value = value; if(key==null) throw new NullPointerException("key must not be null"); if(key.getImplicitUniqueConstraint()!=null) throw new NullPointerException("key must not be unique"); if(value==null) throw new NullPointerException("value must not be null"); if(value.getImplicitUniqueConstraint()!=null) throw new NullPointerException("value must not be unique"); } public static final <K,V> FieldMap<K,V> newMap(final FunctionField<K> key, final FunctionField<V> value) { return new FieldMap<K,V>(key, value); } @Override public void initialize() { final Type<?> type = getType(); parent = Item.newItemField(Field.Option.FINAL, type.getJavaClass(), ItemField.DeletePolicy.CASCADE); uniqueConstraint = new UniqueConstraint(parent, key); final LinkedHashMap<String, Feature> relationTypeFeatures = new LinkedHashMap<String, Feature>(); relationTypeFeatures.put("parent", parent); relationTypeFeatures.put("key", key); relationTypeFeatures.put("uniqueConstraint", uniqueConstraint); relationTypeFeatures.put("value", value); this.relationType = newType(relationTypeFeatures); } public ItemField<?> getParent() { assert parent!=null; return parent; } public FunctionField<K> getKey() { return key; } public UniqueConstraint getUniqueConstraint() { assert uniqueConstraint!=null; return uniqueConstraint; } public FunctionField<V> getValue() { return value; } public Type<?> getRelationType() { assert relationType!=null; return relationType; } public V get(final Item item, final K key) { final Item relationItem = uniqueConstraint.searchUnique(new Object[]{item, key}); if(relationItem!=null) return value.get(relationItem); else return null; } public void set(final Item item, final K key, final V value) { final Item relationItem = uniqueConstraint.searchUnique(new Object[]{item, key}); if(relationItem==null) { if(value!=null) uniqueConstraint.getType().newItem(new SetValue[]{ Cope.mapAndCast(this.parent, item), this.key.map(key), this.value.map(value), }); } else { if(value!=null) this.value.set(relationItem, value); else relationItem.deleteCopeItem(); } } public V getAndCast(final Item item, final Object key) { return get(item, Cope.verboseCast(this.key.getValueClass(), key)); } public void setAndCast(final Item item, final Object key, final Object value) { set(item, Cope.verboseCast(this.key.getValueClass(), key), Cope.verboseCast(this.value.getValueClass(), value)); } }
package com.exedio.cope.pattern; import java.util.LinkedHashMap; import com.exedio.cope.Cope; import com.exedio.cope.Feature; import com.exedio.cope.FunctionField; import com.exedio.cope.Item; import com.exedio.cope.ItemField; import com.exedio.cope.Join; import com.exedio.cope.Pattern; import com.exedio.cope.Query; import com.exedio.cope.Type; import com.exedio.cope.UniqueConstraint; public final class FieldMap<K,V> extends Pattern { private ItemField<? extends Item> parent = null; private final FunctionField<K> key; private UniqueConstraint uniqueConstraint = null; private final FunctionField<V> value; private Type<?> relationType = null; private FieldMap(final FunctionField<K> key, final FunctionField<V> value) { this.key = key; this.value = value; if(key==null) throw new NullPointerException("key must not be null"); if(key.getImplicitUniqueConstraint()!=null) throw new NullPointerException("key must not be unique"); if(value==null) throw new NullPointerException("value must not be null"); if(value.getImplicitUniqueConstraint()!=null) throw new NullPointerException("value must not be unique"); } public static final <K,V> FieldMap<K,V> newMap(final FunctionField<K> key, final FunctionField<V> value) { return new FieldMap<K,V>(key, value); } @Override public void initialize() { final Type<?> type = getType(); parent = type.newItemField(ItemField.DeletePolicy.CASCADE).toFinal(); uniqueConstraint = new UniqueConstraint(parent, key); final LinkedHashMap<String, Feature> relationTypeFeatures = new LinkedHashMap<String, Feature>(); relationTypeFeatures.put("parent", parent); relationTypeFeatures.put("key", key); relationTypeFeatures.put("uniqueConstraint", uniqueConstraint); relationTypeFeatures.put("value", value); this.relationType = newType(relationTypeFeatures); } private void assertParent(final Class<?> parentClass) { if(!parent.getValueClass().equals(parentClass)) throw new IllegalArgumentException( "parent class must be " + parent.getValueClass().getName() + ", but was " + parentClass.getName()); } public <P extends Item> ItemField<P> getParent(final Class<P> parentClass) { assertParent(parentClass); return (ItemField<P>)parent; } public FunctionField<K> getKey() { return key; } public UniqueConstraint getUniqueConstraint() { assert uniqueConstraint!=null; return uniqueConstraint; } public FunctionField<V> getValue() { return value; } public Type<?> getRelationType() { assert relationType!=null; return relationType; } public V get(final Item item, final K key) { final Item relationItem = uniqueConstraint.searchUnique(item, key); if(relationItem!=null) return value.get(relationItem); else return null; } public void set(final Item item, final K key, final V value) { final Item relationItem = uniqueConstraint.searchUnique(item, key); if(relationItem==null) { if(value!=null) uniqueConstraint.getType().newItem( Cope.mapAndCast(this.parent, item), this.key.map(key), this.value.map(value) ); } else { if(value!=null) this.value.set(relationItem, value); else relationItem.deleteCopeItem(); } } public V getAndCast(final Item item, final Object key) { return get(item, Cope.verboseCast(this.key.getValueClass(), key)); } public void setAndCast(final Item item, final Object key, final Object value) { set(item, Cope.verboseCast(this.key.getValueClass(), key), Cope.verboseCast(this.value.getValueClass(), value)); } public Join join(final Query q, final K key) { return q.joinOuterLeft( getRelationType(), parent.equalTarget(). and(this.key.equal(key))); } }
package com.qiniu.android; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.provider.MediaStore; import com.qiniu.android.http.ResponseInfo; import com.qiniu.android.storage.Configuration; import com.qiniu.android.storage.UpCompletionHandler; import com.qiniu.android.storage.UploadManager; import com.qiniu.android.utils.ContextGetter; import com.qiniu.android.utils.Etag; import com.qiniu.android.utils.LogUtil; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class UriTest extends BaseTest { private static boolean[][] testConfigList = { {true, true, true}, {true, true, false}, {true, false, true}, {true, false, false}, {false, true, true}, {false, true, false}, {false, false, true}, {false, false, false}, }; public void testUpload() { int MB = 1024; int[] sizeList = {512, MB, 4*MB, 5*MB, 8*MB, 10*MB, 20*MB}; for (int size : sizeList) { String fileName = size + "KB" + ".mp4"; File file = createFile(size); Uri uri = null; try { uri = writeFileToDownload(file, fileName); } catch (FileNotFoundException e) { e.printStackTrace(); Assert.fail(e.getMessage()); return; } String etag = null; try { etag = Etag.file(file); } catch (IOException e) { e.printStackTrace(); } for (boolean[] config : testConfigList) { testUpload(uri, fileName, etag, config[0], config[1], config[2]); } removeUri(uri); } } private void testUpload(Uri uri, String fileName, String etag, boolean isHttps, boolean isResumableV1, boolean isConcurrent) { assertNotNull("Uri write file error:" + fileName, uri); Configuration configuration = new Configuration.Builder() .resumeUploadVersion(isResumableV1 ? Configuration.RESUME_UPLOAD_VERSION_V1 : Configuration.RESUME_UPLOAD_VERSION_V2) .chunkSize(isResumableV1 ? 1024*1024*2 : 1024*1024*4) .useConcurrentResumeUpload(isConcurrent) .useHttps(isHttps) .build(); UploadManager uploadManager = new UploadManager(configuration); String key = "uri_upload_"; key += isHttps ? "https_" : "http_"; key += isResumableV1 ? "v1_" : "v2_"; key += isConcurrent ? "serial_" : "concurrent_"; key += fileName; final UploadCompleteInfo completeInfo = new UploadCompleteInfo(); uploadManager.put(uri, null, key, TestConfig.token_na0, new UpCompletionHandler() { @Override public void complete(String key, ResponseInfo info, JSONObject response) { completeInfo.key = key; completeInfo.responseInfo = info; } }, null); wait(new WaitConditional() { @Override public boolean shouldWait() { return completeInfo.responseInfo == null; } }, 10 * 60); LogUtil.d("=== upload response key:" + (key != null ? key : "") + " response:" + completeInfo.responseInfo); assertTrue(completeInfo.responseInfo.toString(), completeInfo.responseInfo != null); assertTrue(completeInfo.responseInfo.toString(), completeInfo.responseInfo.statusCode == ResponseInfo.RequestSuccess); assertTrue(completeInfo.responseInfo.toString(), key.equals(completeInfo.key)); String serverEtag = null; try { serverEtag = completeInfo.responseInfo.response.getString("hash"); } catch (JSONException e) { e.printStackTrace(); } System.out.println(" etag:" + etag); System.out.println("serverEtag:" + serverEtag); assertNotNull("key:" + key, serverEtag); assertEquals("key:" + key, etag, serverEtag); } private File createFile(int size) { File file = null; try { file = TempFile.createFile(size); } catch (IOException e) { e.printStackTrace(); } return file; } private Uri writeFileToDownload(File file, String fileName) throws FileNotFoundException { InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); throw e; } ContentResolver resolver = ContextGetter.applicationContext().getContentResolver(); ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, fileName); Uri imageUri = null; try { imageUri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues); } catch (Exception e) { e.printStackTrace(); } if (imageUri != null) { // uri // uri OutputStream outputStream = null; try { outputStream = resolver.openOutputStream(imageUri); } catch (FileNotFoundException e) { e.printStackTrace(); } if (outputStream != null) { try { byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } outputStream.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } return imageUri; } private void removeUri(Uri uri) { ContentResolver resolver = ContextGetter.applicationContext().getContentResolver(); resolver.delete(uri, null, null); } protected static class UploadCompleteInfo { String key; ResponseInfo responseInfo; } }
package com.qiniu.android.utils; import android.os.Handler; import android.os.Looper; public final class AsyncRun { public static void run(Runnable r) { Handler h = new Handler(Looper.getMainLooper()); h.post(r); } }
package cn.fiona.pet.service; import cn.fiona.pet.dto.SignInDTO; import cn.fiona.pet.entity.Organize; import cn.fiona.pet.entity.Role; import cn.fiona.pet.entity.User; import cn.fiona.pet.entity.UserRole; import cn.fiona.pet.repository.RoleDao; import cn.fiona.pet.repository.UserDao; import cn.fiona.pet.repository.UserRoleDao; import com.alibaba.dubbo.common.utils.StringUtils; import lombok.Getter; import org.apache.shiro.authc.AuthenticationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springside.modules.security.utils.Digests; import org.springside.modules.utils.Encodes; import javax.validation.constraints.NotNull; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Service @Getter public class AccountServiceImpl implements AccountService { @Autowired private UserDao userDao; @Autowired private RoleDao roleDao; @Autowired private UserRoleDao userRoleDao; private Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class); @Override public String login(@NotNull SignInDTO signInDTO) { User user = userDao.findByLoginNameAndStatus(signInDTO.getName(),"OK"); if (null == user) { throw new AuthenticationException(String.format("[%s]!", signInDTO)); } String password = signInDTO.getPassword(); if (StringUtils.isBlank(password)) { throw new InvalidParameterException("!"); } if (!passwordValidation(password, user)) { throw new InvalidParameterException("!"); } String token = user.getId(); return token; } private boolean passwordValidation(String password, User user) { byte[] salt = Encodes.decodeHex(user.getSalt()); byte[] hashPassword = Digests.sha1(password.getBytes(), salt, 1024); return user.getPassword().equals(Encodes.encodeHex(hashPassword)); } @Override public boolean validateToken(@NotNull String token) { if (StringUtils.isBlank(token)){ throw new InvalidParameterException("token is null!"); } User user = userDao.findOne(token); if (null == user){ throw new InvalidParameterException(String.format("%s not exists!", token)); } return true; } @Override public User getByToken(String token) { User user = userDao.findOne(token); if (null == user) { throw new InvalidParameterException(String.format("%s not exists!", token)); } User userVO = new User(); userVO.setId(user.getId()); userVO.setName(user.getName()); userVO.setLoginName(user.getLoginName()); userVO.setOrganize(user.getOrganize()); return userVO; } @Override public List<User> listByRoleCode(String code) { List<UserRole> userRoles = userRoleDao.findByRoleCode(code); List<User> users = new ArrayList<User>(); for (UserRole userRole: userRoles){ User userVO = new User(); userVO.setName(userRole.getUser().getName()); userVO.setId(userRole.getUser().getId()); userVO.setLoginName(userRole.getUser().getLoginName()); users.add(userVO); } return users; } @Override public User createUser(User user) { Organize organize = new Organize(); organize.setId("9b06d376-44ff-4153-9b31-c29a19b8da29"); user.setOrganize(organize); // Set<Role> roleSet = new HashSet<Role>(); // for (UserRole role: user.getUserRoles()){ // logger.debug("add role:{}", role.getRole().getCode()); // roleSet.add(role.getRole()); // if (roleSet.size() == 0){ // roleSet.add(roleDao.findByCode("doctor")); // user.setRoles(roleSet); encode(user); userDao.save(user); User userVO = new User(); userVO.setId(user.getId()); userVO.setName(user.getName()); userVO.setLoginName(user.getLoginName()); return userVO; } private void encode(User user){ byte[] salt = Encodes.decodeHex(user.getSalt()); byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, 1024); user.setPassword(Encodes.encodeHex(hashPassword)); } @Override public boolean hasRole(String role, String token) { User user = userDao.findOne(token); if (null == user) { throw new InvalidParameterException(String.format("%s not exists!", token)); } for (UserRole ur: user.getUserRoles()){ if (null != role && role.equalsIgnoreCase(ur.getRole().getCode())){ return true; } } return false; } }
package org.opendatakit.dependencies; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import org.opendatakit.androidcommon.R; import org.opendatakit.application.CommonApplication; /** * This class checks for app dependencies, informing the user if any are missing * * @author marshallbradley93@gmail.com */ public class DependencyChecker { public static final String surveyAppPkgName = "org.opendatakit.survey"; private static final String oiFileMgrPkgName = "org.openintents.filemanager"; private static final String servicesAppPkgName = "org.opendatakit.services"; private static final String tables = "tables"; private static final String scan = "scan"; private final Activity activity; private final Context context; public DependencyChecker(Activity activity) { this.activity = activity; this.context = activity.getApplicationContext(); } public boolean checkDependencies() { boolean oiInstalled; boolean servicesInstalled; if (tables.equals(((CommonApplication)context).getToolName()) || scan.equals(((CommonApplication)context).getToolName())) { // need to check // for OI and Services oiInstalled = isPackageInstalled(context, oiFileMgrPkgName); } else { // only need to check for Services oiInstalled = true; } servicesInstalled = isPackageInstalled(context, servicesAppPkgName); if (oiInstalled && servicesInstalled) { // correct dependencies installed return true; } else { alertMissing(oiInstalled, servicesInstalled); // missing dependencies, warn user return false; } } private void alertMissing(boolean oiInstalled, boolean servicesInstalled) { String message; String title = context.getString(R.string.dependency_missing); if (oiInstalled && !servicesInstalled) { message = context.getString(R.string.services_missing); } else if (!oiInstalled && servicesInstalled) { message = context.getString(R.string.oi_missing); } else { message = context.getString(R.string.oi_and_services_missing); title = context.getString(R.string.dependencies_missing); } AlertDialog alert = buildAlert(title, message); alert.show(); } private AlertDialog buildAlert(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(title); builder.setMessage(message); builder.setCancelable(false); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.finish(); System.exit(0); } }); return builder.create(); } public static boolean isPackageInstalled(Context context, String packageName) { PackageManager pm = context.getPackageManager(); try { pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); return true; } catch (PackageManager.NameNotFoundException e) { return false; } } }
package jorgedizpico; import java.util.Random; import dk.itu.mario.MarioInterface.GamePlay; import dk.itu.mario.MarioInterface.LevelGenerator; import dk.itu.mario.MarioInterface.LevelInterface; public class LakituLevelGenerator implements LevelGenerator { protected static Random rand = new Random(); protected LakituParameters lkp; @Override public LevelInterface generateLevel(GamePlay playerMetrics) { LakituLevel lvl = new LakituLevel(); lkp = new LakituParameters(playerMetrics); ground_pass(lvl); return lvl; } @Override public LevelInterface generateLevel(String detailedInfo) { // TODO Auto-generated method stub return null; } protected int start_platform(LakituLevel lvl, LakituParameters lkp) { int initY = (int) (rand.nextDouble()*lvl.getHeight()/2) + (lvl.getHeight()/2); initY = lvl.constrain_height(initY); lvl.setGroundHeight(0, initY); lvl.addFlatLand(1, lkp.I_START_PLATFORM-1); return initY; } protected void ground_pass(LakituLevel lvl) { /*int length = 0; boolean inGap = false;*/ start_platform(lvl, lkp); // loop optimization int middlestart = lkp.I_START_PLATFORM; int middleend = lvl.getWidth() - lkp.I_END_PLATFORM; int width = 2; for (int x = middlestart; x < middleend; x += width) { double roll = rand.nextDouble(); if (roll < lkp.CHANCE_GAP) { roll = rand.nextDouble(); if (roll < lkp.CHANCE_GAP_HILL); else if (roll < lkp.CHANCE_GAP_BOX); else if (roll < lkp.CHANCE_GAP_VANILLA); } else if (roll < lkp.CHANCE_VERT) { roll = rand.nextDouble(); if (roll < lkp.CHANCE_VERT_PIPE); else if (roll < lkp.CHANCE_VERT_STAIRS); else if (roll < lkp.CHANCE_VERT_HILL) { width = hill_buffer(middleend - x); lvl.addHillChange(x, hill_change(), width); } } else { width = 3; lvl.addFlatLand(x, width); } } // end_platform() lvl.addFlatLand(middleend, lkp.I_END_PLATFORM); lvl.setExit(lvl.getWidth() - lkp.I_EXIT_OFFSET); lvl.fixWalls(); } public int hill_change() { return (int) (lkp.VERT_HILL_OFFSET + lkp.VERT_HILL_RANGE * rand.nextDouble()); } public int hill_buffer(int max) { int candidate = (int) (lkp.VERT_HILL_MIN + lkp.VERT_HILL_MAXEXTRA * rand.nextDouble()); if (candidate > max) candidate = max; return candidate; } }
package io.druid.server; import com.fasterxml.jackson.annotation.JsonProperty; import io.druid.initialization.Initialization; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Path("/{a:status|health}") public class StatusResource { @GET @Produces("application/json") public Status doGet() { return getStatus(); } public static Status getStatus() { return new Status( Initialization.class.getPackage().getImplementationVersion(), new Memory(Runtime.getRuntime()) ); } public static class Status { final String version; final Memory memory; public Status( String version, Memory memory ) { this.version = version; this.memory = memory; } @JsonProperty public String getVersion() { return version; } @JsonProperty public Memory getMemory() { return memory; } @Override public String toString() { final String NL = System.getProperty("line.separator"); return String.format("Druid version - %s", version) + NL; } } public static class ModuleVersion { final String name; final String artifact; final String version; public ModuleVersion(String name) { this(name, "", ""); } public ModuleVersion(String name, String artifact, String version) { this.name = name; this.artifact = artifact; this.version = version; } @JsonProperty public String getName() { return name; } @JsonProperty public String getArtifact() { return artifact; } @JsonProperty public String getVersion() { return version; } @Override public String toString() { if (artifact.isEmpty()) { return String.format(" - %s ", name); } else { return String.format(" - %s (%s-%s)", name, artifact, version); } } } public static class Memory { final long maxMemory; final long totalMemory; final long freeMemory; final long usedMemory; public Memory(Runtime runtime) { maxMemory = runtime.maxMemory(); totalMemory = runtime.totalMemory(); freeMemory = runtime.freeMemory(); usedMemory = totalMemory - freeMemory; } @JsonProperty public long getMaxMemory() { return maxMemory; } @JsonProperty public long getTotalMemory() { return totalMemory; } @JsonProperty public long getFreeMemory() { return freeMemory; } @JsonProperty public long getUsedMemory() { return usedMemory; } } }
package com.heinrichreimersoftware.materialintro.demo; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import butterknife.BindView; import butterknife.ButterKnife; public class FinishActivity extends AppCompatActivity { public static final String PREF_KEY_FIRST_START = "com.heinrichreimersoftware.materialintro.demo.PREF_KEY_FIRST_START"; public static final int REQUEST_CODE_INTRO = 1; @BindView(R.id.toolbar) Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_finish); ButterKnife.bind(this); setSupportActionBar(toolbar); boolean firstStart = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(PREF_KEY_FIRST_START, true); if (firstStart) { Intent intent = new Intent(this, SplashIntroActivity.class); startActivityForResult(intent, REQUEST_CODE_INTRO); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_INTRO) { if (resultCode == RESULT_OK) { PreferenceManager.getDefaultSharedPreferences(this).edit() .putBoolean(PREF_KEY_FIRST_START, false) .apply(); } else { PreferenceManager.getDefaultSharedPreferences(this).edit() .putBoolean(PREF_KEY_FIRST_START, true) .apply(); //User cancelled the intro so we'll finish this activity too. finish(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_finish, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_item_reset_first_start) { PreferenceManager.getDefaultSharedPreferences(this).edit() .putBoolean(PREF_KEY_FIRST_START, true) .apply(); return true; } return super.onOptionsItemSelected(item); } }
package org.openlmis.core.view.activity; import android.app.DatePickerDialog; import android.content.Context; import android.content.Intent; import android.graphics.PorterDuff; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.AdapterView; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import org.apache.commons.lang3.StringUtils; import org.openlmis.core.LMISApp; import org.openlmis.core.R; import org.openlmis.core.exceptions.LMISException; import org.openlmis.core.googleAnalytics.ScreenName; import org.openlmis.core.manager.MovementReasonManager; import org.openlmis.core.manager.NestedRecyclerViewLinearLayoutManager; import org.openlmis.core.model.StockMovementItem; import org.openlmis.core.presenter.NewStockMovementPresenter; import org.openlmis.core.utils.Constants; import org.openlmis.core.utils.DateUtil; import org.openlmis.core.utils.InjectPresenter; import org.openlmis.core.utils.ToastUtil; import org.openlmis.core.view.adapter.LotMovementAdapter; import org.openlmis.core.view.fragment.SimpleSelectDialogFragment; import org.openlmis.core.view.viewmodel.LotMovementViewModel; import org.openlmis.core.view.viewmodel.StockMovementViewModel; import org.openlmis.core.view.widget.AddLotDialogFragment; import org.roboguice.shaded.goole.common.base.Function; import org.roboguice.shaded.goole.common.collect.FluentIterable; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import roboguice.inject.ContentView; import roboguice.inject.InjectView; import rx.functions.Action1; @ContentView(R.layout.activity_stock_card_new_movement) public class StockCardNewMovementActivity extends BaseActivity implements NewStockMovementPresenter.NewStockMovementView, View.OnClickListener { @InjectView(R.id.ly_requested_quantity) View lyRequestedQuantity; @InjectView(R.id.et_movement_date) EditText etMovementDate; @InjectView(R.id.ly_movement_date) TextInputLayout lyMovementDate; @InjectView(R.id.et_document_number) EditText etDocumentNumber; @InjectView(R.id.et_movement_reason) EditText etMovementReason; @InjectView(R.id.ly_movement_reason) TextInputLayout lyMovementReason; @InjectView(R.id.et_requested_quantity) EditText etRequestedQuantity; @InjectView(R.id.et_movement_quantity) EditText etMovementQuantity; @InjectView(R.id.ly_movement_quantity) TextInputLayout lyMovementQuantity; @InjectView(R.id.et_movement_signature) EditText etMovementSignature; @InjectView(R.id.ly_movement_signature) TextInputLayout lyMovementSignature; @InjectView(R.id.btn_complete) View btnComplete; @InjectView(R.id.btn_cancel) TextView tvCancel; @InjectView(R.id.alert_add_lot_amount) TextView alertAddLotAmount; @InjectView(R.id.action_add_new_lot) View actionAddNewLot; @InjectView(R.id.lot_list) private RecyclerView lotMovementRecycleView; @InjectView(R.id.existing_lot_list) private RecyclerView existingLotListView; @InjectPresenter(NewStockMovementPresenter.class) NewStockMovementPresenter presenter; private LotMovementAdapter lotMovementAdapter; private LotMovementAdapter existingLotMovementAdapter; private String stockName; private MovementReasonManager.MovementType movementType; private Long stockCardId; StockMovementItem previousMovement; private List<MovementReasonManager.MovementReason> movementReasons; private MovementReasonManager movementReasonManager; SimpleSelectDialogFragment reasonsDialog; private StockMovementViewModel stockMovementViewModel; private String[] reasonListStr; private boolean isKit; private Context context; private AddLotDialogFragment addLotDialogFragment; @Override protected ScreenName getScreenName() { return ScreenName.StockCardNewMovementScreen; } @Override protected void onCreate(Bundle savedInstanceState) { context = this; super.onCreate(savedInstanceState); movementReasonManager = MovementReasonManager.getInstance(); stockName = getIntent().getStringExtra(Constants.PARAM_STOCK_NAME); movementType = (MovementReasonManager.MovementType) getIntent().getSerializableExtra(Constants.PARAM_MOVEMENT_TYPE); stockCardId = getIntent().getLongExtra(Constants.PARAM_STOCK_CARD_ID, 0L); isKit = getIntent().getBooleanExtra(Constants.PARAM_IS_KIT, false); movementReasons = movementReasonManager.buildReasonListForMovementType(movementType); try { previousMovement = presenter.loadPreviousMovement(stockCardId); } catch (LMISException e) { e.printStackTrace(); } stockMovementViewModel = presenter.getStockMovementModel(); initUI(); if (movementType.equals(MovementReasonManager.MovementType.RECEIVE) || movementType.equals(MovementReasonManager.MovementType.POSITIVE_ADJUST)) { initExistingLotListView(); } initRecyclerView(); } private void initExistingLotListView() { existingLotListView.setLayoutManager(new NestedRecyclerViewLinearLayoutManager(this)); existingLotMovementAdapter = new LotMovementAdapter(presenter.getExistingLotViewModelsByStockCard(stockCardId)); existingLotListView.setAdapter(existingLotMovementAdapter); } private void initRecyclerView() { lotMovementRecycleView.setLayoutManager(new NestedRecyclerViewLinearLayoutManager(this)); lotMovementAdapter = new LotMovementAdapter(presenter.getStockMovementModel().getLotMovementViewModelList(), previousMovement.getStockCard().getProduct().getProductNameWithCodeAndStrength()); lotMovementRecycleView.setAdapter(lotMovementAdapter); } private void refreshRecyclerView() { lotMovementAdapter.notifyDataSetChanged(); } private void initUI() { setTitle(movementType.getDescription() + " " + stockName); if (!movementType.equals(MovementReasonManager.MovementType.ISSUE)) { lyRequestedQuantity.setVisibility(View.GONE); } if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management) && !isKit && (movementType.equals(MovementReasonManager.MovementType.RECEIVE) || movementType.equals(MovementReasonManager.MovementType.POSITIVE_ADJUST))) { actionAddNewLot.setVisibility(View.VISIBLE); lyMovementQuantity.setVisibility(View.GONE); } btnComplete.setOnClickListener(this); tvCancel.setOnClickListener(this); etMovementDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDatePickerDialog(presenter.getStockMovementModel(), previousMovement.getMovementDate()); } }); etMovementDate.setKeyListener(null); etMovementReason.setOnClickListener(getMovementReasonOnClickListener()); etMovementReason.setKeyListener(null); actionAddNewLot.setOnClickListener(getAddNewLotOnClickListener()); } @NonNull private View.OnClickListener getAddNewLotOnClickListener() { return new View.OnClickListener() { @Override public void onClick(View v) { actionAddNewLot.setEnabled(false); addLotDialogFragment = new AddLotDialogFragment(); addLotDialogFragment.setListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_complete: if (addLotDialogFragment.validate() && !addLotDialogFragment.hasIdenticalLot(getLotNumbers())) { presenter.addLotMovement(new LotMovementViewModel(addLotDialogFragment.getLotNumber(), addLotDialogFragment.getExpiryDate())) .subscribe(new Action1<List<LotMovementViewModel>>() { @Override public void call(List<LotMovementViewModel> lotMovementViewModels) { refreshRecyclerView(); } }); addLotDialogFragment.dismiss(); } actionAddNewLot.setEnabled(true); break; case R.id.btn_cancel: addLotDialogFragment.dismiss(); actionAddNewLot.setEnabled(true); break; } } }); addLotDialogFragment.show(getFragmentManager(), ""); } }; } @NonNull private List<String> getLotNumbers() { final List<String> existingLots = new ArrayList<>(); existingLots.addAll(FluentIterable.from(stockMovementViewModel.getLotMovementViewModelList()).transform(new Function<LotMovementViewModel, String>() { @Override public String apply(LotMovementViewModel lotMovementViewModel) { return lotMovementViewModel.getLotNumber(); } }).toList()); existingLots.addAll(FluentIterable.from((stockMovementViewModel.getExistingLotMovementViewModelList())).transform(new Function<LotMovementViewModel, String>() { @Override public String apply(LotMovementViewModel lotMovementViewModel) { return lotMovementViewModel.getLotNumber(); } }).toList()); return existingLots; } @NonNull private View.OnClickListener getMovementReasonOnClickListener() { return new View.OnClickListener() { @Override public void onClick(View view) { reasonListStr = FluentIterable.from(movementReasons).transform(new Function<MovementReasonManager.MovementReason, String>() { @Override public String apply(MovementReasonManager.MovementReason movementReason) { return movementReason.getDescription(); } }).toArray(String.class); reasonsDialog = new SimpleSelectDialogFragment(context, new MovementTypeOnClickListener(stockMovementViewModel), reasonListStr); reasonsDialog.show(getFragmentManager(), ""); } }; } public static Intent getIntentToMe(StockMovementsActivityNew context, String stockName, MovementReasonManager.MovementType movementType, Long stockCardId, boolean isKit) { Intent intent = new Intent(context, StockCardNewMovementActivity.class); intent.putExtra(Constants.PARAM_STOCK_NAME, stockName); intent.putExtra(Constants.PARAM_MOVEMENT_TYPE, movementType); intent.putExtra(Constants.PARAM_STOCK_CARD_ID, stockCardId); intent.putExtra(Constants.PARAM_IS_KIT, isKit); return intent; } private void showDatePickerDialog(StockMovementViewModel model, Date previousMovementDate) { final Calendar today = GregorianCalendar.getInstance(); DatePickerDialog dialog = new DatePickerDialog(this, DatePickerDialog.BUTTON_NEUTRAL, new MovementDateListener(model, previousMovementDate), today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH)); dialog.show(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_complete: stockMovementViewModel.setMovementDate(etMovementDate.getText().toString()); stockMovementViewModel.setDocumentNo(etDocumentNumber.getText().toString()); stockMovementViewModel.setRequested(etRequestedQuantity.getText().toString()); HashMap<MovementReasonManager.MovementType, String> quantityMap = new HashMap<>(); quantityMap.put(movementType, etMovementQuantity.getText().toString()); stockMovementViewModel.setTypeQuantityMap(quantityMap); stockMovementViewModel.setSignature(etMovementSignature.getText().toString()); stockMovementViewModel.setLotMovementViewModelList(lotMovementAdapter.getLotList()); if (showErrors(stockMovementViewModel)) return; presenter.saveStockMovement(); break; case R.id.btn_cancel: finish(); break; } } public void clearErrorAlerts() { alertAddLotAmount.setVisibility(View.GONE); lyMovementDate.setErrorEnabled(false); lyMovementReason.setErrorEnabled(false); lyMovementQuantity.setErrorEnabled(false); lyMovementSignature.setErrorEnabled(false); } protected boolean showErrors(StockMovementViewModel stockMovementViewModel) { MovementReasonManager.MovementType movementType = stockMovementViewModel.getTypeQuantityMap().keySet().iterator().next(); if (StringUtils.isBlank(stockMovementViewModel.getMovementDate())) { showMovementDateEmpty(); return true; } if (stockMovementViewModel.getReason() == null) { showMovementReasonEmpty(); return true; } if ((movementType.equals(MovementReasonManager.MovementType.ISSUE) || movementType.equals(MovementReasonManager.MovementType.NEGATIVE_ADJUST)) && StringUtils.isBlank(stockMovementViewModel.getTypeQuantityMap().get(movementType))) { showQuantityErrors(getResources().getString(R.string.msg_empty_quantity)); return true; } if (StringUtils.isBlank(stockMovementViewModel.getSignature())) { showSignatureErrors(getResources().getString(R.string.msg_empty_signature)); return true; } if (!stockMovementViewModel.validateQuantitiesNotZero()) { showQuantityErrors(getResources().getString(R.string.msg_entries_error)); return true; } if (quantityIsLargerThanSoh(stockMovementViewModel.getTypeQuantityMap().get(movementType), movementType)) { showQuantityErrors(getResources().getString(R.string.msg_invalid_quantity)); return true; } if (!checkSignature(stockMovementViewModel.getSignature())) { showSignatureErrors(getString(R.string.hint_signature_error_message)); return true; } if (validateLotMovement(movementType)) return true; return showLotError(); } private boolean validateLotMovement(MovementReasonManager.MovementType movementType) { if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_lot_management)) { if (this.stockMovementViewModel.isLotEmpty() && !isKit &&(movementType.equals(MovementReasonManager.MovementType.RECEIVE) || movementType.equals(MovementReasonManager.MovementType.POSITIVE_ADJUST))) { showEmptyLotError(); return true; } if (!this.stockMovementViewModel.hasChangedLot() && !isKit && (movementType.equals(MovementReasonManager.MovementType.RECEIVE) || movementType.equals(MovementReasonManager.MovementType.POSITIVE_ADJUST))) { showLotQuantityError(); return true; } } return false; } private void showLotQuantityError() { clearErrorAlerts(); alertAddLotAmount.setVisibility(View.VISIBLE); } private boolean checkSignature(String signature) { return signature.length() >= 2 && signature.length() <= 5 && signature.matches("\\D+"); } private boolean quantityIsLargerThanSoh(String quantity, MovementReasonManager.MovementType type) { if (MovementReasonManager.MovementType.ISSUE.equals(type) || MovementReasonManager.MovementType.NEGATIVE_ADJUST.equals(type)) { return Long.parseLong(quantity) > previousMovement.getStockOnHand(); } return false; } private void showEmptyLotError() { clearErrorAlerts(); ToastUtil.show(getResources().getString(R.string.empty_lot_warning)); } @Override public void showMovementDateEmpty() { clearErrorAlerts(); lyMovementDate.setError(getResources().getString(R.string.msg_empty_movement_date)); etMovementDate.getBackground().setColorFilter(getResources().getColor(R.color.color_red), PorterDuff.Mode.SRC_ATOP); } @Override public void showMovementReasonEmpty() { clearErrorAlerts(); lyMovementReason.setError(getResources().getString(R.string.msg_empty_movement_reason)); etMovementReason.getBackground().setColorFilter(getResources().getColor(R.color.color_red), PorterDuff.Mode.SRC_ATOP); } @Override public void showQuantityErrors(String errorMsg) { clearErrorAlerts(); lyMovementQuantity.setError(errorMsg); etMovementQuantity.getBackground().setColorFilter(getResources().getColor(R.color.color_red), PorterDuff.Mode.SRC_ATOP); } private void showSignatureErrors(String string) { clearErrorAlerts(); lyMovementSignature.setError(string); etMovementSignature.getBackground().setColorFilter(getResources().getColor(R.color.color_red), PorterDuff.Mode.SRC_ATOP); } @Override public boolean showLotError() { clearErrorAlerts(); int position = lotMovementAdapter.validateAll(); if (position >= 0) { lotMovementRecycleView.scrollToPosition(position); return true; } return false; } @Override public void goToStockCard() { setResult(RESULT_OK); finish(); } class MovementDateListener implements DatePickerDialog.OnDateSetListener { private Date previousMovementDate; private StockMovementViewModel model; public MovementDateListener(StockMovementViewModel model, Date previousMovementDate) { this.previousMovementDate = previousMovementDate; this.model = model; } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Date chosenDate = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime(); if (validateStockMovementDate(previousMovementDate, chosenDate)) { etMovementDate.setText(DateUtil.formatDate(chosenDate)); model.setMovementDate(DateUtil.formatDate(chosenDate)); } else { ToastUtil.show(R.string.msg_invalid_stock_movement_date); } } private boolean validateStockMovementDate(Date previousMovementDate, Date chosenDate) { Calendar today = GregorianCalendar.getInstance(); return previousMovementDate == null || !previousMovementDate.after(chosenDate) && !chosenDate.after(today.getTime()); } } class MovementTypeOnClickListener implements AdapterView.OnItemClickListener { StockMovementViewModel movementViewModel; public MovementTypeOnClickListener(StockMovementViewModel movementViewModel) { this.movementViewModel = movementViewModel; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { etMovementReason.setText(reasonListStr[position]); stockMovementViewModel.setReason(movementReasons.get(position)); reasonsDialog.dismiss(); } } }
package com.github.dreamhead.moco; import com.github.dreamhead.moco.action.MocoAsyncAction; import com.github.dreamhead.moco.action.MocoRequestAction; import com.github.dreamhead.moco.config.MocoContextConfig; import com.github.dreamhead.moco.config.MocoFileRootConfig; import com.github.dreamhead.moco.config.MocoRequestConfig; import com.github.dreamhead.moco.config.MocoResponseConfig; import com.github.dreamhead.moco.extractor.*; import com.github.dreamhead.moco.handler.*; import com.github.dreamhead.moco.handler.failover.DefaultFailoverExecutor; import com.github.dreamhead.moco.handler.failover.Failover; import com.github.dreamhead.moco.handler.failover.FailoverStrategy; import com.github.dreamhead.moco.handler.proxy.ProxyConfig; import com.github.dreamhead.moco.internal.ActualHttpServer; import com.github.dreamhead.moco.internal.ActualSocketServer; import com.github.dreamhead.moco.matcher.*; import com.github.dreamhead.moco.monitor.*; import com.github.dreamhead.moco.procedure.LatencyProcedure; import com.github.dreamhead.moco.resource.ContentResource; import com.github.dreamhead.moco.resource.Resource; import com.github.dreamhead.moco.resource.reader.ExtractorVariable; import com.github.dreamhead.moco.resource.reader.Variable; import com.github.dreamhead.moco.util.URLs; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.net.HttpHeaders; import java.io.File; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import static com.github.dreamhead.moco.extractor.Extractors.extractor; import static com.github.dreamhead.moco.handler.ResponseHandlers.responseHandler; import static com.github.dreamhead.moco.resource.ResourceFactory.*; import static com.github.dreamhead.moco.util.Preconditions.checkNotNullOrEmpty; import static com.google.common.base.Optional.of; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.Maps.transformEntries; import static com.google.common.net.HttpHeaders.SET_COOKIE; import static java.lang.String.format; public class Moco { public static HttpServer httpserver(final int port, final MocoConfig... configs) { checkArgument(port > 0, "Port must be greater than zero"); return ActualHttpServer.createQuietServer(of(port), configs); } public static HttpServer httpserver(final int port, final MocoMonitor monitor, final MocoConfig... configs) { checkArgument(port > 0, "Port must be greater than zero"); return ActualHttpServer.createHttpServerWithMonitor(of(port), checkNotNull(monitor, "Monitor should not be null"), configs); } public static HttpServer httpserver(final int port, final MocoMonitor monitor, final MocoMonitor monitor2, final MocoMonitor... monitors) { checkArgument(port > 0, "Port must be greater than zero"); return ActualHttpServer.createHttpServerWithMonitor(of(port), mergeMonitor(monitor, monitor2, monitors)); } private static MocoMonitor mergeMonitor(MocoMonitor monitor, MocoMonitor monitor2, MocoMonitor[] monitors) { MocoMonitor[] targetMonitors = new MocoMonitor[2 + monitors.length]; targetMonitors[0] = checkNotNull(monitor, "Monitor should not be null"); targetMonitors[1] = checkNotNull(monitor2, "Monitor should not be null"); if (monitors.length > 0) { System.arraycopy(monitors, 0, targetMonitors, 2, monitors.length); } return new CompositeMonitor(targetMonitors); } public static HttpServer httpserver(final MocoConfig... configs) { return ActualHttpServer.createQuietServer(Optional.<Integer>absent(), configs); } public static HttpServer httpserver(final MocoMonitor monitor, final MocoConfig... configs) { return ActualHttpServer.createHttpServerWithMonitor(Optional.<Integer>absent(), checkNotNull(monitor, "Monitor should not be null"), configs); } public static HttpsServer httpsServer(final int port, final HttpsCertificate certificate, final MocoConfig... configs) { checkArgument(port > 0, "Port must be greater than zero"); return ActualHttpServer.createHttpsQuietServer(of(port), checkNotNull(certificate, "Certificate should not be null"), configs); } public static HttpsServer httpsServer(final int port, final HttpsCertificate certificate, final MocoMonitor monitor, final MocoConfig... configs) { checkArgument(port > 0, "Port must be greater than zero"); return ActualHttpServer.createHttpsServerWithMonitor(of(port), checkNotNull(certificate, "Certificate should not be null"), checkNotNull(monitor, "Monitor should not be null"), configs); } public static HttpsServer httpsServer(final HttpsCertificate certificate, final MocoConfig... configs) { return ActualHttpServer.createHttpsQuietServer(Optional.<Integer>absent(), checkNotNull(certificate, "Certificate should not be null"), configs); } public static HttpsServer httpsServer(final HttpsCertificate certificate, final MocoMonitor monitor, final MocoConfig... configs) { return ActualHttpServer.createHttpsServerWithMonitor(Optional.<Integer>absent(), checkNotNull(certificate, "Certificate should not be null"), checkNotNull(monitor, "Monitor should not be null"), configs); } public static HttpServer httpsServer(final int port, final HttpsCertificate certificate, final MocoMonitor monitor, final MocoMonitor monitor2, final MocoMonitor... monitors) { checkArgument(port > 0, "Port must be greater than zero"); return ActualHttpServer.createHttpsServerWithMonitor(of(port), checkNotNull(certificate, "Certificate should not be null"), mergeMonitor(monitor, monitor2, monitors)); } public static SocketServer socketServer(int port) { return ActualSocketServer.createQuietServer(of(port)); } public static MocoConfig context(final String context) { return new MocoContextConfig(checkNotNullOrEmpty(context, "Context should not be null")); } public static MocoConfig request(final RequestMatcher matcher) { return new MocoRequestConfig(checkNotNull(matcher, "Request matcher should not be null")); } public static MocoConfig response(final ResponseHandler handler) { return new MocoResponseConfig(checkNotNull(handler, "Response handler should not be null")); } public static MocoConfig fileRoot(final String fileRoot) { return new MocoFileRootConfig(checkNotNullOrEmpty(fileRoot, "File root should not be null")); } public static MocoMonitor log() { return new LogMonitor(new DefaultLogFormatter(), new StdLogWriter()); } public static MocoMonitor log(final String filename) { return new LogMonitor(new DefaultLogFormatter(), new FileLogWriter(checkNotNullOrEmpty(filename, "Filename should not be null or empty"))); } public static RequestMatcher by(final String content) { return by(text(checkNotNullOrEmpty(content, "Content should not be null"))); } public static RequestMatcher by(final Resource resource) { checkNotNull(resource, "resource should not be null"); return eq(extractor(resource.id()), resource); } public static <T> RequestMatcher eq(final RequestExtractor<T> extractor, final String expected) { return eq(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNullOrEmpty(expected, "Expected content should not be null"))); } public static <T> RequestMatcher eq(final RequestExtractor<T> extractor, final Resource expected) { return new EqRequestMatcher<T>(checkNotNull(extractor, "Extractor should not be null"), checkNotNull(expected, "Expected content should not be null")); } public static RequestMatcher match(final Resource resource) { checkNotNull(resource, "Resource should not be null"); return match(extractor(resource.id()), resource); } public static <T> RequestMatcher match(final RequestExtractor<T> extractor, final String expected) { return match(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNullOrEmpty(expected, "Expected content should not be null"))); } private static <T> RequestMatcher match(final RequestExtractor<T> extractor, final Resource expected) { return new MatchMatcher<T>(checkNotNull(extractor, "Extractor should not be null"), checkNotNull(expected, "Expected resource should not be null")); } public static <T> RequestMatcher exist(final RequestExtractor<T> extractor) { return new ExistMatcher<T>(checkNotNull(extractor, "Extractor should not be null")); } public static RequestMatcher startsWith(final Resource resource) { checkNotNull(resource, "Resource should not be null"); return startsWith(extractor(resource.id()), resource); } public static <T> RequestMatcher startsWith(RequestExtractor<T> extractor, String expected) { return startsWith(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNullOrEmpty(expected, "Expected resource should not be null"))); } private static <T> RequestMatcher startsWith(RequestExtractor<T> extractor, Resource resource) { return new StartsWithMatcher<T>(checkNotNull(extractor, "Extractor should not be null"), checkNotNull(resource, "Expected resource should not be null")); } public static RequestMatcher endsWith(final Resource resource) { checkNotNull(resource, "Resource should not be null"); return endsWith(extractor(resource.id()), resource); } public static <T> RequestMatcher endsWith(final RequestExtractor<T> extractor, final String expected) { return endsWith(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNullOrEmpty(expected, "Expected resource should not be null"))); } private static <T> RequestMatcher endsWith(final RequestExtractor<T> extractor, final Resource resource) { return new EndsWithMatcher<T>(checkNotNull(extractor, "Extractor should not be null"), checkNotNull(resource, "Expected resource should not be null")); } public static RequestMatcher contain(final Resource resource) { checkNotNull(resource, "Resource should not be null"); return contain(extractor(resource.id()), resource); } public static <T> RequestMatcher contain(final RequestExtractor<T> extractor, final String expected) { return contain(checkNotNull(extractor, "Extractor should not be null"), text(checkNotNullOrEmpty(expected, "Expected resource should not be null"))); } private static <T> RequestMatcher contain(final RequestExtractor<T> extractor, final Resource resource) { return new ContainMatcher<T>(checkNotNull(extractor, "Extractor should not be null"), checkNotNull(resource, "Expected resource should not be null")); } public static RequestMatcher and(final RequestMatcher... matchers) { return new AndRequestMatcher(copyOf(matchers)); } public static RequestMatcher or(final RequestMatcher... matchers) { return new OrRequestMatcher(copyOf(matchers)); } public static RequestMatcher not(final RequestMatcher matcher) { return new NotRequestMatcher(checkNotNull(matcher, "Expected matcher should not be null")); } public static ContentResource text(final String text) { return textResource(checkNotNullOrEmpty(text, "Text should not be null")); } public static ResponseHandler with(final String text) { return with(text(checkNotNullOrEmpty(text, "Text should not be null"))); } public static ResponseHandler with(final Resource resource) { return responseHandler(checkNotNull(resource, "Resource should not be null")); } public static ResponseHandler with(final MocoProcedure procedure) { return new ProcedureResponseHandler(checkNotNull(procedure, "Procedure should not be null")); } public static Resource uri(final String uri) { return uriResource(checkNotNull(uri, "URI should not be null")); } public static Resource method(final String httpMethod) { return methodResource(checkNotNullOrEmpty(httpMethod, "HTTP method should not be null")); } public static RequestExtractor<String> header(final String header) { return new HeaderRequestExtractor(checkNotNullOrEmpty(header, "Header name should not be null")); } public static ResponseHandler header(final String name, final String value) { return header(checkNotNullOrEmpty(name, "Header name should not be null"), text(checkNotNullOrEmpty(value, "Header value should not be null"))); } public static ResponseHandler header(final String name, final Resource value) { return new HeaderResponseHandler(checkNotNullOrEmpty(name, "Header name should not be null"), checkNotNull(value, "Header value should not be null")); } public static RequestExtractor<String> cookie(final String key) { return new CookieRequestExtractor(checkNotNullOrEmpty(key, "Cookie key should not be null")); } public static ResponseHandler cookie(final String key, final String value) { return cookie(checkNotNullOrEmpty(key, "Cookie key should not be null"), text(checkNotNullOrEmpty(value, "Cookie value should not be null"))); } public static ResponseHandler cookie(final String key, final Resource resource) { return header(SET_COOKIE, cookieResource( checkNotNullOrEmpty(key, "Cookie key should not be null"), checkNotNull(resource, "Cookie value should not be null"))); } public static RequestExtractor<String> form(final String key) { return new FormRequestExtractor(checkNotNullOrEmpty(key, "Form key should not be null")); } public static LatencyProcedure latency(final long millis) { return latency(millis, TimeUnit.MILLISECONDS); } public static LatencyProcedure latency(final long duration, final TimeUnit unit) { checkArgument(duration > 0, "Latency must be greater than zero"); return new LatencyProcedure(duration, checkNotNull(unit, "Time unit should not be null")); } public static RequestExtractor<String> query(final String param) { return new ParamRequestExtractor(checkNotNullOrEmpty(param, "Query parameter should not be null")); } public static XPathRequestExtractor xpath(final String xpath) { return new XPathRequestExtractor(checkNotNullOrEmpty(xpath, "XPath should not be null")); } public static RequestMatcher xml(final Resource resource) { checkNotNull(resource, "Resource should not be null"); return new XmlRequestMatcher(extractor(resource.id()), resource); } public static RequestMatcher json(final Resource resource) { checkNotNull(resource, "JSON should not be null"); return new JsonRequestMatcher(extractor(resource.id()), resource); } public static JsonPathRequestExtractor jsonPath(final String jsonPath) { return new JsonPathRequestExtractor(checkNotNullOrEmpty(jsonPath, "JsonPath should not be null")); } public static ResponseHandler seq(final String... contents) { checkArgument(contents.length > 0, "seq contents should not be null"); return seq(FluentIterable.from(copyOf(contents)).transform(textToResource()).toList()); } public static ResponseHandler seq(final Resource... contents) { checkArgument(contents.length > 0, "seq contents should not be null"); return seq(FluentIterable.from(copyOf(contents)).transform(resourceToResourceHandler()).toList()); } public static ResponseHandler seq(final ResponseHandler... handlers) { checkArgument(handlers.length > 0, "seq contents should not be null"); return seq(copyOf(handlers)); } private static ResponseHandler seq(ImmutableList<ResponseHandler> handlers) { checkArgument(handlers.size() > 0, "seq contents should not be null"); return new SequenceContentHandler(handlers); } public static ContentResource file(final String filename) { return file(text(checkNotNullOrEmpty(filename, "Filename should not be null"))); } public static ContentResource file(final Resource filename) { return file(checkNotNull(filename, "Filename should not be null"), Optional.<Charset>absent()); } public static ContentResource file(final String filename, Charset charset) { return file(text(checkNotNullOrEmpty(filename, "Filename should not be null")), of(checkNotNull(charset, "Charset should not be null"))); } public static ContentResource file(final Resource filename, Charset charset) { return file(checkNotNull(filename, "Filename should not be null"), of(checkNotNull(charset, "Charset should not be null"))); } public static ContentResource file(final String filename, Optional<Charset> charset) { return file(text(checkNotNullOrEmpty(filename, "Filename should not be null")), checkNotNull(charset, "Charset should not be null")); } public static ContentResource file(final Resource filename, Optional<Charset> charset) { return fileResource(checkNotNull(filename, "Filename should not be null"), checkNotNull(charset, "Charset should not be null"), Optional.<MocoConfig>absent()); } public static ContentResource pathResource(final String filename) { return pathResource(text(checkNotNullOrEmpty(filename, "Filename should not be null"))); } public static ContentResource pathResource(final Resource filename) { return pathResource(checkNotNull(filename, "Filename should not be null"), Optional.<Charset>absent()); } public static ContentResource pathResource(final String filename, Charset charset) { return pathResource(text(checkNotNullOrEmpty(filename, "Filename should not be null")), of(checkNotNull(charset, "Charset should not be null"))); } public static ContentResource pathResource(final Resource filename, Charset charset) { return pathResource(checkNotNull(filename, "Filename should not be null"), of(checkNotNull(charset, "Charset should not be null"))); } public static ContentResource pathResource(final String filename, Optional<Charset> charset) { return pathResource(text(checkNotNullOrEmpty(filename, "Filename should not be null")), checkNotNull(charset, "Charset should not be null")); } public static ContentResource pathResource(final Resource filename, Optional<Charset> charset) { return classpathFileResource(checkNotNull(filename, "Filename should not be null"), checkNotNull(charset, "Charset should not be null")); } public static Resource version(final Resource resource) { return versionResource(checkNotNull(resource, "Version should not be null")); } public static Resource version(final String version) { return versionResource(HttpProtocolVersion.versionOf(checkNotNullOrEmpty(version, "Version should not be null"))); } public static Resource version(final HttpProtocolVersion version) { return versionResource(checkNotNull(version, "Version should not be null")); } public static ResponseHandler status(final int code) { checkArgument(code > 0, "Status code must be greater than zero"); return new StatusCodeResponseHandler(code); } public static ResponseHandler proxy(final String url) { return proxy(checkNotNullOrEmpty(url, "URL should not be null"), Failover.DEFAULT_FAILOVER); } public static ResponseHandler proxy(final String url, final Failover failover) { return new ProxyResponseHandler(URLs.toUrl(checkNotNullOrEmpty(url, "URL should not be null")), checkNotNull(failover, "Failover should not be null")); } public static ResponseHandler proxy(final ProxyConfig proxyConfig) { return proxy(checkNotNull(proxyConfig), Failover.DEFAULT_FAILOVER); } public static ResponseHandler proxy(final ProxyConfig proxyConfig, final Failover failover) { return new ProxyBatchResponseHandler(checkNotNull(proxyConfig), checkNotNull(failover)); } public static ProxyConfig.Builder from(final String localBase) { return ProxyConfig.builder(checkNotNullOrEmpty(localBase, "Local base should not be null")); } public static Resource template(final String template) { return template(text(checkNotNullOrEmpty(template, "Template should not be null"))); } public static Resource template(final String template, final String name, final String value) { return template(text(checkNotNullOrEmpty(template, "Template should not be null")), checkNotNullOrEmpty(name, "Template variable name should not be null"), checkNotNullOrEmpty(value, "Template variable value should not be null")); } public static Resource template(final String template, final String name1, final String value1, final String name2, final String value2) { return template(text(checkNotNullOrEmpty(template, "Template should not be null")), checkNotNullOrEmpty(name1, "Template variable name should not be null"), checkNotNullOrEmpty(value1, "Template variable value should not be null"), checkNotNullOrEmpty(name2, "Template variable name should not be null"), checkNotNullOrEmpty(value2, "Template variable value should not be null")); } public static Resource template(final ContentResource resource) { return template(checkNotNull(resource, "Template should not be null"), ImmutableMap.<String, RequestExtractor<?>>of()); } public static Resource template(final ContentResource template, final String name, final String value) { return template(checkNotNull(template, "Template should not be null"), checkNotNullOrEmpty(name, "Template variable name should not be null"), var(checkNotNullOrEmpty(value, "Template variable value should not be null"))); } public static Resource template(final ContentResource template, final String name1, final String value1, final String name2, final String value2) { return template(checkNotNull(template, "Template should not be null"), checkNotNullOrEmpty(name1, "Template variable name should not be null"), var(checkNotNullOrEmpty(value1, "Template variable value should not be null")), checkNotNullOrEmpty(name2, "Template variable name should not be null"), var(checkNotNullOrEmpty(value2, "Template variable value should not be null"))); } public static <T> Resource template(final String template, final String name, final RequestExtractor<T> extractor) { return template(text(checkNotNullOrEmpty(template, "Template should not be null")), checkNotNullOrEmpty(name, "Template variable name should not be null"), checkNotNull(extractor, "Template variable extractor should not be null")); } public static <ExtractorType1, ExtractorType2> Resource template(final String template, final String name1, final RequestExtractor<ExtractorType1> extractor1, final String name2, final RequestExtractor<ExtractorType2> extractor2) { return template(text(checkNotNullOrEmpty(template, "Template should not be null")), checkNotNullOrEmpty(name1, "Template variable name should not be null"), checkNotNull(extractor1, "Template variable extractor should not be null"), checkNotNullOrEmpty(name2, "Template variable name should not be null"), checkNotNull(extractor2, "Template variable extractor should not be null")); } public static <T> Resource template(final ContentResource template, final String name, final RequestExtractor<T> extractor) { return templateResource(checkNotNull(template, "Template should not be null"), ImmutableMap.of(checkNotNullOrEmpty(name, "Template variable name should not be null"), new ExtractorVariable<T>(checkNotNull(extractor, "Template variable extractor should not be null"))) ); } public static <ExtractorType1, ExtractorType2> Resource template(final ContentResource template, final String name1, final RequestExtractor<ExtractorType1> extractor1, final String name2, final RequestExtractor<ExtractorType2> extractor2) { return templateResource(checkNotNull(template, "Template should not be null"), ImmutableMap.of(checkNotNullOrEmpty(name1, "Template variable name should not be null"), new ExtractorVariable<ExtractorType1>(checkNotNull(extractor1, "Template variable extractor should not be null")), checkNotNullOrEmpty(name2, "Template variable name should not be null"), new ExtractorVariable<ExtractorType2>(checkNotNull(extractor2, "Template variable extractor should not be null"))) ); } public static Resource template(final String template, final ImmutableMap<String, ? extends RequestExtractor<?>> variables) { return template(text(checkNotNull(template, "Template should not be null")), checkNotNull(variables, "Template variable should not be null")); } public static Resource template(final ContentResource template, final ImmutableMap<String, ? extends RequestExtractor<?>> variables) { return templateResource(checkNotNull(template, "Template should not be null"), toVariables(checkNotNull(variables, "Template variable should not be null"))); } public static RequestExtractor<Object> var(final Object text) { return new PlainExtractor(checkNotNull(text, "Template variable should not be null or empty")); } public static Failover failover(final String file) { return new Failover(failoverExecutor(checkNotNullOrEmpty(file, "Filename should not be null")), FailoverStrategy.FAILOVER); } private static DefaultFailoverExecutor failoverExecutor(final String file) { return new DefaultFailoverExecutor(new File(checkNotNullOrEmpty(file, "Filename should not be null"))); } public static Failover playback(final String file) { return new Failover(failoverExecutor(checkNotNullOrEmpty(file, "Filename should not be null")), FailoverStrategy.PLAYBACK); } public static MocoEventTrigger complete(final MocoEventAction action) { return new MocoEventTrigger(MocoEvent.COMPLETE, checkNotNull(action, "Action should not be null")); } public static MocoEventAction async(final MocoEventAction action) { return async(checkNotNull(action, "Action should not be null"), latency(LatencyProcedure.DEFAULT_LATENCY)); } public static MocoEventAction async(final MocoEventAction action, final LatencyProcedure procedure) { return new MocoAsyncAction(checkNotNull(action, "Action should not be null"), checkNotNull(procedure, "Procedure should not be null")); } public static MocoEventAction get(final String url) { return new MocoRequestAction(checkNotNullOrEmpty(url, "URL should not be null"), "GET", Optional.<ContentResource>absent()); } public static MocoEventAction post(final String url, final ContentResource content) { return new MocoRequestAction(checkNotNullOrEmpty(url, "URL should not be null"), "POST", of(checkNotNull(content, "Content should not be null"))); } public static MocoEventAction post(final String url, final String content) { return post(checkNotNullOrEmpty(url, "URL should not be null"), text(checkNotNullOrEmpty(content, "Content should not be null"))); } public static ResponseHandler attachment(final String filename, final Resource resource) { return new AndResponseHandler(ImmutableList.of( header(HttpHeaders.CONTENT_DISPOSITION, format("attachment; filename=%s", checkNotNullOrEmpty(filename, "Filename should not be null or empty"))), with(checkNotNull(resource, "Resource should not be null")))); } private static Function<String, ResponseHandler> textToResource() { return new Function<String, ResponseHandler>() { @Override public ResponseHandler apply(String content) { return with(text(content)); } }; } private static Function<Resource, ResponseHandler> resourceToResourceHandler() { return new Function<Resource, ResponseHandler>() { @Override public ResponseHandler apply(Resource content) { return with(content); } }; } private static ImmutableMap<String, Variable> toVariables(final ImmutableMap<String, ? extends RequestExtractor<?>> variables) { return ImmutableMap.copyOf(transformEntries(variables, toVariable())); } private static Maps.EntryTransformer<String, RequestExtractor<?>, Variable> toVariable() { return new Maps.EntryTransformer<String, RequestExtractor<?>, Variable>() { @Override @SuppressWarnings("unchecked") public Variable transformEntry(String key, RequestExtractor<?> value) { return new ExtractorVariable(value); } }; } private Moco() { } }
package com.axelor.apps.account.ebics.web; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.xmlbeans.impl.common.IOUtil; import com.axelor.apps.ReportFactory; import com.axelor.apps.account.db.EbicsBank; import com.axelor.apps.account.db.EbicsCertificate; import com.axelor.apps.account.db.EbicsUser; import com.axelor.apps.account.db.repo.BankOrderFileFormatRepository; import com.axelor.apps.account.db.repo.EbicsBankRepository; import com.axelor.apps.account.db.repo.EbicsCertificateRepository; import com.axelor.apps.account.db.repo.EbicsUserRepository; import com.axelor.apps.account.ebics.certificate.CertificateManager; import com.axelor.apps.account.ebics.service.EbicsCertificateService; import com.axelor.apps.account.ebics.service.EbicsService; import com.axelor.apps.account.exception.IExceptionMessage; import com.axelor.apps.account.report.IReport; import com.axelor.apps.report.engine.ReportSettings; import com.axelor.data.Listener; import com.axelor.data.xml.XMLImporter; import com.axelor.db.Model; import com.axelor.exception.AxelorException; import com.axelor.exception.db.IException; import com.axelor.i18n.I18n; import com.axelor.meta.MetaFiles; import com.axelor.meta.db.MetaFile; import com.axelor.meta.schema.actions.ActionView; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.axelor.rpc.Context; import com.google.common.base.Joiner; import com.google.common.io.Files; import com.google.inject.Inject; import com.google.inject.persist.Transactional; public class EbicsController { @Inject private EbicsUserRepository ebicsUserRepo; @Inject private EbicsService ebicsService; @Inject private EbicsBankRepository bankRepo; @Inject private EbicsCertificateService certificateService; @Inject private EbicsCertificateRepository certificateRepo; @Transactional public void generateCertificate(ActionRequest request, ActionResponse response){ EbicsUser ebicsUser = ebicsUserRepo.find(request.getContext().asType(EbicsUser.class).getId()); if (ebicsUser.getStatusSelect() != EbicsUserRepository.STATUS_WAITING_CERTIFICATE_CONFIG && ebicsUser.getStatusSelect() != EbicsUserRepository.STATUS_CERTIFICATES_SHOULD_BE_RENEW) { return; } CertificateManager cm = new CertificateManager(ebicsUser); try { cm.create(); ebicsUser.setStatusSelect(EbicsUserRepository.STATUS_WAITING_SENDING_SIGNATURE_CERTIFICATE); ebicsUserRepo.save(ebicsUser); } catch (GeneralSecurityException | IOException e) { e.printStackTrace(); } response.setReload(true); } public void generateDn(ActionRequest request, ActionResponse response){ EbicsUser ebicsUser = ebicsUserRepo.find(request.getContext().asType(EbicsUser.class).getId()); response.setValue("dn", ebicsService.makeDN(ebicsUser)); } public void sendINIRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { ebicsService.sendINIRequest(ebicsUser, null); }catch (AxelorException e) { e.printStackTrace(); response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } public void sendHIARequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { ebicsService.sendHIARequest(ebicsUser, null); }catch (AxelorException e) { e.printStackTrace(); response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } public void sendHPBRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { X509Certificate[] certificates = ebicsService.sendHPBRequest(ebicsUser, null); confirmCertificates(ebicsUser, certificates, response); }catch (AxelorException e) { e.printStackTrace(); response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } private void confirmCertificates(EbicsUser user, X509Certificate[] certificates, ActionResponse response) { try { EbicsBank bank = user.getEbicsPartner().getEbicsBank(); response.setView(ActionView.define("Confirm certificates") .model("com.axelor.apps.account.db.EbicsCertificate") .add("form", "ebics-certificate-confirmation-form") .param("show-toolbar", "false") .param("show-confirm", "false") .param("popup-save", "false") .param("popup", "true") .context("ebicsBank", bank) .context("url", bank.getUrl()) .context("hostId", bank.getHostId()) .context("e002Hash", DigestUtils.sha1Hex(certificates[0].getEncoded()).toUpperCase()) .context("x002Hash", DigestUtils.sha1Hex(certificates[1].getEncoded()).toUpperCase()) .context("certificateE002", certificateService.convertToPEMString(certificates[0])) .context("certificateX002", certificateService.convertToPEMString(certificates[1])).map()); }catch(Exception e) { response.setFlash("Error in certificate confirmation "); } } public void sendSPRRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { ebicsService.sendSPRRequest(ebicsUser, null); }catch (AxelorException e) { e.printStackTrace(); response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } public void sendFULRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { EbicsBank ebicsBank = ebicsUser.getEbicsPartner().getEbicsBank(); MetaFile testMetaFile = ebicsBank.getTestFile(); if(ebicsBank.getTestMode() && testMetaFile != null) { ebicsService.sendFULRequest(ebicsUser, null, MetaFiles.getPath(testMetaFile).toFile(), BankOrderFileFormatRepository.FILE_FORMAT_pain_001_001_02_SCT); } else { response.setFlash(I18n.get(IExceptionMessage.EBICS_TEST_MODE_NOT_ENABLED)); } }catch (AxelorException e) { response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } public void sendFDLRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { ebicsService.sendFDLRequest(ebicsUser, null, null, null, BankOrderFileFormatRepository.FILE_FORMAT_pain_001_001_02_SCT); }catch (AxelorException e) { response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } public void sendHTDRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { ebicsService.sendHTDRequest(ebicsUser, null, null, null); }catch (AxelorException e) { response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } public void sendPTKRequest(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = ebicsUserRepo.find( request.getContext().asType(EbicsUser.class).getId()); try { ebicsService.sendPTKRequest(ebicsUser, null, null, null); }catch (AxelorException e) { response.setFlash(stripClass(e.getLocalizedMessage())); } response.setReload(true); } private String stripClass(String msg) { return msg.replace(AxelorException.class.getName() + ":", ""); } public void addCertificates(ActionRequest request, ActionResponse response) throws AxelorException { Context context = request.getContext(); EbicsBank bank = (EbicsBank)context.get("ebicsBank"); bank = bankRepo.find(bank.getId()); try { X509Certificate certificate = certificateService.convertToCertificate((String)context.get("certificateE002")); certificateService.createCertificate(certificate, bank, EbicsCertificateRepository.TYPE_ENCRYPTION); certificate = certificateService.convertToCertificate((String)context.get("certificateX002")); certificateService.createCertificate(certificate, bank, EbicsCertificateRepository.TYPE_AUTHENTICATION); } catch (CertificateException | IOException e) { e.printStackTrace(); throw new AxelorException(I18n.get("Error in adding bank certificate"), IException.CONFIGURATION_ERROR); } response.setCanClose(true); } public void loadCertificate(ActionRequest request, ActionResponse response) throws AxelorException, CertificateEncodingException, IOException { EbicsCertificate cert = request.getContext().asType(EbicsCertificate.class); cert = certificateRepo.find(cert.getId()); byte[] certs = cert.getCertificate(); if (certs != null && certs.length > 0) { X509Certificate certificate = EbicsCertificateService.getCertificate(certs, cert.getTypeSelect()); cert = certificateService.updateCertificate(certificate, cert); response.setValue("validFrom", cert.getValidFrom()); response.setValue("validTo", cert.getValidTo()); response.setValue("issuer", cert.getIssuer()); response.setValue("subject", cert.getSubject()); response.setValue("publicKeyModulus", cert.getPublicKeyModulus()); response.setValue("publicKeyExponent", cert.getPublicKeyExponent()); response.setValue("fullName", cert.getFullName()); response.setValue("pemString", cert.getPemString()); response.setValue("sha2has", cert.getSha2has()); } } public void updateEditionDate(ActionRequest request, ActionResponse response) { EbicsUser ebicsUser = request.getContext().asType(EbicsUser.class); ebicsUser = ebicsUserRepo.find(ebicsUser.getId()); certificateService.updateEditionDate(ebicsUser); response.setReload(true); } @Transactional public void importEbicsUsers(ActionRequest request, ActionResponse response) { String config = "/data-import/import-ebics-user-config.xml"; try { InputStream inputStream = this.getClass().getResourceAsStream(config); File configFile = File.createTempFile("config", ".xml"); FileOutputStream fout = new FileOutputStream(configFile); IOUtil.copyCompletely(inputStream, fout); Path path = MetaFiles.getPath((String) ((Map) request.getContext().get("dataFile")).get("filePath")); File tempDir = Files.createTempDir(); File importFile = new File(tempDir, "ebics-user.xml"); Files.copy(path.toFile(), importFile); XMLImporter importer = new XMLImporter(configFile.getAbsolutePath(), tempDir.getAbsolutePath()); final StringBuilder log = new StringBuilder(); Listener listner = new Listener() { @Override public void imported(Integer imported, Integer total) { log.append("Total records: " + total + ", Total imported: " + total); } @Override public void imported(Model arg0) { } @Override public void handle(Model arg0, Exception err) { log.append("Error in import: " + err.getStackTrace().toString()); } }; importer.addListener(listner); importer.run(); FileUtils.forceDelete(configFile); FileUtils.forceDelete(tempDir); response.setValue("importLog", log.toString()); } catch (IOException e) { e.printStackTrace(); } } public void printCertificates(ActionRequest request, ActionResponse response) throws AxelorException { EbicsUser ebicsUser = request.getContext().asType(EbicsUser.class); ArrayList<Long> certIds = new ArrayList<Long>(); if (ebicsUser.getA005Certificate() != null) { certIds.add(ebicsUser.getA005Certificate().getId()); } if (ebicsUser.getE002Certificate() != null) { certIds.add(ebicsUser.getE002Certificate().getId()); } if (ebicsUser.getX002Certificate() != null) { certIds.add(ebicsUser.getX002Certificate().getId()); } if (certIds.isEmpty()) { throw new AxelorException(I18n.get(IExceptionMessage.EBICS_MISSING_CERTIFICATES), 1); } String title = I18n.get("EbicsCertificate"); ReportSettings report = ReportFactory.createReport(IReport.EBICS_CERTIFICATE, title + "-${date}"); report.addParam("CertificateId", Joiner.on(",").join(certIds)); report.addParam("EbicsUserId", ebicsUser.getId()); report.toAttach(ebicsUser); report.generate(); response.setView(ActionView .define(title) .add("html", report.getFileLink()).map()); } }
package com.ejlchina.searcher.implement; import com.ejlchina.searcher.FieldOp; import com.ejlchina.searcher.operator.*; import java.util.regex.Pattern; /** * * @author Troy.Zhou @ 2021-11-01 * @since v3.0.0 */ public class DateValueCorrector { static final Pattern DATE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}"); static final Pattern DATE_HOUR_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}"); static final Pattern DATE_MINUTE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}"); private FieldOp lt = new LessThan(); private FieldOp ge = new GreaterEqual(); private FieldOp le = new LessEqual(); private FieldOp gt = new GreaterThan(); private FieldOp bt = new Between(); private FieldOp nb = new NotBetween(); /** * * @param dateValues * @param operator * @return */ public Object[] correct(Object[] dateValues, FieldOp operator) { if (operator.sameTo(lt) || operator.sameTo(ge)) { for (int i = 0; i < dateValues.length; i++) { dateValues[i] = dateValue(dateValues[i], true); } } if (operator.sameTo(le) || operator.sameTo(gt)) { for (int i = 0; i < dateValues.length; i++) { dateValues[i] = dateValue(dateValues[i], false); } } if (operator.sameTo(bt) || operator.sameTo(nb)) { if (dateValues.length > 0) { dateValues[0] = dateValue(dateValues[0], true); } if (dateValues.length > 1) { dateValues[1] = dateValue(dateValues[1], false); } } return dateValues; } protected Object dateValue(Object value, boolean roundDown) { if (value instanceof String) { String strValue = (String) value; if (DATE_PATTERN.matcher(strValue).matches()) { if (roundDown) { return strValue + " 00:00:00"; } else { return strValue + " 23:59:59"; } } else if (DATE_HOUR_PATTERN.matcher(strValue).matches()) { if (roundDown) { return strValue + ":00:00"; } else { return strValue + ":59:59"; } } else if (DATE_MINUTE_PATTERN.matcher(strValue).matches()) { if (roundDown) { return strValue + ":00"; } else { return strValue + ":59"; } } } return value; } public FieldOp getLt() { return lt; } public void setLt(FieldOp lt) { this.lt = lt; } public FieldOp getGe() { return ge; } public void setGe(FieldOp ge) { this.ge = ge; } public FieldOp getLe() { return le; } public void setLe(FieldOp le) { this.le = le; } public FieldOp getGt() { return gt; } public void setGt(FieldOp gt) { this.gt = gt; } public FieldOp getBt() { return bt; } public void setBt(FieldOp bt) { this.bt = bt; } public FieldOp getNb() { return nb; } public void setNb(FieldOp nb) { this.nb = nb; } }
package org.intermine.bio.dataconversion; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.apache.log4j.Logger; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.SAXParser; import org.intermine.util.StringUtil; import org.intermine.xml.full.Item; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * DataConverter to parse biogrid data into items * * Genetic interactions are labeled protein interactions, so we can't store or create any objects * until all experiments and interactors are processed. Holder objects are creating, storing the * data processed until the interactions are processed and we know the interactionType * * EXPERIMENT HOLDER * holds the experiment data until the interactions are processed. * interactions.interactionType tells us if this is a genetic or protein interaction, and thus * which type of experiment object to create * * INTERACTOR HOLDER * holds the identifier * could be gene or protein * * INTERACTION HOLDER * holds all interaction data until the entire entry is processed * * invalid experiments: * - human interactions use genbank IDs * - dmel gene doesn't resolve * - if any of the participants are invalid, we throw away the interaction * * @author Julie Sullivan */ public class BioGridConverter extends BioFileConverter { private static final Logger LOG = Logger.getLogger(BioGridConverter.class); protected IdResolverFactory resolverFactory; private Map<String, String> terms = new HashMap<String, String>(); private Map<String, String> pubs = new HashMap<String, String>(); /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public BioGridConverter(ItemWriter writer, Model model) { super(writer, model, "BioGRID", "BioGRID interaction data set"); // only construct factory here so can be replaced by mock factory in tests resolverFactory = new FlyBaseIdResolverFactory(); } /** * {@inheritDoc} */ public void process(Reader reader) throws Exception { BioGridHandler handler = new BioGridHandler(); try { SAXParser.parse(new InputSource(reader), handler); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Handles xml file */ class BioGridHandler extends DefaultHandler { private Map<String, Item> genes = new HashMap<String, Item>(); //private Map<String, Item> proteins = new HashMap<String, Item>(); // [participant id] [identifier or accession] private Map<String, InteractorHolder> ids = new HashMap<String, InteractorHolder>(); // [id][experimentholder] private Map<String, ExperimentHolder> experimentIds = new HashMap<String, ExperimentHolder>(); private Stack<String> stack = new Stack<String>(); private String attName = null; private StringBuffer attValue = null; private InteractionHolder holder; private ExperimentHolder experimentHolder; private InteractorHolder interactorHolder; private String interactorId; private Item organism = null; private String organismTaxonId = null, currentParticipantId = null; //private Set<String> invalidInteractorIds = new HashSet<String>(); /** * Constructor */ public BioGridHandler() { // nothing to do } /** * {@inheritDoc} */ public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { attName = null; // <experimentList><experimentDescription> if (qName.equals("experimentDescription")) { experimentHolder = getExperimentHolder(attrs.getValue("id")); // <entry><source release="2.0.37" releaseDate="2008-01-25"><names><shortLabel> // Interactions for BIOGRID-ORGANISM-7227</shortLabel> } else if (qName.equals("shortLabel") && stack.peek().equals("names") && stack.search("source") == 2) { attName = "organismTaxonId"; // <experimentList><experimentDescription id="2"><names><shortLabel> } else if (qName.equals("shortLabel") && stack.peek().equals("names") && stack.search("experimentDescription") == 2) { attName = "experimentName"; // <experimentList><experimentDescription id="2"><names><fullName> } else if (qName.equals("fullName") && stack.peek().equals("names") && stack.search("experimentDescription") == 2) { attName = "experimentDescr"; //<experimentList><experimentDescription><bibref><xref><primaryRef> } else if (qName.equals("primaryRef") && stack.peek().equals("xref") && stack.search("bibref") == 2 && stack.search("experimentDescription") == 3) { String pubMedId = attrs.getValue("id"); if (StringUtil.allDigits(pubMedId)) { String pub = getPub(pubMedId); experimentHolder.setPublication(pub); } //<experimentList><experimentDescription><interactionDetectionMethod><names><shortLabel> } else if (qName.equals("shortLabel") && stack.peek().equals("names") && stack.search("interactionDetectionMethod") == 2) { attName = "interactionDetectionMethod"; // <interactorList><interactor id="4"> } else if (qName.equals("interactor") && stack.peek().equals("interactorList")) { interactorId = attrs.getValue("id"); interactorHolder = new InteractorHolder(interactorId); ids.put(interactorId, interactorHolder); // <interactorList><interactor id="4"><names><shortLabel>YFL039C</shortLabel> } else if (qName.equals("shortLabel") && stack.search("interactor") == 2) { attName = "secondaryIdentifier"; // <interactorList><interactor id="4"><xref><primaryRef db="FLYBASE" id="FBgn0000659" } else if ((qName.equals("primaryRef") || qName.equals("secondaryRef")) && stack.peek().equals("xref") && stack.search("interactor") == 2) { // TODO we aren't using these at the moment // if (attrs.getValue("db") != null) { // String dbRef = attrs.getValue("db"); // String identifier = attrs.getValue("id"); // // store all identifiers as we don't know if this is a gene or a protein, yet // if (dbRef.equalsIgnoreCase("FLYBASE") // || dbRef.equalsIgnoreCase("WormBase") // || dbRef.equalsIgnoreCase("SGD")) { // interactorHolder.primaryIdentifiers.add(identifier); // } else if (dbRef.equalsIgnoreCase("UNIPROTKB")) { // interactorHolder.accessions.add(identifier); // <interactorList><interactor id="4"><organism ncbiTaxId="7227"> } else if (qName.equals("organism") && stack.peek().equals("interactor")) { String taxId = attrs.getValue("ncbiTaxId"); if (organism == null) { organism = getOrganism(taxId); // } else { // String currentTaxId = organism.getAttribute("taxonId").getValue(); // if (!taxId.equals(currentTaxId)) { // LOG.error("Interaction with different organisms found: " + taxId // + " and " + currentTaxId); // invalidInteractorIds.add(interactorId); } interactorId = null; //<interactionList><interaction><experimentList><experimentRef> } else if (qName.equals("experimentRef") && stack.peek().equals("experimentList")) { attName = "experimentRef"; holder = new InteractionHolder(); //<interactionList><interaction> <participantList><participant id="68259"> } else if (qName.equals("participant") && stack.peek().equals("participantList")) { currentParticipantId = attrs.getValue("id"); holder.addInteractor(ids.get(currentParticipantId)); //<interactionList><interaction><interactionType><names><shortLabel } else if (qName.equals("shortLabel") && stack.peek().equals("names") && stack.search("interactionType") == 2) { attName = "interactionType"; // <participant id="62692"><interactorRef>62692</interactorRef> // <experimentalRoleList><experimentalRole><names><shortLabel> } else if (qName.equals("shortLabel") && stack.search("experimentalRole") == 2) { attName = "role"; } super.startElement(uri, localName, qName, attrs); stack.push(qName); attValue = new StringBuffer(); } /** * {@inheritDoc} */ public void characters(char[] ch, int start, int length) { int st = start; int l = length; if (attName != null) { // DefaultHandler may call this method more than once for a single // attribute content -> hold text & create attribute in endElement while (l > 0) { boolean whitespace = false; switch(ch[st]) { case ' ': case '\r': case '\n': case '\t': whitespace = true; break; default: break; } if (!whitespace) { break; } ++st; --l; } if (l > 0) { StringBuffer s = new StringBuffer(); s.append(ch, st, l); attValue.append(s); } } } /** * {@inheritDoc} */ public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); stack.pop(); // <experimentList><experimentDescription id="13022"><names><shortLabel> if (attName != null && attName.equals("experimentName") && qName.equals("shortLabel")) { experimentHolder.shortName = attValue.toString(); // <experimentList><experimentDescription id="13022"><names><fullName> } else if (attName != null && attName.equals("experimentDescr") && qName.equals("fullName")) { experimentHolder.setDescription(attValue.toString()); //<experimentList><experimentDescription> //<interactionDetectionMethod><names><shortLabel> } else if (attName != null && attName.equals("interactionDetectionMethod") && qName.equals("shortLabel")) { experimentHolder.setMethod(getTerm(attValue.toString())); // <interactorList><interactor id="4"><names><shortLabel>YFL039C</shortLabel> } else if (attName != null && attName.equals("secondaryIdentifier") && qName.equals("shortLabel") && stack.search("interactor") == 2) { interactorHolder.secondaryIdentifier = attValue.toString(); //<participant><interactorRef> //<experimentalRoleList><experimentalRole><names><shortLabel> } else if (attName != null && attName.equals("role") && qName.equals("shortLabel") && stack.search("experimentalRole") == 2) { holder.interactors.get(currentParticipantId).role = attValue.toString(); //<interactionList><interaction><experimentList><experimentRef> } else if (attName != null && attName.equals("experimentRef") && qName.equals("experimentRef") && stack.peek().equals("experimentList")) { holder.setExperimentHolder(experimentIds.get(attValue.toString())); //<interactionType><names><shortLabel> } else if (attName != null && attName.equals("interactionType")) { String type = attValue.toString(); holder.methodRefId = getTerm(type); // holder.type = type; // if (type.equalsIgnoreCase("Phenotypic Suppression") // || type.equalsIgnoreCase("Phenotypic Enhancement")) { // holder.isGeneticInteraction = true; // we now know what kind of interaction this is, so we can set our identifiers and // build the correct objects try { setInteractions(holder); } catch (ObjectStoreException e) { // TODO something clever } //<interactionList><interaction> } else if (qName.equals("interaction") && holder != null && holder.validActors) { try { storeExperiment(holder.eh); } catch (ObjectStoreException e) { // TODO something clever here } storeInteraction(holder); holder = null; } else if (attName != null && attName.equals("organismTaxonId")) { String shortLabel = attValue.toString(); String[] tokens = shortLabel.split("-"); organismTaxonId = tokens[2]; } } private void storeInteraction(InteractionHolder h) throws SAXException { //List<InteractorHolder> interactors = h.interactors.values); try { //while (iter.hasNext()) { for (InteractorHolder ih: h.interactors.values()) { // InteractorHolder ih = iter.next(); String refId = ih.refId; Item interaction = null; interaction = createItem("Interaction"); if (ih.role != null) { interaction.setAttribute("role", ih.role); } // if (ih.type.equals("Gene")) { interaction.setReference("gene", refId); interaction.setCollection("interactingGenes", getInteractingObjects(h, refId)); interaction.setReference("type", h.methodRefId); // } else { // interaction.setReference("protein", refId); // interaction.setCollection("interactingProteins", // getInteractingObjects(h, refId)); String interactionName = ""; for (String identifier : h.identifiers) { if (!identifier.equals(ih.identifier)) { interactionName += "_" + identifier; } else { interactionName = identifier + interactionName; } } interaction.setReference("experiment", h.eh.experimentRefId); interaction.setAttribute("shortName", interactionName); store(interaction); } } catch (ObjectStoreException e) { throw new SAXException(e); } } private String getPub(String pubMedId) throws SAXException { String itemId = pubs.get(pubMedId); if (itemId == null) { try { Item pub = createItem("Publication"); pub.setAttribute("pubMedId", pubMedId); itemId = pub.getIdentifier(); pubs.put(pubMedId, itemId); store(pub); } catch (ObjectStoreException e) { throw new SAXException(e); } } return itemId; } private Item getGene(String taxonId, String id, boolean isPrimaryIdentifier) throws ObjectStoreException { String identifier = id; // for Drosophila attempt to update to a current gene identifier IdResolver resolver = resolverFactory.getIdResolver(false); if (taxonId.equals("7227") && resolver != null) { int resCount = resolver.countResolutions(taxonId, identifier); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: " + identifier + " count: " + resCount + " FBgn: " + resolver.resolveId(taxonId, identifier)); return null; } identifier = resolver.resolveId(taxonId, identifier).iterator().next(); } Item item = genes.get(identifier); if (item == null) { item = createItem("Gene"); String identifierLabel = "primaryIdentifier"; if (!taxonId.equals("7227") && !isPrimaryIdentifier) { identifierLabel = "secondaryIdentifier"; } item.setAttribute(identifierLabel, identifier); item.setReference("organism", organism.getIdentifier()); store(item); genes.put(identifier, item); } return item; } // TODO save protein info too? // private Item getProtein(String identifier) throws ObjectStoreException { // Item item = proteins.get(identifier); // if (item == null) { // item = createItem("Protein"); // item.setAttribute("primaryAccession", identifier); // item.setReference("organism", organism.getIdentifier()); // store(item); // proteins.put(identifier, item); // return item; // private String getBioEntity(boolean isPrimaryIdentifier, String identifier) { // Item bioentity = null; // try { // if (isPrimaryIdentifier) { // bioentity = getGene(organismTaxonId, identifier, true); // } else { // bioentity = getProtein(identifier); // if (bioentity != null) { // return bioentity.getIdentifier(); // } catch (ObjectStoreException e) { // throw new RuntimeException("error while storing: " + identifier, e); // LOG.error("couldn't match identifier with a partipantid " + identifier); // return null; private Item getOrganism(String taxonId) throws SAXException { try { Item item = createItem("Organism"); item.setAttribute("taxonId", taxonId); store(item); return item; } catch (ObjectStoreException e) { throw new SAXException(e); } } private String getTerm(String name) throws SAXException { String refId = terms.get(name); if (refId != null) { return refId; } try { Item item = createItem("ProteinInteractionTerm"); item.setAttribute("name", name); terms.put(name, item.getIdentifier()); store(item); return item.getIdentifier(); } catch (ObjectStoreException e) { throw new SAXException(e); } } private ExperimentHolder getExperimentHolder(String experimentId) { ExperimentHolder eh = experimentIds.get(experimentId); if (eh == null) { eh = new ExperimentHolder(experimentId); experimentIds.put(experimentId, eh); } return eh; } private void storeExperiment(ExperimentHolder eh) throws ObjectStoreException { if (!eh.isStored) { Item exp = null; exp = createItem("InteractionExperiment"); exp.setReference("interactionDetectionMethod", eh.methodRefId); exp.setAttribute("name", eh.shortName); exp.setReference("publication", eh.pubRefId); store(exp); eh.isStored = true; eh.experimentRefId = exp.getIdentifier(); } } private ArrayList<String> getInteractingObjects(InteractionHolder interactionHolder, String refId) { ArrayList<String> interactorIds = new ArrayList(interactionHolder.refIds); interactorIds.remove(refId); return interactorIds; } /** * we now know what kind of interaction this is, so we can fetch our identifiers from * the correct maps. * * we add the identifiers to a list just for convenience. this list will later be used * to build the indentifier for the entire interaction. */ private void setInteractions(InteractionHolder h) throws ObjectStoreException { for (InteractorHolder ih : h.interactors.values()) { String refId = null; Item item = getGene(organismTaxonId, ih.secondaryIdentifier, false); if (item != null) { refId = item.getIdentifier(); ih.refId = refId; h.refIds.add(refId); ih.identifier = ih.secondaryIdentifier; h.identifiers.add(ih.secondaryIdentifier); } else { h.validActors = false; String msg = "could not resolve bioentity == " + ih.secondaryIdentifier + ", participantId: " + ih.participantId; LOG.error(msg); } } } /** * Holder object for GeneInteraction. Holds all information about an interaction until * ready to store * @author Julie Sullivan */ public class InteractionHolder { protected ExperimentHolder eh; protected Map<String, InteractorHolder> interactors = new HashMap<String, InteractorHolder>(); protected Set<String> refIds = new HashSet<String>(); protected Set<String> identifiers = new HashSet<String>(); protected boolean validActors = true; protected String methodRefId; /** * @param eh object holding experiment object */ protected void setExperimentHolder(ExperimentHolder eh) { this.eh = eh; } /** * @param ih object holding interactor */ protected void addInteractor(InteractorHolder ih) { interactors.put(ih.participantId, ih); } } /** * Holder object for GeneInteractor. Holds id and identifier for gene until the experiment * is verified as a gene interaction and not a protein interaction * @author Julie Sullivan */ protected class InteractorHolder { protected String role; protected String participantId; protected String identifier; // same as secondaryIdentifier right now protected String refId; protected List<String> accessions = new ArrayList<String>(); // obsolete? protected List<String> primaryIdentifiers = new ArrayList<String>(); // obsolete? protected String secondaryIdentifier; /** * Constructor * @param participantId bioGRID id */ public InteractorHolder(String participantId) { this.participantId = participantId; } } /** * Holder object for Experiment. Holds all information about an experiment until * an interaction is verified to have only valid organisms * @author Julie Sullivan */ protected class ExperimentHolder { protected String experimentRefId; protected String shortName; protected String description; protected String pubRefId; protected boolean isStored = false; protected String methodRefId; protected String id; /** * Constructor * @param id experiment id */ public ExperimentHolder(String id) { this.id = id; } /** * * @param description the full name of the experiments */ protected void setDescription(String description) { this.description = description; } /** * * @param pubRefId reference to publication item for this experiment */ protected void setPublication(String pubRefId) { this.pubRefId = pubRefId; } /** * terms describe the method used int he experiment, eg two hybrid, etc * @param methodRefId reference to the term item for this experiment */ protected void setMethod(String methodRefId) { this.methodRefId = methodRefId; } } } }
package org.intermine.bio.dataconversion; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import org.apache.commons.collections.keyvalue.MultiKey; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.bio.util.OrganismData; import org.intermine.bio.util.OrganismRepository; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.SAXParser; import org.intermine.util.StringUtil; import org.intermine.xml.full.Item; import org.intermine.xml.full.ReferenceList; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * DataConverter to parse biogrid data into items * * Genetic interactions are labeled protein interactions, so we can't store or create any objects * until all experiments and interactors are processed. Holder objects are creating, storing the * data processed until the interactions are processed and we know the interactionType * * EXPERIMENT HOLDER * holds the experiment data until the experiment data are processed * * INTERACTOR HOLDER * holds the identifier * * INTERACTION HOLDER * holds all interaction data until the entire entry is processed * * invalid experiments: * - human interactions use genbank IDs * - dmel gene doesn't resolve * - if any of the participants are invalid, we throw away the interaction * * @author Julie Sullivan */ public class BioGridConverter extends BioFileConverter { private static final Logger LOG = Logger.getLogger(BioGridConverter.class); private static final String PROP_FILE = "biogrid_config.properties"; private Map<String, String> terms = new HashMap<String, String>(); private Map<String, String> pubs = new HashMap<String, String>(); private Map<String, String> organisms = new HashMap<String, String>(); private static final Map<String, String> PSI_TERMS = new HashMap<String, String>(); private Map<String, String> genes = new HashMap<String, String>(); private Map<String, Map<String, String>> config = new HashMap<String, Map<String, String>>(); private Set<String> taxonIds = null; private static final OrganismRepository OR = OrganismRepository.getOrganismRepository(); private Map<MultiKey, Item> idsToExperiments; private Map<String, String> strains = new HashMap<String, String>(); private Map<MultiKey, Item> interactions = new HashMap<MultiKey, Item>(); private static final String SPOKE_MODEL = "prey"; private static final String BLANK_EXPERIMENT_NAME = "NAME NOT AVAILABLE"; protected IdResolver rslv; private static final String FLY = "7227"; private static final String HUMAN = "9606"; /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public BioGridConverter(ItemWriter writer, Model model) { super(writer, model, "BioGRID", "BioGRID interaction data set"); readConfig(); } static { PSI_TERMS.put("MI:0915", "physical"); PSI_TERMS.put("MI:0407", "physical"); PSI_TERMS.put("MI:0403", "physical"); PSI_TERMS.put("MI:0914", "physical"); PSI_TERMS.put("MI:0794", "genetic"); PSI_TERMS.put("MI:0796", "genetic"); PSI_TERMS.put("MI:0799", "genetic"); } /** * {@inheritDoc} */ @Override public void process(Reader reader) throws Exception { File file = getCurrentFile(); if (file == null) { throw new FileNotFoundException("No valid data files found."); } if (taxonIds != null && !taxonIds.isEmpty()) { if (!isValidOrganism(file.getName())) { return; } } if (rslv == null) { rslv = IdResolverService.getIdResolverByOrganism(FLY); rslv = IdResolverService.getHumanIdResolver(); } BioGridHandler handler = new BioGridHandler(); try { SAXParser.parse(new InputSource(reader), handler); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } private boolean isValidOrganism(String filename) { String organism = filename.substring(17); organism = organism.substring(0, organism.indexOf('-')); if (!organism.contains("_")) { return false; } String[] bits = organism.split("_"); if (bits.length == 1) { return false; } OrganismData od = OR.getOrganismDataByGenusSpecies(bits[0], bits[1]); if (taxonIds.contains(String.valueOf(od.getTaxonId()))) { return true; } return false; } private void readConfig() { Properties props = new Properties(); try { props.load(getClass().getClassLoader().getResourceAsStream(PROP_FILE)); } catch (IOException e) { throw new RuntimeException("Problem loading properties '" + PROP_FILE + "'", e); } for (Map.Entry<Object, Object> entry: props.entrySet()) { String key = (String) entry.getKey(); String value = ((String) entry.getValue()).trim(); String[] attributes = key.split("\\."); if (attributes.length == 0) { throw new RuntimeException("Problem loading properties '" + PROP_FILE + "' on line " + key); } String taxonId = attributes[0]; if (config.get(taxonId) == null) { Map<String, String> configs = new HashMap<String, String>(); config.put(taxonId, configs); } if ("xref".equals(attributes[1])) { config.get(taxonId).put(attributes[2], value.toLowerCase()); } else { String attribute = attributes[1]; if ("strain".equals(attribute)) { strains.put(value, taxonId); } else { config.get(taxonId).put(attribute, value); } } } } /** * Sets the list of taxonIds that should be imported if using split input files. * * @param taxonIds a space-separated list of taxonIds */ public void setBiogridOrganisms(String taxonIds) { this.taxonIds = new HashSet<String>(Arrays.asList(StringUtil.split(taxonIds, " "))); } /** * {@inheritDoc} */ @Override public void close() { if (idsToExperiments != null) { for (Item experiment : idsToExperiments.values()) { try { store(experiment); } catch (ObjectStoreException e) { throw new RuntimeException(e); } } } } /** * Handles xml file */ class BioGridHandler extends DefaultHandler { // identifier to [refId|BioGRID_id] private Map<String, Participant> participants = new HashMap<String, Participant>(); // BioGRID_ID to holder - one holder object can have multiple BioGRID_ids (proteins, genes) private Map<String, InteractorHolder> interactors = new HashMap<String, InteractorHolder>(); private Map<String, ExperimentHolder> experimentIDs = new HashMap<String, ExperimentHolder>(); private InteractionHolder holder; private ExperimentHolder experimentHolder; private InteractorHolder interactorHolder; private String participantId = null; private Stack<String> stack = new Stack<String>(); private String attName = null; private StringBuffer attValue = null; /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { attName = null; // <experimentList><experimentDescription> if ("experimentDescription".equals(qName)) { experimentHolder = getExperimentHolder(attrs.getValue("id")); // <entry><source release="2.0.37" releaseDate="2008-01-25"><names><shortLabel> // Interactions for BIOGRID-ORGANISM-7227</shortLabel> } else if ("shortLabel".equals(qName) && "names".equals(stack.peek()) && stack.search("source") == 2) { attName = "organismTaxonId"; // <experimentList><experimentDescription id="2"><names><shortLabel> } else if ("shortLabel".equals(qName) && "names".equals(stack.peek()) && stack.search("experimentDescription") == 2) { attName = "experimentName"; // <experimentList><experimentDescription id="2"><names><fullName> } else if ("fullName".equals(qName) && "names".equals(stack.peek()) && stack.search("experimentDescription") == 2) { attName = "experimentDescr"; //<experimentList><experimentDescription><bibref><xref><primaryRef> } else if ("primaryRef".equals(qName) && "xref".equals(stack.peek()) && stack.search("bibref") == 2 && stack.search("experimentDescription") == 3) { String pubMedId = attrs.getValue("id"); if (StringUtil.allDigits(pubMedId)) { experimentHolder.setPublication(getPub(pubMedId)); } //<experimentList><experimentDescription><interactionDetectionMethod><xref><primaryRef> } else if ("primaryRef".equals(qName) && "xref".equals(stack.peek()) && stack.search("interactionDetectionMethod") == 2) { String term = attrs.getValue("id"); experimentHolder.setMethod(getTerm(term)); // <interactorList><interactor id="4"> } else if ("interactor".equals(qName) && "interactorList".equals(stack.peek())) { String interactorId = attrs.getValue("id"); interactorHolder = new InteractorHolder(interactorId); interactors.put(interactorId, interactorHolder); // <interactorList><interactor id="4"><xref> // <secondaryRef db="SGD" id="S000006331" secondary="YPR127W"/> } else if (("primaryRef".equals(qName) || "secondaryRef".equals(qName)) && stack.search("interactor") == 2) { String db = attrs.getValue("db"); if (db != null) { db = db.toLowerCase(); interactorHolder.xrefs.put(db, attrs.getValue("id")); } // <interactorList><interactor id="4"><names><shortLabel>YFL039C</shortLabel> } else if ("shortLabel".equals(qName) && stack.search("interactor") == 2) { attName = "shortLabel"; // <interactorList><interactor id="4"><organism ncbiTaxId="7227"> } else if ("organism".equals(qName) && "interactor".equals(stack.peek())) { String taxId = attrs.getValue("ncbiTaxId"); taxId = replaceStrain(taxId); if ((taxonIds == null || taxonIds.isEmpty()) || taxonIds.contains(taxId)) { try { interactorHolder.organismRefId = getOrganism(taxId); } catch (ObjectStoreException e) { LOG.error("couldn't store organism:" + taxId); throw new RuntimeException("Could not store organism " + taxId, e); } Map<String, String> identifierConfigs = config.get(taxId); if (identifierConfigs != null) { for (Map.Entry<String, String> entry : identifierConfigs.entrySet()) { boolean validGene = setGene(taxId, interactorHolder, entry.getKey(), entry.getValue()); // try all configs until we get a good one to make it more likely to // find a match if (validGene) { break; } } } } // <interaction> } else if ("interaction".equals(qName)) { holder = new InteractionHolder(); //<interactionList><interaction><experimentList><experimentRef> } else if ("experimentRef".equals(qName) && "experimentList".equals(stack.peek())) { attName = "experimentRef"; //<interactionList><interaction> <participantList><participant id="68259"> // <interactorRef> } else if ("interactorRef".equals(qName) && "participant".equals(stack.peek())) { attName = "participant"; //<interactionList><interaction><interactionType><xref><primaryRef> } else if ("primaryRef".equals(qName) && "xref".equals(stack.peek()) && stack.search("interactionType") == 2) { String termIdentifier = attrs.getValue("id"); holder.methodRefId = getTerm(termIdentifier); String interactionType = PSI_TERMS.get(termIdentifier); if (interactionType == null) { throw new RuntimeException("Bad interaction type:" + termIdentifier); } holder.interactionType = interactionType; // <participant id="62692"><interactorRef>62692</interactorRef> // <experimentalRoleList><experimentalRole><names><shortLabel> } else if ("shortLabel".equals(qName) && stack.search("experimentalRole") == 2) { attName = "role"; // <interactionList><interaction><names><shortLabel> } else if ("shortLabel".equals(qName) && stack.search("interaction") == 2) { attName = "interactionName"; } super.startElement(uri, localName, qName, attrs); stack.push(qName); attValue = new StringBuffer(); } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) { int st = start; int l = length; if (attName != null) { if (l > 0) { StringBuffer s = new StringBuffer(); s.append(ch, st, l); attValue.append(s); } } } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); stack.pop(); // <experimentList><experimentDescription id="13022"><names><shortLabel> if (attName != null && "experimentName".equals(attName) && "shortLabel".equals(qName)) { String shortName = attValue.toString(); if (shortName != null) { experimentHolder.shortName = shortName; } // <experimentList><experimentDescription id="13022"><names><fullName> } else if (attName != null && "experimentDescr".equals(attName) && "fullName".equals(qName)) { String descr = attValue.toString(); if (descr != null) { experimentHolder.setDescription(descr); } } else if ("experimentDescription".equals(qName)) { setExperiment(experimentHolder); // <interactorList><interactor id="4"><names><shortLabel>YFL039C</shortLabel> } else if (attName != null && "shortLabel".equals(attName) && "shortLabel".equals(qName) && stack.search("interactor") == 2) { String shortLabel = attValue.toString(); if (shortLabel.startsWith("Dmel")) { shortLabel = shortLabel.substring(4); shortLabel = shortLabel.trim(); } interactorHolder.shortLabel = shortLabel; //<interactionList><interaction> <participantList><participant id="68259"> //<interactorRef>1</interactorRef> } else if (attName != null && "participant".equals(attName) && "interactorRef".equals(qName)) { participantId = attValue.toString(); InteractorHolder ih = interactors.get(participantId); if (ih == null) { holder.validActors = false; LOG.error("invalid participant ID: " + participantId); } else { // TODO make sure this is necessary. interactor id is reused? ih.role = null; // resolver didn't return valid identifier Participant p = ih.participant; if (p == null) { ih.valid = false; holder.validActors = false; } else { holder.refIds.add(p.refId); holder.identifiers.add(p.identifier); holder.addInteractor(participantId, ih); } } //<participant><interactorRef> //<experimentalRoleList><experimentalRole><names><shortLabel> } else if (attName != null && "role".equals(attName) && "shortLabel".equals(qName) && stack.search("experimentalRole") == 2) { String role = attValue.toString(); if (role != null) { InteractorHolder ih = interactors.get(participantId); if (ih == null) { holder.validActors = false; } else { ih.role = role; } } //<interactionList><interaction><experimentList><experimentRef> } else if (attName != null && "experimentRef".equals(attName) && "experimentRef".equals(qName) && "experimentList".equals(stack.peek())) { holder.setExperimentHolder(experimentIDs.get(attValue.toString())); // <interactionList><interaction><names><shortLabel> } else if (attName != null && "interactionName".equals(attName) && "shortLabel".equals(qName)) { String name = attValue.toString(); if (name != null) { holder.name = name; } //</interaction> } else if ("interaction".equals(qName) && holder != null && holder.validActors) { try { storeInteraction(holder); } catch (ObjectStoreException e) { throw new RuntimeException(" can't store data", e); } holder = null; } } private Item getInteraction(String refId, String gene2RefId) throws ObjectStoreException { MultiKey key = new MultiKey(refId, gene2RefId); Item interaction = interactions.get(key); if (interaction == null) { interaction = createItem("Interaction"); interaction.setReference("gene1", refId); interaction.setReference("gene2", gene2RefId); interactions.put(key, interaction); store(interaction); } return interaction; } // get all the gene ref IDs for an interaction private ReferenceList getAllRefIds(Collection<InteractorHolder> allInteractors) { ReferenceList allRefIds = new ReferenceList("allInteractors"); for (InteractorHolder ih : allInteractors) { allRefIds.addRefId(ih.participant.refId); } return allRefIds; } private void storeInteraction(InteractionHolder h) throws ObjectStoreException { ReferenceList allInteractors = getAllRefIds(h.ihs.values()); // for every gene in interaction store interaction pair for (InteractorHolder gene1Interactor: h.ihs.values()) { // gene1 String refId = gene1Interactor.participant.refId; Set<InteractorHolder> ihs = new HashSet<InteractorHolder>(h.ihs.values()); // loop through other genes in this interaction, set as gene2 for (InteractorHolder gene2Interactor : ihs) { String gene2RefId = gene2Interactor.participant.refId; if (gene2RefId.equals(refId)) { continue; } Item interaction = getInteraction(refId, gene2RefId); Item detail = createItem("InteractionDetail"); String role1 = gene1Interactor.role; String role2 = gene2Interactor.role; if (SPOKE_MODEL.equalsIgnoreCase(role1) && SPOKE_MODEL.equalsIgnoreCase(role2)) { // spoke! not storing bait - bait, only bait - prey continue; } if (gene1Interactor.role != null) { detail.setAttribute("role1", role1); } if (gene2Interactor.role != null) { detail.setAttribute("role2", role2); } detail.setAttribute("type", h.interactionType); detail.setReference("relationshipType", h.methodRefId); detail.setReference("experiment", h.eh.experimentRefId); if (StringUtils.isEmpty(h.name)) { String prettyName = StringUtils.join(h.identifiers, "_"); detail.setAttribute("name", "BioGRID:" + prettyName); } else { detail.setAttribute("name", h.name); } detail.setReference("interaction", interaction); detail.addCollection(allInteractors); store(detail); } } } private String getPub(String pubMedId) throws SAXException { String itemId = pubs.get(pubMedId); if (itemId == null) { Item pub = createItem("Publication"); pub.setAttribute("pubMedId", pubMedId); itemId = pub.getIdentifier(); pubs.put(pubMedId, itemId); try { store(pub); } catch (ObjectStoreException e) { throw new SAXException(e); } } return itemId; } private boolean setGene(String taxonId, InteractorHolder ih, String identifierField, String db) throws SAXException { String identifier = null; String label = identifierField; if ("shortLabel".equals(db)) { identifier = ih.shortLabel; } else { identifier = ih.xrefs.get(db); } if (FLY.equals(taxonId) && rslv != null) { identifier = resolveGene(taxonId, identifier); label = "primaryIdentifier"; } // no valid identifiers if (identifier == null) { ih.valid = false; return false; } ih.participant = storeGene(label, identifier, ih, taxonId); ih.valid = true; return true; } private Participant storeGene(String label, String identifier, InteractorHolder ih, String taxonId) throws SAXException { // genes can be in different XML files String refId = genes.get(identifier); if (refId == null) { Item item = createItem("Gene"); item.setAttribute(label, identifier); try { item.setReference("organism", getOrganism(taxonId)); Item xref = processBioGridId(ih, item); if (xref != null) { item.addToCollection("crossReferences", xref); } store(item); } catch (ObjectStoreException e) { throw new SAXException(e); } refId = item.getIdentifier(); genes.put(identifier, refId); } // participants are specific to an XML file, includes BioGRID id Participant p = participants.get(identifier); if (p == null) { p = new Participant(identifier, ih, refId); participants.put(identifier, p); } else { // we've seen this gene before, discard current holder object - replace with // holder object already used String interactorId = ih.biogridId; interactors.put(interactorId, p.ih); } return p; } private Item processBioGridId(InteractorHolder ih, Item item) throws ObjectStoreException { String biogridID = ih.getBiogridId(); if (StringUtils.isNotEmpty(biogridID)) { Item xref = createItem("CrossReference"); xref.setAttribute("identifier", biogridID); xref.setReference("subject", item); store(xref); return xref; } return null; } /** * resolve dmel and human genes * @param taxonId id of organism for this gene * @param ih interactor holder * @throws ObjectStoreException */ private String resolveGene(String taxonId, String identifier) { String id = identifier; if (FLY.equals(taxonId) && rslv != null && rslv.hasTaxon(FLY)) { int resCount = rslv.countResolutions(taxonId, identifier); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: " + identifier + " count: " + resCount + " FBgn: " + rslv.resolveId(taxonId, identifier)); return null; } id = rslv.resolveId(taxonId, identifier).iterator().next(); } if (HUMAN.equals(taxonId) && rslv != null && rslv.hasTaxon(HUMAN)) { int resCount = rslv.countResolutions(taxonId, identifier); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: " + identifier + " count: " + resCount + " Human identifier: " + rslv.resolveId(taxonId, identifier)); return null; } id = rslv.resolveId(taxonId, identifier).iterator().next(); } return id; } private String getOrganism(String taxonId) throws ObjectStoreException { String refId = organisms.get(taxonId); if (refId != null) { return refId; } Item item = createItem("Organism"); item.setAttribute("taxonId", taxonId); organisms.put(taxonId, item.getIdentifier()); try { store(item); } catch (ObjectStoreException e) { throw new ObjectStoreException(e); } return item.getIdentifier(); } private String replaceStrain(String id) { String mainTaxonId = strains.get(id); if (StringUtils.isNotEmpty(mainTaxonId)) { return mainTaxonId; } return id; } private String getTerm(String identifier) throws SAXException { String refId = terms.get(identifier); if (refId != null) { return refId; } Item item = createItem("InteractionTerm"); item.setAttribute("identifier", identifier); terms.put(identifier, item.getIdentifier()); try { store(item); } catch (ObjectStoreException e) { throw new SAXException(e); } return item.getIdentifier(); } private ExperimentHolder getExperimentHolder(String experimentId) { ExperimentHolder eh = experimentIDs.get(experimentId); if (eh == null) { eh = new ExperimentHolder(); experimentIDs.put(experimentId, eh); } return eh; } /** * Experiments are in the worm file multiple times, with the same publication and * experiment name. The only difference is the interactionDetectionMethod. * @param eh temporary holder for experiment */ private void setExperiment(ExperimentHolder eh) { String pubRefId = eh.pubRefId; String name = eh.shortName; MultiKey key = new MultiKey(pubRefId, name); if (idsToExperiments == null || idsToExperiments.isEmpty()) { idsToExperiments = new HashMap<MultiKey, Item>(); } Item exp = idsToExperiments.get(key); if (exp == null) { exp = createItem("InteractionExperiment"); exp.addToCollection("interactionDetectionMethods", eh.methodRefId); if (eh.description != null && !eh.description.equals("")) { exp.setAttribute("description", eh.description); } if (name != null && !name.equals("")) { exp.setAttribute("name", name); } else { exp.setAttribute("name", BLANK_EXPERIMENT_NAME); } exp.setReference("publication", pubRefId); idsToExperiments.put(key, exp); } eh.experimentRefId = exp.getIdentifier(); } /** * Holder object for GeneInteraction. Holds all information about an interaction until * ready to store * @author Julie Sullivan */ public class InteractionHolder { protected ExperimentHolder eh; protected Map<String, InteractorHolder> ihs = new HashMap<String, InteractorHolder>(); protected Set<String> refIds = new HashSet<String>(); protected Set<String> identifiers = new HashSet<String>(); protected boolean validActors = true; protected String methodRefId; protected String interactionType = "physical"; protected String name; /** * @param eh object holding experiment object */ protected void setExperimentHolder(ExperimentHolder eh) { this.eh = eh; } /** * @param id the participant id used only in the XML * @param ih object holding interactor */ protected void addInteractor(String id, InteractorHolder ih) { ihs.put(id, ih); } @Override public String toString() { return StringUtil.join(identifiers, ","); } @Override public int hashCode() { return (methodRefId.hashCode() + 3 * eh.hashCode() + 5 * identifiers.hashCode()); } } /** * Represents a "participant" in BioGRID XML */ protected class Participant { protected String identifier; protected InteractorHolder ih; protected String refId; /** * Constructor. * * @param identifier eg. FBgn * @param ih holder object for this interacting gene * @param refId ID representing stored gene object */ protected Participant(String identifier, InteractorHolder ih, String refId) { this.identifier = identifier; this.refId = refId; this.ih = ih; } } /** * Holder object for Interactor. */ protected class InteractorHolder { // bait or prey protected String role; // <interactorList><interactor id="1"> // <interactorRef>1</interactorRef> protected String biogridId; // refId and identifier, eg. FBgn protected Participant participant = null; // db to identifier, eg. FlyBase --> FBgn protected Map<String, String> xrefs = new HashMap<String, String>(); // symbol protected String shortLabel; protected boolean valid = true; protected String organismRefId; /** * Constructor * @param id bioGRID id */ public InteractorHolder(String id) { this.biogridId = id; } /** * @return ID to use to link to biogrid */ protected String getBiogridId() { if (xrefs == null || xrefs.isEmpty()) { return null; } return xrefs.get("biogrid"); } } } /** * Holder object for Experiment. Holds all information about an experiment until * an interaction is verified to have only valid organisms * @author Julie Sullivan */ protected class ExperimentHolder { protected String experimentRefId; protected String shortName; protected String description; protected String pubRefId; protected boolean isStored = false; protected String methodRefId; /** * * @param description the full name of the experiments */ protected void setDescription(String description) { this.description = description; } /** * * @param pubRefId reference to publication item for this experiment */ protected void setPublication(String pubRefId) { this.pubRefId = pubRefId; } /** * terms describe the method used int he experiment, eg two hybrid, etc * @param methodRefId reference to the term item for this experiment */ protected void setMethod(String methodRefId) { this.methodRefId = methodRefId; } } }
/** <h1>Evaluators to simplify Saxon access.</h1> <p> Implemented as Callables, therefore can be used in ThreadPools. </p> <p> Code example for use with XPathEvaluator: <code><pre> final File file = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "testfile"); Database.truncateDatabase(file); final IDatabase database = Database.openDatabase(file); final XPathSelector selector = new XPathEvaluator(QUERYSTRING, database).call(); final StringBuilder strBuilder = new StringBuilder(); for (final XdmItem item : selector) { strBuilder.append(item.toString()); } System.out.println(strBuilder.toString()); </pre></code> You can do everything you like with the resulting items. The method <em> getStringValue()</em> of the item get's the string value from the underlying node type. In case of an element it concatenates all descending text-nodes. To get the underlying node, which is a Treetank item instead of a Saxon item can be retrieved by using the identically named method <em> getUnderlyingNode()</em>. </p> <p> Code example for use with XQueryEvaluator <code><pre> final File file = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "testfile"); Database.truncateDatabase(file); final IDatabase database = Database.openDatabase(file); final StringBuilder strBuilder = new StringBuilder(); for (final XdmItem item : value) { strBuilder.append(item.toString()); } System.out.println(strBuilder.toString()); </pre></code> </p> <p> Code example for use with XQueryEvaluatorOutputStream: <code><pre> final File file = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "testfile"); Database.truncateDatabase(file); final IDatabase database = Database.openDatabase(file); final XQueryEvaluator xqe = new XQueryEvaluator( XQUERYSTRING, database, new ByteArrayOutputStream()); final String result = xqe.call().toString(); System.out.println(result); </pre></code> Note that you can use other output streams as well. </p> <p> Code example for use with XQueryEvaluatorSAXHandler: <code><pre> final StringBuilder strBuilder = new StringBuilder(); final ContentHandler contHandler = new XMLFilterImpl() { @Override public void startElement( final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { strBuilder.append("<" + localName); for (int i = 0; i < atts.getLength(); i++) { strBuilder.append(" " + atts.getQName(i)); strBuilder.append("=\"" + atts.getValue(i) + "\""); } strBuilder.append(">"); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { strBuilder.append("</" + localName + ">"); } @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { for (int i = start; i < start + length; i++) { strBuilder.append(ch[i]); } } }; final File file = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "testfile"); Database.truncateDatabase(file); final IDatabase database = Database.openDatabase(file); new XQueryEvaluatorSAXHandler( XQUERYSTRING, database, contHandler).run(); System.out.println(strBuilder.toString()); </pre></code> </p> <p> Code example for use with XSLTEvaluator: <code><pre> final File file = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "testfile"); final File stylesheet = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "stylesheet.xsl"); final IDatabase database = Database.openDatabase(file); final OutputStream out = new ByteArrayOutputStream(); final OutputStream out = new XSLTEvaluator( database, stylesheet, out).call(); System.out.prinln(out.toString()); </pre></code> </p> * * @author Johannes Lichtenberger, University of Konstanz */ package com.treetank.saxon.evaluator;
package gov.nih.nci.caadapter.ui.main; import gov.nih.nci.caadapter.common.Log; import gov.nih.nci.caadapter.common.util.Config; import gov.nih.nci.caadapter.ui.common.AbstractMainFrame; import gov.nih.nci.caadapter.ui.common.DefaultSettings; import gov.nih.nci.caadapter.ui.common.actions.CloseAllAction; import gov.nih.nci.caadapter.ui.common.context.ContextManagerClient; import gov.nih.nci.caadapter.ui.common.context.ContextManager; import gov.nih.nci.caadapter.ui.help.HelpContentViewer; import gov.nih.nci.caadapter.ui.help.InitialSplashWindow; import gov.nih.nci.caadapter.ui.hl7message.HL7MessagePanel; import gov.nih.nci.caadapter.ui.mapping.hl7.HL7MappingPanel; import gov.nih.nci.caadapter.ui.mapping.sdtm.Database2SDTMMappingPanel; import gov.nih.nci.caadapter.ui.specification.csv.CSVPanel; import gov.nih.nci.caadapter.ui.specification.hsm.HSMPanel; import gov.nih.nci.caadapter.ui.common.ActionConstants; import gov.nih.nci.caadapter.ui.common.preferences.CaWindowClosingListener; import javax.swing.*; import java.awt.*; import java.awt.event.WindowEvent; import java.util.HashMap; //import nickyb.sqleonardo.environment.Preferences; public class MainFrame extends AbstractMainFrame { private JTabbedPane tabbedPane = new JTabbedPane(); private int tabcount = 0; private JPanel statusBar = new JPanel(); private JPanel toolBarPanel; private JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); // inserted by Kisung for handling the default screen and the tabbedPane on 09/20/05. private JPanel currentToolBarPanel; private java.util.Map<Class, JComponent> tabMap; private JLabel baseScreenJLabel; // inserted by Kisung 09/13/05 The default screen component object private HelpContentViewer helpContentViewer; /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#launch() */ public void launch() { tabMap = new HashMap<Class, JComponent>(); ContextManager contextManager = ContextManager.getContextManager(); MainMenuBar frameMenu=new MainMenuBar(this); contextManager.setMenu(frameMenu); contextManager.setToolBarHandler(new MainToolBarHandler()); contextManager.initContextManager(this); this.setTitle(Config.PRODUCT_NAME); Container contentPane = this.getContentPane(); contentPane.setLayout(new BorderLayout()); //set the icon. Image icon = DefaultSettings.getMainframeImage();//using default image file setIconImage(icon); // set the menu bar. setJMenuBar(frameMenu); //set size before constructing each of those panels since some of them //may depend on the size to align components. this.setSize(Config.FRAME_DEFAULT_WIDTH, Config.FRAME_DEFAULT_HEIGHT); contentPane.add(constructNorthPanel(), BorderLayout.NORTH); contentPane.add(constructCenterPanel(), BorderLayout.CENTER); // inserted by Kisung on 09/20/05 contentPane.add(statusBar, BorderLayout.SOUTH); tabbedPane.addChangeListener(contextManager); tabbedPane.setOpaque(false); enableEvents(AWTEvent.WINDOW_EVENT_MASK); this.addWindowListener(new CaWindowClosingListener()); this.setVisible(true); DefaultSettings.centerWindow(this); this.setFocusable(true); this.setFocusableWindowState(true); //helpContentViewer = new HelpContentViewer(this); InitialSplashWindow isw = new InitialSplashWindow(); //isw.setAlwaysOnTop(true); DefaultSettings.centerWindow(isw); isw.setVisible(true); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } isw.dispose(); } private JPanel constructNorthPanel() { Image bannerImage = DefaultSettings.getImage("NCICBBanner.jpg"); ImageIcon imageIcon = new ImageIcon(bannerImage); toolBarPanel = new JPanel(new BorderLayout()); JPanel northUpperPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); JLabel label = new JLabel(imageIcon); northUpperPanel.add(label); toolBarPanel.add(northUpperPanel, BorderLayout.NORTH); currentToolBarPanel = constructToolbarPanel(); //updateToolBar(getMainContextManager().getToolbar()); toolBarPanel.add(currentToolBarPanel, BorderLayout.SOUTH); return toolBarPanel; } private JPanel constructToolbarPanel() { JPanel mainP = new JPanel(new BorderLayout()); mainP.add(ContextManager.getContextManager().getToolBarHandler().getToolBar(), BorderLayout.CENTER); mainP.add(new JPanel(), BorderLayout.EAST); return mainP; } //This method was inserted by Kisung 09/20/05 For initial displaying of the default screen object before the JTabbedPane object is activated. private JPanel constructCenterPanel() { ImageIcon ii1 = new ImageIcon(DefaultSettings.getImage(Config.DEFAULT_SCREEN_IMAGE_FILENAME)); //FileUtil.getWorkingDirPath() + File.separator + "images" + File.separator + Config.DEFAULT_SCREEN_IMAGE_FILENAME); baseScreenJLabel = new JLabel(ii1); ii1.setImageObserver(baseScreenJLabel); centerPanel.add(baseScreenJLabel); centerPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); centerPanel.setOpaque(false); return centerPanel; } public void updateToolBar(JToolBar newToolBar) { updateToolBar(newToolBar, null); } public void updateToolBar(JToolBar newToolBar, JButton rightSideButton) { //remove first in case it already contains JToolBar rightSideToolbar = new JToolBar(); JPanel rightSidePanel = new JPanel(new BorderLayout()); if (rightSideButton != null) { rightSideToolbar.add(rightSideButton); rightSidePanel.add(rightSideToolbar, BorderLayout.CENTER); } toolBarPanel.remove(currentToolBarPanel); currentToolBarPanel.removeAll(); currentToolBarPanel.add(newToolBar, BorderLayout.CENTER); currentToolBarPanel.add(rightSidePanel, BorderLayout.EAST); toolBarPanel.add(currentToolBarPanel, BorderLayout.SOUTH); } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#addNewTab(javax.swing.JPanel) */ public void addNewTab(JPanel panel) { //Follwing 5 lines are inserted by Kisung 09/20/05 For remove default screen object before the JTabbedPane object is activated. if (tabbedPane.getTabCount() == 0) { centerPanel.removeAll(); centerPanel.setLayout(new BorderLayout()); centerPanel.add(tabbedPane, BorderLayout.CENTER); } String title = null; // if (isContainedInTabPane(panel)) {//do nothing if tabbed pane already contains the given panel. // return; if (panel instanceof CSVPanel) { title = "Untitled_" + (++tabcount) + Config.CSV_METADATA_FILE_DEFAULT_EXTENTION; } else if (panel instanceof HL7MappingPanel) { title = "Untitled_" + (++tabcount) + Config.MAP_FILE_DEFAULT_EXTENTION; } else if (panel instanceof HSMPanel) { title = "Untitled_" + (++tabcount) + Config.HSM_META_DEFINITION_FILE_DEFAULT_EXTENSION; } else if (panel instanceof HL7MessagePanel) { title = "HL7 v3 Message"; } else if (panel instanceof HL7MessagePanel) { title = panel.getName();//"HL7 v3 Message"; } else if (panel instanceof Database2SDTMMappingPanel) { title = "Untitled_" + (++tabcount) + Config.MAP_FILE_DEFAULT_EXTENTION; } tabbedPane.addTab(title, panel); tabbedPane.setSelectedComponent(panel); // Log.logInfo(this, "Panel Class: '" + (panel==null?"null":panel.getClass().getName()) + "'."); tabMap.put(panel.getClass(), panel); } private boolean isContainedInTabPane(JPanel j) { boolean result = false; result = tabMap.containsValue(j); return result; } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#closeTab() */ public void closeTab() { Component comp = tabbedPane.getSelectedComponent(); tabbedPane.remove(comp); if (tabbedPane.getTabCount() == 0) {//reset if not tab at all. tabcount = 0; //Follwing 4 lines are inserted by Kisung 09/20/05 For remove empty JTabbedPane object and display default screen. centerPanel.removeAll(); centerPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); centerPanel.add(baseScreenJLabel); centerPanel.update(centerPanel.getGraphics()); } tabMap.remove(comp.getClass()); if (comp instanceof ContextManagerClient) { ContextManager.getContextManager().getContextFileManager().removeFileUsageListener((ContextManagerClient) comp); } } /** * Only accessible by the same package so as to * avoid abuse of using the tabbedPane directly. * @return the tab pane. */ public JTabbedPane getTabbedPane() { return tabbedPane; } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#hasComponentOfGivenClass(java.lang.Class, boolean) */ public JComponent hasComponentOfGivenClass(Class classValue, boolean bringToFront) { JComponent component = tabMap.get(classValue); if (component != null) { if (bringToFront) { try { tabbedPane.setSelectedComponent(component); } catch (Throwable e) { Log.logInfo(this, "What kind of Component is this: '" + component.getClass().getName() + "'."); Log.logException(this, e); } } return component; } else { return null; } } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#getAllTabs() */ public java.util.List<Component> getAllTabs() { java.util.List<Component> resultList = new java.util.ArrayList<Component>(); int count = tabbedPane.getComponentCount(); for (int i = 0; i < count; i++) { Component comp = tabbedPane.getComponentAt(i); resultList.add(comp); } return resultList; } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#setCurrentPanelTitle(java.lang.String) */ public boolean setCurrentPanelTitle(String newTitle) { int seleIndex = tabbedPane.getSelectedIndex(); if (seleIndex != -1) { tabbedPane.setTitleAt(seleIndex, newTitle); return true; } else { return false; } } public static void main(String[] args) { //Preferences.loadDefaults(); try { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new MainFrame().launch(); // AbstractMainFrame mainFrame = new MainFrame(); // mainFrame.launch(); // InitialSplashWindow isw = new InitialSplashWindow(); // //isw.setAlwaysOnTop(true); // //DefaultSettings.centerWindow(isw); // isw.setVisible(true); // MainFrame mainFrame = new MainFrame(); // mainFrame.launch(); // try{ // Thread.sleep(100); // }catch (Exception e) { // // TODO Auto-generated catch block // // e.printStackTrace(); // isw.dispose(); //isw.dispose(); // DefaultSettings.installAll(); // MainFrame mainFrame = new MainFrame(); // mainFrame.launch(); // DefaultSettings.centerWindow(mainFrame); } catch (Throwable t) { Log.logException(new Object(), t); } } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#showHelpContentViewer() */ public void showHelpContentViewer() // inserted by umkis on 01/16/2006, for reduce uploading time for help content. { DefaultSettings.centerWindow(helpContentViewer); helpContentViewer.setVisible(true); } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#showHelpContentWithNodeID(java.lang.String) */ public void showHelpContentWithNodeID(String id) // inserted by umkis on 01/16/2006, for reduce uploading time for help content. { DefaultSettings.centerWindow(helpContentViewer); helpContentViewer.linkNodeID(id); helpContentViewer.setVisible(true); } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#showHelpContentWithNodeID(java.lang.String, java.awt.Dialog) */ public void showHelpContentWithNodeID(String id, Dialog dispose) // inserted by umkis on 01/16/2006, for reduce uploading time for help content. { if (dispose != null) dispose.dispose(); showHelpContentWithNodeID(id); } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#resetCenterPanel() */ public void resetCenterPanel() // inserted by umkis on 01/18/2006, defaect# 252 { centerPanel.updateUI(); } // /** // * Invoked when the target of the listener has changed its state. // * @param e a ChangeEvent object // */ // public void stateChanged(ChangeEvent e) // {//listen to tab change event // public void windowOpened(WindowEvent e) // //To change body of implemented methods use File | Settings | File Templates. // public void windowClosing(WindowEvent event) // exit(); // public void windowClosed(WindowEvent e) // //To change body of implemented methods use File | Settings | File Templates. // public void windowIconified(WindowEvent e) // //To change body of implemented methods use File | Settings | File Templates. // public void windowDeiconified(WindowEvent e) // //To change body of implemented methods use File | Settings | File Templates. // public void windowActivated(WindowEvent e) // //To change body of implemented methods use File | Settings | File Templates. // public void windowDeactivated(WindowEvent e) // //To change body of implemented methods use File | Settings | File Templates. /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#processWindowEvent(java.awt.event.WindowEvent) */ public void processWindowEvent(WindowEvent e) { // Log.logInfo(this, "processWindowEvent() invoked with '" + e + "'."); if (e.getID() == WindowEvent.WINDOW_CLOSING) { this.getMenuBar(); MainMenuBar frameMenuBar=(MainMenuBar)ContextManager.getContextManager().getMenu(); CloseAllAction closeAllAction=(CloseAllAction)frameMenuBar.getDefinedAction(ActionConstants.CLOSE_ALL);//.closeAllAction; // CloseAllAction closeAllAction =ContextManager.getContextManager().getMenu().closeAllAction; if (closeAllAction != null && closeAllAction.isEnabled()) { closeAllAction.actionPerformed(null); if (closeAllAction.isSuccessfullyPerformed()) { super.processWindowEvent(e); } else {//back to normal process. return; } } else { super.processWindowEvent(e); } exit(); } else { super.processWindowEvent(e); } } /* (non-Javadoc) * @see gov.nih.nci.caadapter.ui.main.AbstractMainFrame#exit() */ public void exit() { ContextManager contextManager = ContextManager.getContextManager(); if (contextManager.isItOKtoShutdown()) { this.exit(0); } } protected void exit(int errorLevel) { this.setVisible(false); this.dispose(); //FunctionUtil.deleteTemporaryFiles(); Log.logInfo(this, "\r\n\r\nShutting down logging with exit code = " + errorLevel + "\r\n\r\n" + "===============================================================\r\n" + "===============================================================\r\n"); System.exit(errorLevel); } }
package gameutils; import gameutils.util.FastMath; import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; /** * Game is the main class that must be extended by the user. It handles the game loop and certain other functions.<br> * Game extends Applet but also supports being a desktop app.<br> * Remember: if this game will be used as an Applet, a default constructor <strong>MUST</strong> be present.<br> * <br> * It uses a Screen system where only 1 Screen is active at one time.<br> * <br> * A typical game looks like this: <br> * <br> * <code> * public class MyGame extends Game {<br> * &nbsp;&nbsp;&nbsp;&nbsp;public static void main(String args[]) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MyGame game = new MyGame();<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;game.setupFrame("My Game",800,600,true);<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;game.start();<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * <br> * &nbsp;&nbsp;&nbsp;&nbsp;public void initGame() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Initialize the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * <br> * &nbsp;&nbsp;&nbsp;&nbsp;public void update(long deltaTime) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Update the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * <br> * &nbsp;&nbsp;&nbsp;&nbsp;public void paused() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Pause the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void resumed() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Resume the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void resized(int width, int height) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Resize the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void stopGame() {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Stop the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> *<br> * &nbsp;&nbsp;&nbsp;&nbsp;public void paint(Graphics2D g) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Draw the game<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * } * </code> * @author Roi Atalla */ public abstract class Game extends Applet implements Runnable { private static final long serialVersionUID = -1870725768768871166L; /** * Initializes and displays the window. * @param title The title of the window * @param width The width of the window * @param height The height of the window * @param resizable If true, the window will be resizable, else it will not be resizable. * @return The JFrame that was initialized by this method. */ protected final JFrame setupFrame(String title, int width, int height, boolean resizable) { final JFrame frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setIgnoreRepaint(true); frame.setResizable(resizable); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { stop(); } }); frame.add(this); frame.setVisible(true); isApplet = false; setSize(width,height); init(); ((JPanel)frame.getContentPane()).revalidate(); return frame; } /** * Used to notify the game loop thread to update and render as fast as possible. */ public static final int MAX_FPS = 0; /** * Used to notify the game loop thread to update the maximum number of times before render. */ public static final int MAX_UPDATES = -1; /** * 1 second in nanoseconds in double precision, AKA 1,000,000 nanoseconds. */ public static final double ONE_SECOND = 1e9; /** * 1 second in nanoseconds as a long, AKA 1,000,000 nanoseconds. */ public static final long ONE_SECOND_L = (long)ONE_SECOND; private final Art art; private final Sound sound; private final Map<String,ScreenInfo> screens; private ScreenInfo screenInfo; private final Canvas canvas; private final Input input; private Object quality; private int maxUpdates; private int FPS; private double version; private boolean showFPS; private boolean useYield; private boolean standardKeysEnabled = true; private boolean isApplet = true; private volatile boolean isActive; private volatile boolean isPaused; /** * Default constructor. The defaults are:<br> * - MAX_UPDATES is set * - 60FPS<br> * - Version 1.0<br> * - showFPS = true<br> * - quality = high<br> * - standardKeysEnabled = true */ public Game() { this(60,1.0); } /** * Sets defaults and the FPS and version. * @param FPS The FPS to achieve. * @param version The version of this game. */ public Game(int FPS, double version) { art = new Art(); sound = new Sound(); screens = Collections.synchronizedMap(new HashMap<String,ScreenInfo>()); screenInfo = new ScreenInfo(new Screen() { public void init(Game game) {} public Game getParent() { return null; } public void show() {} public void hide() {} public void update(long deltaTime) {} public void draw(Graphics2D g) { g.setColor(Color.lightGray); g.fillRect(0, 0, getWidth(), getHeight()); } }); canvas = new Canvas(); input = new Input(canvas); this.FPS = FPS; this.version = version; showFPS = true; quality = RenderingHints.VALUE_ANTIALIAS_ON; maxUpdates = MAX_UPDATES; } /** * Returns the current working directory of this game. * @return The current working directory of this game. */ public URL getCodeBase() { if(isApplet()) return super.getCodeBase(); try{ return getClass().getResource("/"); } catch(Exception exc) { exc.printStackTrace(); return null; } } public Graphics getGraphics() { return canvas.getGraphics(); } /** * Returns the appropriate container of this game: this instance if it is an Applet, the JFrame if it is a desktop application. * @return If this game is an Applet, it returns this instance, else it returns the JFrame used to display this game. */ public Container getRootParent() { if(isApplet()) return this; return getParent().getParent().getParent().getParent(); } /** * @return Returns true if this game is an Applet, false otherwise. */ public boolean isApplet() { return isApplet; } /** * @return Returns true if this game is currently active. */ public boolean isActive() { return isActive; } /** * Manually pauses the game loop. paused() will be called */ public void pause() { if(isActive()) { isPaused = true; paused(); } } /** * Returns true if the game loop is paused. * @return True if the game loop is paused, false otherwise. */ public boolean isPaused() { return isPaused; } /** * Manually resumes the game loop. resumed() will be called right before the game loop resumes. */ public void resume() { if(isActive() && isPaused()) { isPaused = false; resumed(); } } /** * If this game is an applet, it calls the superclass's resize method, else it calls setSize(int,int). * @param width The new width of this game's canvas. * @param height The new height of this game's canvas; */ public void resize(int width, int height) { if(isApplet()) super.resize(width,height); else setSize(width,height); } /** * If this game is an Applet, it calls the superclass's resize method, else it adjusts the JFrame according to the platform specific Insets. * @param width The new width of this game's canvas * @param height The new height of this game's canvas */ public void setSize(int width, int height) { if(isApplet()) super.resize(width,height); else { Insets i = getRootParent().getInsets(); getRootParent().setSize(width+i.right+i.left,height+i.bottom+i.top); ((JFrame)getRootParent()).setLocationRelativeTo(null); } } /** * Game loop. */ public final void run() { if(isActive()) return; Thread.currentThread().setName("Game Loop Thread"); try{ UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception exc) {} synchronized(Game.this) { initGame(); } Listener listener = new Listener(); canvas.addKeyListener(listener); canvas.addMouseListener(listener); canvas.addMouseMotionListener(listener); canvas.addMouseWheelListener(listener); BufferStrategy strategy = canvas.getBufferStrategy(); int frames = 0; int currentFPS = 0; long time = System.nanoTime(); long lastTime = System.nanoTime(); isActive = true; canvas.requestFocus(); while(isActive()) { long now = System.nanoTime(); long diffTime = now-lastTime; lastTime = now; int updateCount = 0; while(diffTime > 0 && (maxUpdates == MAX_UPDATES || updateCount < maxUpdates) && !isPaused()) { long deltaTime; if(FPS > 0) deltaTime = Math.min(diffTime,ONE_SECOND_L/FPS); else deltaTime = diffTime; try{ synchronized(Game.this) { update(deltaTime); } } catch(Exception exc) { exc.printStackTrace(); } diffTime -= deltaTime; updateCount++; } try{ do{ do{ Graphics2D g = (Graphics2D)strategy.getDrawGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,quality); try{ synchronized(Game.this) { paint(g); } } catch(Exception exc) { exc.printStackTrace(); } if(showFPS) { g.setColor(Color.black); g.setFont(new Font(Font.SANS_SERIF,Font.TRUETYPE_FONT,10)); g.drawString("Version " + version + " " + currentFPS + " FPS",2,canvas.getHeight()-2); } g.dispose(); }while(strategy.contentsRestored()); strategy.show(); }while(strategy.contentsLost()); } catch(Exception exc) { exc.printStackTrace(); } if(System.nanoTime()-time >= ONE_SECOND_L) { time = System.nanoTime(); currentFPS = frames; frames = 0; } frames++; try{ if(FPS > 0) { long sleepTime = FastMath.round((ONE_SECOND/FPS)-(System.nanoTime()-lastTime)); if(sleepTime <= 0) continue; long prevTime = System.nanoTime(); while(System.nanoTime()-prevTime <= sleepTime) { if(useYield) Thread.yield(); else Thread.sleep(1); } } } catch(Exception exc) { exc.printStackTrace(); } } stopGame(); } public final void init() { setIgnoreRepaint(true); setLayout(new BorderLayout()); add(canvas); canvas.setIgnoreRepaint(true); canvas.createBufferStrategy(2); canvas.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent ce) { resized(getWidth(),getHeight()); } }); canvas.addFocusListener(new FocusListener() { private boolean focusLost; public void focusGained(FocusEvent fe) { if(focusLost && isPaused() && isActive()) { focusLost = false; resume(); } } public void focusLost(FocusEvent fe) { if(!isPaused() && isActive()) { focusLost = true; pause(); } } }); } /** * Automatically called if this game is an Applet, otherwise it has to be manually called. */ public final void start() { if(!isActive()) new Thread(this).start(); } /** * Called when this game is stopped. Calling this method stops the game loop. stopGame() is then called. */ public final void stop() { sound.setOn(false); isActive = false; } /** * Called as soon as the game is created. */ protected abstract void initGame(); /** * Called the set FPS times a second. Updates the current screen. * @param deltaTime The time passed since the last call to it. */ protected void update(long deltaTime) { screenInfo.screen.update(deltaTime); } /** * Called when this game loses focus. */ protected abstract void paused(); /** * Called when this game regains focus. */ protected abstract void resumed(); /** * called when the game is resized. * @param width The new width. * @param height The new height. */ protected abstract void resized(int width, int height); /** * Called when this game is stopped. */ protected abstract void stopGame(); /** * Called the set FPS times a second. Clears the window using the Graphics2D's background color then draws the current screen. * @param g The Graphics context to be used to draw to the canvas. */ protected void paint(Graphics2D g) { g.clearRect(0, 0, getWidth(), getHeight()); screenInfo.screen.draw((Graphics2D)g.create()); } /** * Adds a screen to this game. * @param screen The Screen to add. * @param name The name of the screen. */ public synchronized void addScreen(Screen screen, String name) { if(screen == null) throw new IllegalArgumentException("Screen cannot be null."); if(name == null) throw new IllegalArgumentException("Name cannot be null."); screens.put(name,new ScreenInfo(screen)); screen.init(this); } /** * Returns the current screen. * @return The current screen. */ public Screen getScreen() { return screenInfo.screen; } /** * Returns the name of the current screen. This is the same as calling <code>getName(getScreen())</code>. * @return The name of the current screen. */ public String getScreenName() { return getName(getScreen()); } /** * Returns the screen specified * @param name The name of the screen. * @return The screen associated with the specified name. */ public Screen getScreen(String name) { return screens.get(name).screen; } /** * Returns the name of the screen. * @param screen The Screen who's name is returned. * @return The name of the specified screen. */ public synchronized String getName(Screen screen) { for(String s : screens.keySet()) if(screens.get(s).screen == screen) return s; return null; } /** * Adds the screen and sets it as the current screen. * @param screen The Screen to be added and set. * @param name The name assigned to the Screen. */ public synchronized void setScreen(Screen screen, String name) { addScreen(screen,name); setScreen(name); } public void setScreen(Screen screen) { setScreen(getScreenInfo(screen)); } public void setScreen(String name) { ScreenInfo info = screens.get(name); if(info == null) throw new IllegalArgumentException(name + " does not exist."); setScreen(info); } private void setScreen(ScreenInfo screenInfo) { if(screenInfo == null || !screens.containsValue(screenInfo)) throw new IllegalArgumentException("Screen has not been added."); this.screenInfo.screen.hide(); this.screenInfo = screenInfo; this.screenInfo.screen.show(); } private ScreenInfo getScreenInfo(Screen screen) { if(screen == null) return null; for(ScreenInfo s : screens.values()) if(s.screen == screen) return s; return null; } /** * Adds an input listener on the specified screen. * @param screen The Screen to add the listener to. * @param listener The InputListener to be notified of input events on this screen. */ public void addInputListener(Screen screen, InputListener listener) { if(screen == null) throw new IllegalArgumentException("Screen cannot be null."); addInputListener(getScreenInfo(screen),listener); } /** * Adds an input listener on the specified screen. * @param name The name of the screen to add the listener to. * @param listener The InputListener to be notified of input events on this screen. */ public void addInputListener(String name, InputListener listener) { ScreenInfo info = screens.get(name); if(info == null) throw new IllegalArgumentException(name + " does not exist."); addInputListener(screens.get(name),listener); } private synchronized void addInputListener(ScreenInfo screenInfo, InputListener listener) { if(screenInfo == null || !screens.containsValue(screenInfo)) throw new IllegalArgumentException("Screen has not been added."); if(listener == null) throw new IllegalArgumentException("InputListener cannot be null."); screenInfo.listeners.add(listener); } /** * Removes the input listener from the specified screen. * @param screen The Screen to remove the listener from. * @param listener The InputListener reference to remove. */ public void removeInputListener(Screen screen, InputListener listener) { if(screen == null) throw new IllegalArgumentException("Screen cannot be null."); removeInputListener(getScreenInfo(screen),listener); } /** * Removes the input listener from the specified screen. * @param name The name of the screen to remove the listener from. * @param listener The InputListneer reference to remove. */ public void removeInputListener(String name, InputListener listener) { ScreenInfo info = screens.get(name); if(info == null) throw new IllegalArgumentException(name + " does not exist."); removeInputListener(screens.get(name),listener); } private synchronized void removeInputListener(ScreenInfo screenInfo, InputListener listener) { if(screenInfo == null || !screens.containsValue(screenInfo)) throw new IllegalArgumentException("Screen has not been added."); if(listener == null) throw new IllegalArgumentException("InputListener cannot be null."); screenInfo.listeners.remove(listener); } /** * Sets the version of the game. * @param version The current version of the game. */ public void setVersion(double version) { this.version = version; } /** * Returns the version of the game. * @return The current version of the game. */ public double getVersion() { return version; } /** * Sets the showFPS property. * @param showFPS If true, the FPS is updated and displayed every second, else the FPS is not displayed. */ public void showFPS(boolean showFPS) { this.showFPS = showFPS; } /** * Returns the current state of the showFPS property. * @return If true, the FPS is updated and displayed every second, else the FPS is not displayed. */ public boolean isShowingFPS() { return showFPS; } /** * Sets the optimal FPS of this game. * @param FPS Specifies the number of updates and frames shown per second. */ public void setFPS(int FPS) { this.FPS = FPS; } /** * Returns the optimal FPS of this game. * @return The number of udpates and frames shown per second. */ public int getFPS() { return FPS; } /** * Sets whether the game loop should use Thread.yield() or Thread.sleep(1).<br> * Thread.yield() produces a smoother game loop but at the expense of a high CPU usage.<br> * Thread.sleep(1) is less smooth but barely uses any CPU time.<br> * The default is Thread.sleep(1). * @param useYield If true, uses Thread.yield(), otherwise uses Thread.sleep(1). */ public void useYield(boolean useYield) { this.useYield = useYield; } /** * Returns whether the game loop uses Thread.yield() or Thread.sleep(1). The default is Thread.sleep(1). * @return True if the game loop uses Thread.yield(), false if it uses Thread.sleep(1). */ public boolean usesYield() { return useYield; } /** * Sets the quality of this game's graphics. * @param highQuality If true, the graphics are of high quality, else the graphics are of low quality. */ public void setHighQuality(boolean highQuality) { if(highQuality) quality = RenderingHints.VALUE_ANTIALIAS_ON; else quality = RenderingHints.VALUE_ANTIALIAS_OFF; } /** * Returns the current state of the quality property. * @return If true, the graphics are of high quality, else the graphics are of low quality. */ public boolean isHighQuality() { return quality == RenderingHints.VALUE_ANTIALIAS_ON; } /** * The standard keys are M for audio on/off, P for pause/resume, and Q for high/low quality. * @param standardKeysEnabled If true, a key press of the standard keys automatically call the appropriate methods, else this function is disabled. */ public void setStandardKeysEnabled(boolean standardKeysEnabled) { this.standardKeysEnabled = standardKeysEnabled; } /** * Returns the current state of the standardKeysEnabled property. * @return If true, a key press of the standard keys automatically call the appropriate methods, else this function is disabled. */ public boolean isStandardKeysEnabled() { return standardKeysEnabled; } /** * Sets the maximum number of updates before render. * @param maxUpdates The maximum number of updates before render. */ public void setMaximumUpdatesBeforeRender(int maxUpdates) { this.maxUpdates = maxUpdates; } /** * Returns the maximum number of updates before render. * @return The maximum number of updates before render. */ public int getMaximumUpdatesBeforeRender() { return maxUpdates; } /** * Returns a reference to the Art object. * @return A reference to the Art object. */ public Art getArt() { return art; } /** * Returns a reference to the Sound object. * @return A reference to the Sound object. */ public Sound getSound() { return sound; } /** * Returns a reference to the Input object. * @return A reference to the Input object. */ public Input getInput() { return input; } private static class ScreenInfo { private Screen screen; private ArrayList<InputListener> listeners = new ArrayList<InputListener>(); public ScreenInfo(Screen screen) { this.screen = screen; } } private class Listener implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener { public void keyTyped(KeyEvent key) { for(InputListener l : screenInfo.listeners) l.keyTyped(key,getScreen()); } public void keyPressed(KeyEvent key) { for(InputListener l : screenInfo.listeners) l.keyPressed(key,getScreen()); if(isStandardKeysEnabled()) { switch(key.getKeyCode()) { case KeyEvent.VK_P: if(isPaused()) resume(); else pause(); break; case KeyEvent.VK_M: sound.setOn(!sound.isOn()); break; case KeyEvent.VK_Q: setHighQuality(!isHighQuality()); break; } } } public void keyReleased(KeyEvent key) { for(InputListener l : screenInfo.listeners) l.keyReleased(key,getScreen()); } public void mouseClicked(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mouseClicked(me,getScreen()); } public void mouseEntered(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mouseEntered(me,getScreen()); } public void mouseExited(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mouseExited(me,getScreen()); } public void mousePressed(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mousePressed(me,getScreen()); } public void mouseReleased(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mouseReleased(me,getScreen()); } public void mouseDragged(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mouseDragged(me,getScreen()); } public void mouseMoved(MouseEvent me) { for(InputListener l : screenInfo.listeners) l.mouseMoved(me,getScreen()); } public void mouseWheelMoved(MouseWheelEvent mwe) { for(InputListener l : screenInfo.listeners) l.mouseWheelMoved(mwe,getScreen()); } } }
package com.example.moreapp; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonArrayRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MoreActivity extends AppCompatActivity implements MoreAppAdapter.CallBcack{ private static final String TAG_NAME = MoreActivity.class.getSimpleName(); RecyclerView recyclerView; MoreAppAdapter adapter; public ArrayList<Items> itemsArrayList; public static String url; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_more); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("More Apps"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); itemsArrayList = new ArrayList<>(); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); adapter = new MoreAppAdapter(getApplicationContext() , itemsArrayList , this); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); recyclerView.setAdapter(adapter); JsonArrayRequest movieReq = new JsonArrayRequest( url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG_NAME, response.toString()); // Parsing json for (int i = 0; i < response.length(); i++) { try { JSONObject obj = response.getJSONObject(i); Items song = new Items(); song.setName(obj.getString("name")); song.setImageId(obj.getString("image")); song.setId(obj.getLong("rating")); song.setLink(obj.getString("package_name")); itemsArrayList.add(song); } catch (JSONException e) { e.printStackTrace(); } } // notifying list adapter about data changes // so that it renders the list view with updated data adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG_NAME, "Error: " + error.getMessage()); } }); movieReq.setShouldCache(false); // Adding request to request queue App.getInstance().addToRequestQueue(movieReq); } @Override public void show(int position, Items items) { String hollywood_movie_link = items.getLink(); Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + hollywood_movie_link)); intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent2); } }
package org.whattf.checker; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class RdfaLiteChecker extends Checker { private String GUIDANCE = " Consider checking against the HTML5 + RDFa 1.1 schema instead."; private void warnNonRDFaLite(String localName, String att) throws SAXException { warn("RDFa Core attribute \u201C" + att + "\u201D is only allowed on the \u201C" + localName + "\u201D element in HTML5 + RDFa 1.1 documents," + " not in HTML5 + RDFa 1.1 Lite documents." + GUIDANCE); } /** * @see org.whattf.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if ("http: return; } int len = atts.getLength(); for (int i = 0; i < len; i++) { String att = atts.getLocalName(i); if ("datatype" == att || "resource" == att || "inlist" == att) { warn("RDFa Core attribute \u201C" + att + "\u201D is only allowed in HTML + RDFa 1.1 documents," + " not in HTML + RDFa 1.1 Lite documents." + GUIDANCE); } else if ("content" == att && "meta" != localName) { warnNonRDFaLite(localName, att); } else if ("href" == att && "a" != localName && "area" != localName && "link" != localName && "base" != localName) { warnNonRDFaLite(localName, att); } else if (("rel" == att || "rev" == att) && "a" != localName && "area" != localName && "link" != localName) { warnNonRDFaLite(localName, att); } else if ("src" == att && "audio" != localName && "embed" != localName && "iframe" != localName && "img" != localName && "input" != localName && "script" != localName && "source" != localName && "track" != localName && "video" != localName) { warnNonRDFaLite(localName, att); } } } }
package oap.metrics; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.Histogram; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.ScheduledReporter; import com.codahale.metrics.Timer; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBFactory; import org.influxdb.dto.BatchPoints; import org.influxdb.dto.Point; import org.joda.time.DateTimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.ConnectException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.SortedMap; import java.util.concurrent.TimeUnit; class InfluxDBReporter extends ScheduledReporter { private static final Logger logger = LoggerFactory.getLogger( InfluxDBReporter.class ); private final InfluxDB influxDB; private final String database; private final HashMap<String, String> tags; private HashMap<String, Object> lastReport = new HashMap<>(); protected InfluxDBReporter( InfluxDB influxDB, String database, HashMap<String, String> tags, MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit ) { super( registry, name, filter, rateUnit, durationUnit ); this.influxDB = influxDB; this.database = database; this.tags = tags; } public static Builder forRegistry( MetricRegistry registry ) { return new Builder( registry ); } @Override public synchronized void report( SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers ) { try { final long time = DateTimeUtils.currentTimeMillis(); BatchPoints.Builder pointsBuilder = BatchPoints.database( database ); BatchPoints points = pointsBuilder .consistency( InfluxDB.ConsistencyLevel.QUORUM ) .time( time, TimeUnit.MILLISECONDS ) .build(); int c = reportCounters( counters, points ); int m = reportMeters( meters, points ); int t = reportTimers( timers, points ); int g = reportGauges( gauges, points ); int h = reportHistograms( histograms, points ); logger.trace( "reporting {} counters, {} meters, {} timers, {} gauges, {} histograms", c, m, t, g, h ); influxDB.write( points ); } catch( Exception e ) { if( e.getCause() instanceof ConnectException ) { logger.error( e.getMessage() ); } else { logger.error( e.getMessage(), e ); } } } private int reportCounters( SortedMap<String, Counter> counters, BatchPoints points ) { int before = points.getPoints().size(); for( Map.Entry<String, Counter> entry : counters.entrySet() ) { final long value = entry.getValue().getCount(); final Object lastValue = lastReport.computeIfAbsent( entry.getKey(), k -> value ); if( !Objects.equals( value, lastValue ) ) { lastReport.put( entry.getKey(), value ); Point.Builder builder = Point .measurement( entry.getKey() ); tags.forEach( builder::tag ); final Point point = builder .field( "value", value ) .build(); points.point( point ); } } return points.getPoints().size() - before; } private int reportMeters( SortedMap<String, Meter> meters, BatchPoints points ) { int before = points.getPoints().size(); for( Map.Entry<String, Meter> entry : meters.entrySet() ) { final double value = entry.getValue().getOneMinuteRate(); final Object lastValue = lastReport.computeIfAbsent( entry.getKey(), k -> value ); if( !Objects.equals( value, lastValue ) ) { lastReport.put( entry.getKey(), value ); Point.Builder builder = Point .measurement( entry.getKey() ); tags.forEach( builder::tag ); final Point point = builder .field( "value", format( convertRate( value ) ) ) .build(); points.point( point ); } } return points.getPoints().size() - before; } private int reportTimers( SortedMap<String, Timer> timers, BatchPoints points ) { int before = points.getPoints().size(); for( Map.Entry<String, Timer> entry : timers.entrySet() ) { double value = entry.getValue().getSnapshot().getMean(); makePoint( entry.getKey(), value, points, format( convertDuration( value ) ) ); } return points.getPoints().size() - before; } private int reportGauges( SortedMap<String, Gauge> gauges, BatchPoints points ) { int before = points.getPoints().size(); for( Map.Entry<String, Gauge> entry : gauges.entrySet() ) { Object value = entry.getValue().getValue(); makePoint( entry.getKey(), value, points, format( value ) ); } return points.getPoints().size() - before; } private int reportHistograms( SortedMap<String, Histogram> gauges, BatchPoints points ) { int before = points.getPoints().size(); for( Map.Entry<String, Histogram> entry : gauges.entrySet() ) { double mean = entry.getValue().getSnapshot().getMean(); makePoint( entry.getKey(), mean, points, format( mean ) ); } return points.getPoints().size() - before; } private void makePoint( String key, Object value, BatchPoints points, Object formatted ) { final Object lastValue = lastReport.computeIfAbsent( key, k -> value ); if( !Objects.equals( value, lastValue ) ) { lastReport.put( key, value ); Point.Builder builder = Point.measurement( key ); tags.forEach( builder::tag ); builder.field( "value", formatted ); points.point( builder.build() ); } } private String format( double v ) { // the Carbon plaintext format is pretty underspecified, but it seems like it just wants // US-formatted digits return String.format( Locale.US, "%2.2f", v ); } private String format( Object o ) { if( o instanceof Float ) { return format( ( ( Float ) o ).doubleValue() ); } else if( o instanceof Double ) { return format( ( ( Double ) o ).doubleValue() ); } else if( o instanceof Byte ) { return format( ( ( Byte ) o ).longValue() ); } else if( o instanceof Short ) { return format( ( ( Short ) o ).longValue() ); } else if( o instanceof Integer ) { return format( ( ( Integer ) o ).longValue() ); } else if( o instanceof Long ) { return format( ( ( Long ) o ).longValue() ); } return null; } public static class Builder { private final MetricRegistry registry; private final HashMap<String, String> tags = new HashMap<>(); private String host; private int port; private String database; private String login; private String password; private TimeUnit rateUnit; private TimeUnit durationUnit; private ReporterFilter filter; public Builder( MetricRegistry registry ) { this.registry = registry; } public Builder withTag( String name, String value ) { tags.put( name, value ); return this; } public Builder withConnect( String host, int port, String database, String login, String password ) { this.host = host; this.port = port; this.database = database; this.login = login; this.password = password; return this; } public Builder convertRatesTo( TimeUnit rateUnit ) { this.rateUnit = rateUnit; return this; } public Builder convertDurationsTo( TimeUnit durationUnit ) { this.durationUnit = durationUnit; return this; } public InfluxDBReporter build() { InfluxDB influxDB = InfluxDBFactory.connect( "http://" + host + ":" + port, login, password ); if( logger.isTraceEnabled() ) influxDB.setLogLevel( InfluxDB.LogLevel.FULL ); return new InfluxDBReporter( influxDB, database, tags, registry, "influx-reporter", filter, rateUnit, durationUnit ); } public Builder withFilter( ReporterFilter filter ) { this.filter = filter; return this; } } }
package edu.msu.nscl.olog; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.ws.rs.core.Response; import java.util.logging.Logger; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; /** * JDBC query to add a logbook to log(s). * * @author Eric Berryman taken from Ralph Lange <Ralph.Lange@bessy.de> */ public class UpdateValuesQuery { private Logger audit = Logger.getLogger(this.getClass().getPackage().getName() + ".audit"); private static SqlSessionFactory ssf = MyBatisSession.getSessionFactory(); /** * Creates a new instance of UpdateValuesQuery. * * @param data logbook data (containing logs to add logbook to) */ private UpdateValuesQuery() { } /** * Updates a logbook in the database with an incoming log * * @param name String the name of the logbook * @param logId Long the log to add to logbook * @throws CFException wrapping an SQLException */ public static XmlLogbook updateLogbookWithLog(String name, Long logId) throws CFException { SqlSession ss = ssf.openSession(); try { List<Long> ids = new ArrayList<Long>(); // Get logbook id Long pid = FindLogbookIdsQuery.getLogbookId(name); if (pid == null) { throw new CFException(Response.Status.NOT_FOUND, "A logbook named '" + name + "' does not exist"); } // Add incoming id ids.add(logId); if (ids.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs specified in Logbook update do not exist"); } HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("logidsList", ids); hm.put("logbookid", pid); hm.put("state", null); ss.insert("mappings.LogMapping.logsLogbooksEntryFromList", hm); ss.commit(); // Return the logbook now that the new log has been added return ListLogbooksQuery.findLogbook(name); } catch (PersistenceException e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "MyBatis exception: " + e); } finally { ss.close(); } } /** * Updates a logbook in the database. * * @param logbook XmlLogbook * @throws CFException wrapping an SQLException */ public static XmlLogbook updateLogbook(String name, XmlLogbook logbook) throws CFException { SqlSession ss = ssf.openSession(); try { List<Long> newestVersionIds = new ArrayList<Long>(); List<Long> ids = new ArrayList<Long>(); // Get logbook id Long pid = FindLogbookIdsQuery.getLogbookId(logbook.getName()); if (pid == null) { throw new CFException(Response.Status.NOT_FOUND, "A logbook named '" + logbook.getName() + "' does not exist"); } XmlLogbook p = ListLogbooksQuery.findLogbook(logbook.getName()); String logbookOwner = p.getOwner(); if ((name != null && !name.equals(logbook.getName())) || (logbook.getOwner() != null && !logbookOwner.equals(logbook.getOwner()))) { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("name", logbook.getName()); hm.put("owner", logbook.getOwner()); hm.put("id", pid); ss.update("mappings.LogbookMapper.updateLogbook", hm); } if (logbook.getXmlLogs() == null) { return ListLogbooksQuery.findLogbook(logbook.getName()); } for (XmlLog log : logbook.getXmlLogs().getLogs()) { if (log.getVersion() > 0) { newestVersionIds.add(log.getId()); } else { ids.add(log.getId()); } } if (!newestVersionIds.isEmpty()) { ArrayList<XmlLog> logs = (ArrayList<XmlLog>) ss.selectList("mappings.LogMapping.getChildrenIds", newestVersionIds); if (logs.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs do not exist in getChildrenIds query"); } for (XmlLog log : logs) { ids.add(log.getId()); } } if (ids.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs specified in Logbook update do not exist"); } HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("pid", pid); hm.put("list", ids); ss.update("mappings.LogMapping.updateAsInactive", hm); hm.clear(); hm.put("logidsList", ids); hm.put("logbookid", pid); hm.put("state", null); ss.insert("mappings.LogMapping.logsLogbooksEntryFromList", hm); ss.commit(); // Return the logbook now that all the changes have been made return ListLogbooksQuery.findLogbook(logbook.getName()); } catch (PersistenceException e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "MyBatis exception: " + e); } finally { ss.close(); } } /** * Updates a tag in the database, adding it to all logs in <tt>tag</tt>. * * @param tag XmlTag * @throws CFException wrapping an SQLException */ public static XmlTag updateTag(String name, XmlTag tag) throws CFException { SqlSession ss = ssf.openSession(); try { List<Long> newestVersionIds = new ArrayList<Long>(); List<Long> ids = new ArrayList<Long>(); // Get logbook id Long pid = FindLogbookIdsQuery.getLogbookId(tag.getName()); if (pid == null) { throw new CFException(Response.Status.NOT_FOUND, "A tag named '" + tag.getName() + "' does not exist"); } if (name != null && !name.equals(tag.getName())) { HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("name", tag.getName()); hm.put("id", pid); ss.update("mappings.TagMapper.updateTag", hm); } XmlTag t = ListLogbooksQuery.findTag(tag.getName()); if(t == null){ return null; } if (tag.getXmlLogs() == null) { return t; } if (tag.getXmlLogs().getLogs().isEmpty()) { return t; } for (XmlLog log : tag.getXmlLogs().getLogs()) { if (log.getVersion() > 0) { newestVersionIds.add(log.getId()); } else { ids.add(log.getId()); } } if (!newestVersionIds.isEmpty()) { ArrayList<XmlLog> logs = (ArrayList<XmlLog>) ss.selectList("mappings.LogMapping.getChildrenIds", newestVersionIds); if (logs.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs do not exist in getChildrenIds query"); } for (XmlLog log : logs) { ids.add(log.getId()); } } if (ids.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs specified in Logbook update do not exist"); } HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("pid", pid); hm.put("list", ids); ss.update("mappings.LogMapping.updateAsInactive", hm); hm.clear(); hm.put("logidsList", ids); hm.put("logbookid", pid); hm.put("state", null); ss.insert("mappings.LogMapping.logsLogbooksEntryFromList", hm); ss.commit(); // Return new tag now that the logs have been added return ListLogbooksQuery.findTag(tag.getName()); } catch (PersistenceException e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "MyBatis exception: " + e); } finally { ss.close(); } } /** * Updates the <tt>tag</tt> in the database, adding it to the single log <tt>logId</tt>. * * @param tag name of tag to add * @param logId id of log to add tag to * @throws CFException wrapping an SQLException */ public static XmlTag updateTag(String tag, Long logId) throws CFException { SqlSession ss = ssf.openSession(); try { List<Long> newestVersionIds = new ArrayList<Long>(); List<Long> ids = new ArrayList<Long>(); XmlLogs logs = new XmlLogs(new XmlLog(logId)); // Get log id Long pid = FindLogbookIdsQuery.getLogbookId(tag); if (pid == null) { throw new CFException(Response.Status.NOT_FOUND, "A tag named '" + tag + "' does not exist"); } if (logs == null) { return null; } if (logs.getLogs().isEmpty()) { return null; } for (XmlLog log : logs.getLogs()) { if (log.getVersion() > 0) { newestVersionIds.add(log.getId()); } else { ids.add(log.getId()); } } if (!newestVersionIds.isEmpty()) { ArrayList<XmlLog> logs_returned = (ArrayList<XmlLog>) ss.selectList("mappings.LogMapping.getChildrenIds", newestVersionIds); if (logs_returned.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs do not exist in getChildrenIds query"); } for (XmlLog log : logs_returned) { ids.add(log.getId()); } } if (ids.isEmpty()) { throw new CFException(Response.Status.NOT_FOUND, "Logs specified in Logbook update do not exist"); } HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("logidsList", ids); hm.put("logbookid", pid); hm.put("state", null); ss.insert("mappings.LogMapping.logsLogbooksEntryFromList", hm); ss.commit(); // Return new tag now that the new log have been added return ListLogbooksQuery.findTag(tag); } catch (PersistenceException e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "MyBatis exception: " + e); } finally { ss.close(); } } }
package test.ccn.network.daemons.repo; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.query.Interest; import com.parc.ccn.library.profiles.SegmentationProfile; /** * For now to run this you need to first run the RepoIoPutTest, then restart * the local ccnd, then run this * * @author rasmusse * */ public class RemoteRepoIOGetTest extends RepoTestBase { @Test public void testPolicyViaCCN() throws Exception { checkContent("/repoTest/data3", false); checkContent("/testNameSpace/data1", true); } @Test public void testWriteToRepo() throws Exception { System.out.println("Testing writing streams to repo"); byte [] data = new byte[4000]; byte value = 1; for (int i = 0; i < data.length; i++) data[i] = value++; for (int i = 0; i < 40; i++) { byte [] testData = new byte[100]; System.arraycopy(data, i * 100, testData, 0, 100); checkData(ContentName.fromNative("/testNameSpace/stream"), testData, i); } } private ContentObject checkContent(String contentName, boolean expected) throws Exception { return checkContent(ContentName.fromNative(contentName), expected); } private ContentObject checkContent(ContentName contentName, boolean expected) throws Exception { Interest interest = new Interest(contentName); ContentObject co = getLibrary.get(interest, 20000); if (expected) Assert.assertTrue(co != null); else Assert.assertTrue(co == null); return co; } private void checkData(ContentName currentName, byte[] testData, int i) throws Exception { ContentName segmentedName = SegmentationProfile.segmentName(currentName, i); ContentObject co = checkContent(segmentedName, true); Assert.assertTrue(Arrays.equals(testData, co.content())); } }
/* HashTableChained.java */ package com.xqbase.java.dict; import com.xqbase.java.list.DList; import java.util.Random; /** * HashTableChained implements a Dictionary as a hash table with chaining. * All objects used as keys must have a valid hashCode() method, which is * used to determine which bucket of the hash table an entry is stored in. * Each object's hashCode() is presumed to return an int between * Integer.MIN_VALUE and Integer.MAX_VALUE. The HashTableChained class * implements only the compression function, which maps the hash code to * a bucket in the table's range. * <p/> * DO NOT CHANGE ANY PROTOTYPES IN THIS FILE. */ public class HashTableChained implements Dictionary { /** The has table data .*/ private DList[] table; /** The total number of entries in the hash table. */ private int count; /** The load factor for the hash table. */ private float loadFactor; /** * Construct a new empty hash table intended to hold roughly sizeEstimate * entries. (The precise number of buckets is up to you, but we recommend * you use a prime number, and shoot for a load factor between 0.5 and 1.) */ public HashTableChained(int sizeEstimate) { loadFactor = 0.75f; table = new DList[getNearestPrime((int)Math.ceil(sizeEstimate/loadFactor))]; } /** * Construct a new empty hash table with a default size. Say, a prime in * the neighborhood of 100. */ public HashTableChained() { loadFactor = 0.75f; table = new DList[101]; } /** * Converts a hash code in the range Integer.MIN_VALUE...Integer.MAX_VALUE * to a value in the range 0...(size of hash table) - 1. * <p/> * This function should have package protection (so we can test it), and * should be used by insert, find, and remove. */ int compFunction(int code) { int p = getNearestPrime(table.length); Random r = new Random(); int a = r.nextInt(p); int b = r.nextInt(p); return ((a * code + b) % p) % table.length; } /** * Returns the number of entries stored in the dictionary. Entries with * the same key (or even the same key and value) each still count as * a separate entry. * * @return number of entries in the dictionary. */ public int size() { // Replace the following line with your solution. return count; } /** * Tests if the dictionary is empty. * * @return true if the dictionary has no entries; false otherwise. */ public boolean isEmpty() { return size() == 0; } /** * Create a new Entry object referencing the input key and associated value, * and insert the entry into the dictionary. Return a reference to the new * entry. Multiple entries with the same key (or even the same key and * value) can coexist in the dictionary. * <p/> * This method should run in O(1) time if the number of collisions is small. * * @param key the key by which the entry can be retrieved. * @param value an arbitrary object. * @return an entry containing the key and value. */ public Entry insert(Object key, Object value) { // Replace the following line with your solution. return null; } /** * Search for an entry with the specified key. If such an entry is found, * return it; otherwise return null. If several entries have the specified * key, choose one arbitrarily and return it. * <p/> * This method should run in O(1) time if the number of collisions is small. * * @param key the search key. * @return an entry containing the key and an associated value, or null if * no entry contains the specified key. */ public Entry find(Object key) { // Replace the following line with your solution. return null; } /** * Remove an entry with the specified key. If such an entry is found, * remove it from the table and return it; otherwise return null. * If several entries have the specified key, choose one arbitrarily, then * remove and return it. * <p/> * This method should run in O(1) time if the number of collisions is small. * * @param key the search key. * @return an entry containing the key and an associated value, or null if * no entry contains the specified key. */ public Entry remove(Object key) { // Replace the following line with your solution. return null; } /** * Remove all entries from the dictionary. */ public void makeEmpty() { // Your solution here. } /** * Whether a num is prime. */ private boolean isPrime(int num) { if (num == 2) return true; for (int i = 2; i <= Math.sqrt(num); i++) { if (num%i == 0) return false; } return true; } /** * Get the nearest prime number; */ private int getNearestPrime(int num) { for (int i = num; i < 2 * num; i++) { if (isPrime(i)) return i; } // This should not happen in real case. return 2; } }
package com.erakk.lnreader; import java.util.ArrayList; import java.util.Iterator; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.erakk.lnreader.adapter.ExpandListAdapter; import com.erakk.lnreader.classes.ExpandListChild; import com.erakk.lnreader.classes.ExpandListGroup; import com.erakk.lnreader.dao.NovelsDao; import com.erakk.lnreader.helper.AsyncTaskResult; import com.erakk.lnreader.model.BookModel; import com.erakk.lnreader.model.NovelCollectionModel; import com.erakk.lnreader.model.PageModel; public class LightNovelChaptersActivity extends Activity { NovelsDao dao; NovelCollectionModel novelCol; private ExpandListAdapter ExpAdapter; private ArrayList<ExpandListGroup> ExpListItems; private ExpandableListView ExpandList; @SuppressLint({ "NewApi", "NewApi" }) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Get intent and message Intent intent = getIntent(); //String novel = intent.getStringExtra(DisplayLightNovelsActivity.EXTRA_MESSAGE); PageModel page = new PageModel(); page.setPage(intent.getStringExtra(Constants.EXTRA_PAGE)); page.setTitle(intent.getStringExtra(Constants.EXTRA_TITLE)); setContentView(R.layout.activity_light_novel_chapters); getActionBar().setDisplayHomeAsUpEnabled(true); //View NovelView = findViewById(R.id.ligh_novel_chapter_screen); // get the textView SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); boolean invertColors = sharedPrefs.getBoolean("invert_colors", false); if (invertColors == true) { /*textViewSynopsys.setBackgroundColor(Color.TRANSPARENT); textViewSynopsys.setTextColor(Color.WHITE); textViewTitle.setBackgroundColor(Color.TRANSPARENT); textViewTitle.setTextColor(Color.WHITE); NovelView.setBackgroundColor(Color.BLACK);*/ } dao = new NovelsDao(this); try { new LoadNovelDetailsTask().execute(new PageModel[] {page}); } catch (Exception e) { // TODO Auto-generated catch block Toast t = Toast.makeText(this, e.getClass().toString() +": " + e.getMessage(), Toast.LENGTH_SHORT); t.show(); } // setup listener ExpandList = (ExpandableListView) findViewById(R.id.chapter_list); ExpandList.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if(novelCol != null) { PageModel p = novelCol.getBookCollections().get(groupPosition).getChapterCollection().get(childPosition); Intent intent = new Intent(getApplicationContext(), DisplayNovelContentActivity.class); intent.putExtra(Constants.EXTRA_PAGE, p.getPage()); intent.putExtra(Constants.EXTRA_TITLE, p.getTitle()); startActivity(intent); } return false; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_light_novel_chapters, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_settings: Intent launchNewIntent = new Intent(this, DisplaySettingsActivity.class); startActivity(launchNewIntent); return true; case R.id.menu_refresh_chapter_list: /* * Implement code to refresh chapter/synopsis list */ Toast.makeText(getApplicationContext(), "Refreshing", Toast.LENGTH_SHORT).show(); return true; case R.id.invert_colors: /* * Implement code to invert colors */ Toast.makeText(getApplicationContext(), "Colors inverted", Toast.LENGTH_SHORT).show(); return true; case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); Toast t = Toast.makeText(LightNovelChaptersActivity.this, "onCreateContextMenu", Toast.LENGTH_SHORT); ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; int type = ExpandableListView.getPackedPositionType(info.packedPosition); if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) { // if (v == findViewById(R.layout.expandvolume_list_item)) { inflater.inflate(R.menu.synopsys_volume_context_menu, menu); } else if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { // } else if (v == findViewById(R.layout.expandchapter_list_item)) { inflater.inflate(R.menu.synopsys_chapter_context_menu, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); //String[] names = getResources().getStringArray(R.array.novel_context_menu); switch(item.getItemId()) { //Volume cases case R.id.download_volume: /* * Implement code to download this volume */ Toast.makeText(this, "Download this Volume", Toast.LENGTH_SHORT).show(); return true; case R.id.clear_volume: /* * Implement code to clear this volume cache */ Toast.makeText(this, "Clear this Volume", Toast.LENGTH_SHORT).show(); return true; case R.id.mark_volume: /* * Implement code to mark entire volume as read */ Toast.makeText(this, "Mark Volume as Read", Toast.LENGTH_SHORT).show(); return true; //Chapter cases case R.id.download_chapter: /* * Implement code to download this chapter */ Toast.makeText(this, "Download this chapter", Toast.LENGTH_SHORT).show(); return true; case R.id.clear_chapter: /* * Implement code to clear this chapter cache */ Toast.makeText(this, "Clear this Chapter", Toast.LENGTH_SHORT).show(); return true; case R.id.mark_read: /* * Implement code to mark this chapter read */ Toast.makeText(this, "Mark as Read", Toast.LENGTH_SHORT).show(); return true; default: return super.onContextItemSelected(item); } } public class LoadNovelDetailsTask extends AsyncTask<PageModel, ProgressBar, AsyncTaskResult<NovelCollectionModel>> { @SuppressLint("NewApi") @Override protected AsyncTaskResult<NovelCollectionModel> doInBackground(PageModel... arg0) { PageModel page = arg0[0]; ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar2); pb.setIndeterminate(true); pb.setActivated(true); pb.animate(); try { NovelCollectionModel novelCol = dao.getNovelDetails(page); Log.d("LoadNovelDetailsTask", "Loaded: " + novelCol.getPage()); return new AsyncTaskResult<NovelCollectionModel>(novelCol); } catch (Exception e) { e.printStackTrace(); Log.e("NovelDetails", e.getClass().toString() + ": " + e.getMessage()); return new AsyncTaskResult<NovelCollectionModel>(e); } } @SuppressLint("NewApi") protected void onPostExecute(AsyncTaskResult<NovelCollectionModel> result) { ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar2); pb.setActivated(false); pb.setVisibility(ProgressBar.GONE); novelCol = result.getResult(); if(novelCol != null) { //Clear progressBar and string TextView tv = (TextView) findViewById(R.id.loading); tv.setVisibility(TextView.GONE); pb.setActivated(false); pb.setVisibility(ProgressBar.GONE); ExpandList = (ExpandableListView) findViewById(R.id.chapter_list); // Prepare header LayoutInflater layoutInflater = getLayoutInflater(); View synopsis = layoutInflater.inflate(R.layout.activity_display_synopsis, null); synopsis.findViewById(R.id.loading).setVisibility(TextView.GONE); synopsis.findViewById(R.id.progressBar2).setVisibility(ProgressBar.GONE); TextView textViewTitle = (TextView) synopsis.findViewById(R.id.title); TextView textViewSynopsis = (TextView) synopsis.findViewById(R.id.synopsys); textViewTitle.setTextSize(20); textViewSynopsis.setTextSize(16); textViewTitle.setText(novelCol.getPageModel().getTitle()); textViewSynopsis.setText(novelCol.getSynopsis()); ImageView ImageViewCover = (ImageView) synopsis.findViewById(R.id.cover); if (novelCol.getCoverBitmap() == null) { // IN app test, is returning empty bitmap Toast tst = Toast.makeText(getApplicationContext(), "Bitmap empty", Toast.LENGTH_LONG); tst.show(); } else { ImageViewCover.setImageBitmap(novelCol.getCoverBitmap()); } ExpandList.addHeaderView(synopsis); // now add the volume and chapter list. try { ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>(); for(Iterator<BookModel> i = novelCol.getBookCollections().iterator(); i.hasNext();) { BookModel book = i.next(); ExpandListGroup volume = new ExpandListGroup(); volume.setName(book.getTitle()); list.add(volume); ArrayList<ExpandListChild> list2 = new ArrayList<ExpandListChild>(); for(Iterator<PageModel> i2 = book.getChapterCollection().iterator(); i2.hasNext();){ PageModel chapter = i2.next(); ExpandListChild chapter_page = new ExpandListChild(); chapter_page.setName(chapter.getTitle()); // chapter_page.setName(chapter.getTitle() + " (" + chapter.getPage() + ")"); chapter_page.setTag(null); list2.add(chapter_page); } volume.setItems(list2); } ExpListItems = list; ExpAdapter = new ExpandListAdapter(LightNovelChaptersActivity.this, ExpListItems); ExpandList.setAdapter(ExpAdapter); } catch (Exception e) { e.getStackTrace(); Toast t = Toast.makeText(LightNovelChaptersActivity.this, e.getClass().toString() +": " + e.getMessage(), Toast.LENGTH_SHORT); t.show(); } } if(result.getError() != null) { Exception e = result.getError(); Toast t = Toast.makeText(getApplicationContext(), e.getClass().toString() + ": " + e.getMessage(), Toast.LENGTH_SHORT); t.show(); Log.e(this.getClass().toString(), e.getClass().toString() + ": " + e.getMessage()); } } } }
package com.qulice.xml; import com.jcabi.log.Logger; import com.jcabi.xml.StrictXML; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import com.jcabi.xml.XSDDocument; import com.qulice.spi.Environment; import com.qulice.spi.ValidationException; import com.qulice.spi.Validator; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.xml.sax.SAXException; /** * Validates XML files for formatting. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public final class XmlValidator implements Validator { @Override public void validate(final Environment env) throws ValidationException { try { for (final File file : env.files("*.xml")) { final String name = file.getAbsolutePath().substring( env.basedir().toString().length() ); if (env.exclude("xml", name)) { Logger.info(this, "%s: skipped", name); continue; } Logger.info(this, "%s: to be validated", name); final XML document = new XMLDocument(file); final List<String> schemas = document .xpath("/*/@xsi:schemaLocation"); if (schemas.isEmpty()) { throw new ValidationException( String.format( "XML validation exception: missing schema in %s", name ) ); } else { final String schema = schemas.get(0); try { new StrictXML( document, new XSDDocument( URI.create( StringUtils.substringAfter(schema, " ") ).toURL() ) ); } catch (final IllegalStateException ex) { if (ex.getCause() != null && ex.getCause() instanceof SAXException) { Logger.warn( // @checkstyle LineLength (1 line) this, "Failed to validate file %s against schema %s. Cause: %s", name, schema, ex.toString() ); } } } } } catch (final IOException ex) { throw new IllegalStateException(ex); } } }
package org.jboss.as.cli.handlers; import java.io.File; import java.io.IOException; import java.util.List; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandFormatException; import org.jboss.as.cli.Util; import org.jboss.as.cli.batch.BatchManager; import org.jboss.as.cli.util.StrictSizeTable; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.vfs.TempFileProvider; import org.jboss.vfs.VFS; import org.jboss.vfs.spi.MountHandle; /** * Base class for deploy and undeploy handlers containing common code * for these handlers. * * @author Alexey Loubyansky */ public abstract class DeploymentHandler extends BatchModeCommandHandler { static final String CLI_ARCHIVE_SUFFIX = ".cli"; public DeploymentHandler(CommandContext ctx, String command, boolean connectionRequired) { super(ctx, command, connectionRequired); } protected void listDeployments(CommandContext ctx, boolean l) throws CommandFormatException { if(!l) { printList(ctx, Util.getDeployments(ctx.getModelControllerClient()), l); return; } final ModelControllerClient client = ctx.getModelControllerClient(); final List<String> names = Util.getDeployments(client); if(names.isEmpty()) { return; } final StrictSizeTable table = new StrictSizeTable(names.size()); final List<Property> descriptions = getDeploymentDescriptions(ctx, names).asPropertyList(); for(Property prop : descriptions) { final ModelNode step = prop.getValue(); if(step.hasDefined(Util.RESULT)) { final ModelNode result = step.get(Util.RESULT); table.addCell(Util.NAME, result.get(Util.NAME).asString()); table.addCell(Util.RUNTIME_NAME, result.get(Util.RUNTIME_NAME).asString()); if(result.has(Util.ENABLED)) { table.addCell(Util.ENABLED, result.get(Util.ENABLED).asString()); } if(result.has(Util.STATUS)) { table.addCell(Util.STATUS, result.get(Util.STATUS).asString()); } } if(!table.isAtLastRow()) { table.nextRow(); } } ctx.printLine(table.toString()); } protected ModelNode getDeploymentDescriptions(CommandContext ctx, List<String> names) throws CommandFormatException { final ModelNode composite = new ModelNode(); composite.get(Util.OPERATION).set(Util.COMPOSITE); composite.get(Util.ADDRESS).setEmptyList(); final ModelNode steps = composite.get(Util.STEPS); for(String name : names) { final ModelNode deploymentResource = buildReadDeploymentResourceRequest(name); if(deploymentResource != null) { steps.add(deploymentResource); } } ModelNode result; try { result = ctx.getModelControllerClient().execute(composite); } catch (IOException e) { throw new CommandFormatException("Failed to execute operation request.", e); } if (!result.hasDefined(Util.RESULT)) { return null; } return result.get(Util.RESULT); } protected ModelNode buildReadDeploymentResourceRequest(String name) { ModelNode request = new ModelNode(); ModelNode address = request.get(Util.ADDRESS); address.add(Util.DEPLOYMENT, name); request.get(Util.OPERATION).set(Util.READ_RESOURCE); request.get(Util.INCLUDE_RUNTIME).set(true); return request; } protected MountHandle extractArchive(File archive, TempFileProvider tempFileProvider) throws IOException { return ((MountHandle)VFS.mountZipExpanded(archive, VFS.getChild("cli"), tempFileProvider)); } protected String activateNewBatch(CommandContext ctx) { String currentBatch = null; BatchManager batchManager = ctx.getBatchManager(); if (batchManager.isBatchActive()) { currentBatch = "batch" + System.currentTimeMillis(); batchManager.holdbackActiveBatch(currentBatch); } batchManager.activateNewBatch(); return currentBatch; } protected void discardBatch(CommandContext ctx, String holdbackBatch) { BatchManager batchManager = ctx.getBatchManager(); batchManager.discardActiveBatch(); if (holdbackBatch != null) { batchManager.activateHeldbackBatch(holdbackBatch); } } protected boolean isCliArchive(File f) { if (f == null || f.isDirectory() || !f.getName().endsWith(CLI_ARCHIVE_SUFFIX)) { return false; } else { return true; } } }
package de.qaware.chronix.client; import de.qaware.chronix.client.benchmark.benchmarkrunner.BenchmarkRunner; import de.qaware.chronix.database.BenchmarkDataSource; import de.qaware.chronix.shared.ServerConfig.ServerConfigAccessor; import de.qaware.chronix.shared.ServerConfig.ServerConfigRecord; import de.qaware.chronix.shared.ServerConfig.TSDBInterfaceHandler; import java.io.File; import java.util.LinkedList; import java.util.List; public class BenchmarkImport { public static void main(String[] args){ if(args.length < 7){ printImportUsage(); return; } List<String> tsdbImportList = new LinkedList<>(); List<File> importDirectories = new LinkedList<>(); String server = args[0]; int batchSize; int fromFile; try{ batchSize = Integer.valueOf(args[1]); fromFile = Integer.valueOf(args[2]); for(int i = 3; i < args.length - 1; i = i + 2 ){ if(args[i].equals("-t")){ tsdbImportList.add(args[i+1]); } if(args[i].equals("-d")){ File dir = new File(args[i+1]); if(dir.exists() && dir.isDirectory()){ importDirectories.add(dir); } } } } catch (Exception e){ System.err.println("Error processing your entries: " + e.getLocalizedMessage()); return; } // print info for user System.out.println("Recognized entries: \n"); System.out.println("Server: " + server); System.out.println("BatchSize: " + batchSize); System.out.println("fromFile: " + fromFile); tsdbImportList.forEach(s -> System.out.println("TSDB: " + s)); importDirectories.forEach(dir -> System.out.println("Directory: " + dir.getAbsolutePath())); //check if server is configured ServerConfigAccessor serverConfigAccessor = ServerConfigAccessor.getInstance(); ServerConfigRecord serverConfig = serverConfigAccessor.getServerConfigRecord(server); if(serverConfig == null){ System.err.println("Server: " + server + " was not configured."); return; } // check if tsdb interface is imported. LinkedList<String> configuredTsdbImpls = serverConfig.getExternalTimeSeriesDataBaseImplementations(); List<String> removeTsdbList = new LinkedList<>(); for(String tsdb : tsdbImportList) { if(!configuredTsdbImpls.contains(tsdb)){ removeTsdbList.add(tsdb); System.err.println("No interface found for: " + tsdb + " -> rejected!"); } } tsdbImportList.removeAll(removeTsdbList); if(tsdbImportList.isEmpty()){ System.out.println("No Tsdb given for import"); return; } if(importDirectories.isEmpty()){ System.out.println("No directory given for import"); return; } BenchmarkRunner benchmarkRunner = BenchmarkRunner.getInstance(); for(File directory : importDirectories) { System.out.println("\nImporting directory: " + directory); benchmarkRunner.importTimeSeriesFromDirectory(server, directory, batchSize, fromFile, tsdbImportList); } System.out.println("\nDownloading benchmark records from server successful: " + benchmarkRunner.getBenchmarkRecordsFromServer(server)); } private static void printImportUsage(){ System.out.println("Import usage: import [server] [batchSize] [fromFile] -t [tsdbName1] -t [tsdbName2] ... -d [directoryToImport1] -d [directoryToImport2] ..."); System.out.println("Example: import localhost 25 0 -t someTsdb -d /home/someUser/chronixBenchmark/timeseries_records/someFolder"); System.out.println("NOTICE: paths have to be absolute paths!"); } }
package org.bouncycastle.est; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Set; import org.bouncycastle.util.Properties; import org.bouncycastle.util.Strings; /** * A basic http response. */ public class ESTResponse { private final ESTRequest originalRequest; private final HttpUtil.Headers headers; private final byte[] lineBuffer; private final Source source; private String HttpVersion; private int statusCode; private String statusMessage; private InputStream inputStream; private Long contentLength; private long read = 0; private Long absoluteReadLimit; private static final Long ZERO = 0L; public ESTResponse(ESTRequest originalRequest, Source source) throws IOException { this.originalRequest = originalRequest; this.source = source; if (source instanceof LimitedSource) { this.absoluteReadLimit = ((LimitedSource)source).getAbsoluteReadLimit(); } Set<String> opts = Properties.asKeySet("org.bouncycastle.debug.est"); if (opts.contains("input") || opts.contains("all")) { this.inputStream = new PrintingInputStream(source.getInputStream()); } else { this.inputStream = source.getInputStream(); } this.headers = new HttpUtil.Headers(); this.lineBuffer = new byte[1024]; process(); } private void process() throws IOException { // Status line. HttpVersion = readStringIncluding(' '); this.statusCode = Integer.parseInt(readStringIncluding(' ')); this.statusMessage = readStringIncluding('\n'); // Headers. String line = readStringIncluding('\n'); int i; while (line.length() > 0) { i = line.indexOf(':'); if (i > -1) { String k = Strings.toLowerCase(line.substring(0, i).trim()); // Header keys are case insensitive headers.add(k, line.substring(i + 1).trim()); } line = readStringIncluding('\n'); } contentLength = getContentLength(); // Concerned that different servers may or may not set a Content-length // for these success types. In this case we will arbitrarily set content length // to zero. if (statusCode == 204 || statusCode == 202) { if (contentLength == null) { contentLength = 0L; } else { if (statusCode == 204 && contentLength > 0) { throw new IOException("Got HTTP status 204 but Content-length > 0."); } } } if (contentLength == null) { throw new IOException("No Content-length header."); } if (contentLength.equals(ZERO)) { // The server is likely to hang up the socket and any attempt to read can // result in a broken pipe rather than an eof. // So we will return a dummy input stream that will return eof to anything that reads from it. inputStream = new InputStream() { public int read() throws IOException { return -1; } }; } if (contentLength < 0) { throw new IOException("Server returned negative content length: " + absoluteReadLimit); } if (absoluteReadLimit != null && contentLength >= absoluteReadLimit) { throw new IOException("Content length longer than absolute read limit: " + absoluteReadLimit + " Content-Length: " + contentLength); } inputStream = wrapWithCounter(inputStream, absoluteReadLimit); // Observed that some if ("base64".equalsIgnoreCase(getHeader("content-transfer-encoding"))) { inputStream = new CTEBase64InputStream(inputStream, getContentLength()); } } public String getHeader(String key) { return headers.getFirstValue(key); } protected InputStream wrapWithCounter(final InputStream in, final Long absoluteReadLimit) { return new InputStream() { public int read() throws IOException { int i = in.read(); if (i > -1) { read++; if (absoluteReadLimit != null && read >= absoluteReadLimit) { throw new IOException("Absolute Read Limit exceeded: " + absoluteReadLimit); } } return i; } public void close() throws IOException { if (contentLength != null && contentLength - 1 > read) { throw new IOException("Stream closed before limit fully read, Read: " + read + " ContentLength: " + contentLength); } if (in.available() > 0) { throw new IOException("Stream closed with extra content in pipe that exceeds content length."); } in.close(); } }; } protected String readStringIncluding(char until) throws IOException { int c = 0; int j; do { j = inputStream.read(); lineBuffer[c++] = (byte)j; if (c >= lineBuffer.length) { throw new IOException("Server sent line > " + lineBuffer.length); } } while (j != until && j > -1); if (j == -1) { throw new EOFException(); } return new String(lineBuffer, 0, c).trim(); } public ESTRequest getOriginalRequest() { return originalRequest; } public HttpUtil.Headers getHeaders() { return headers; } public String getHttpVersion() { return HttpVersion; } public int getStatusCode() { return statusCode; } public String getStatusMessage() { return statusMessage; } public InputStream getInputStream() { return inputStream; } public Source getSource() { return source; } public Long getContentLength() { String v = headers.getFirstValue("Content-Length"); if (v == null) { return null; } try { return Long.parseLong(v); } catch (RuntimeException nfe) { throw new RuntimeException("Content Length: '" + v + "' invalid. " + nfe.getMessage()); } } public void close() throws IOException { if (inputStream != null) { inputStream.close(); } this.source.close(); } private class PrintingInputStream extends InputStream { private final InputStream src; private PrintingInputStream(InputStream src) { this.src = src; } public int read() throws IOException { int i = src.read(); return i; } public int available() throws IOException { return src.available(); } public void close() throws IOException { src.close(); } } }
public class pecas { private String nome; private double custo; public pecas(){ nome = "NULL"; custo = 0; } public pecas(String nome, double custo){ this.nome = nome; this.custo = custo; } public String getNome(){ return nome; } public double getCusto(){ return custo; } public void setNome(String nome){ this.nome = nome; } public void setCusto(double custo){ this.custo = custo; } }
package com.thoughtworks.selenium; import java.io.*; import junit.extensions.*; import junit.framework.*; import org.openqa.selenium.server.*; public class I18nTest extends TestCase { private static String startUrl = "http://localhost:" + SeleniumServer.getDefaultPort(); private static Selenium sel; //private static SeleniumServer server; public static Test suite() { return new I18nTestSetup(new TestSuite(I18nTest.class)); } private static class I18nTestSetup extends TestSetup { public I18nTestSetup(Test test) { super(test); } public void setUp() throws Exception { //server = new SeleniumServer(); //server.start(); try { sel = new DefaultSelenium("localhost", SeleniumServer.getDefaultPort(), "*firefox", startUrl); sel.start(); sel.open(startUrl + "/selenium-server/tests/html/test_i18n.html"); } catch (Exception e) { e.printStackTrace(); throw e; } } public void tearDown() throws Exception { try { sel.stop(); } catch (Exception e) { throw e; } //server.stop(); } } public void testRomance() throws UnsupportedEncodingException { String expected = "\u00FC\u00F6\u00E4\u00DC\u00D6\u00C4 \u00E7\u00E8\u00E9 \u00BF\u00F1 \u00E8\u00E0\u00F9\u00F2"; String id = "romance"; verifyText(expected, id); } public void testKorean() throws UnsupportedEncodingException { String expected = "\uC5F4\uC5D0"; String id = "korean"; verifyText(expected, id); } public void testChinese() throws UnsupportedEncodingException { String expected = "\u4E2D\u6587"; String id = "chinese"; verifyText(expected, id); } public void testJapanese() throws UnsupportedEncodingException { String expected = "\u307E\u3077"; String id = "japanese"; verifyText(expected, id); } public void testDangerous() throws UnsupportedEncodingException { String expected = "&%?\\+|,%*"; String id = "dangerous"; verifyText(expected, id); } private void verifyText(String expected, String id) throws UnsupportedEncodingException { System.out.println(getName()); System.out.println(expected); assertTrue(sel.isTextPresent(expected)); String actual = sel.getText(id); byte[] result = actual.getBytes("UTF-8"); for (int i = 0; i < result.length; i++) { Byte b = new Byte(result[i]); System.out.println("BYTE " + i + ": " + b.toString()); } assertEquals(id + " characters didn't match", expected, actual); } }
package com.mercadopago; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.text.Spanned; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.mercadopago.callbacks.FailureRecovery; import com.mercadopago.core.MercadoPago; import com.mercadopago.model.Instruction; import com.mercadopago.model.InstructionActionInfo; import com.mercadopago.model.InstructionReference; import com.mercadopago.model.Payment; import com.mercadopago.model.PaymentMethod; import com.mercadopago.util.ApiUtil; import com.mercadopago.util.CurrenciesUtil; import com.mercadopago.util.ErrorUtil; import com.mercadopago.util.LayoutUtil; import com.mercadopago.util.ScaleUtil; import com.mercadopago.views.MPButton; import com.mercadopago.views.MPTextView; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class InstructionsActivity extends AppCompatActivity { //Values protected MercadoPago mMercadoPago; protected FailureRecovery failureRecovery; protected Boolean mBackPressedOnce; //Controls protected LinearLayout mReferencesLayout; protected Activity mActivity; protected MPTextView mTitle; protected MPTextView mPrimaryInfo; protected MPTextView mSecondaryInfo; protected MPTextView mTertiaryInfo; protected MPTextView mAccreditationMessage; protected MPButton mActionButton; protected MPTextView mExitTextView; //Params protected Payment mPayment; protected String mMerchantPublicKey; protected PaymentMethod mPaymentMethod; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_instructions); getActivityParameters(); initializeControls(); mBackPressedOnce = false; mActivity = this; mMercadoPago = new MercadoPago.Builder() .setContext(this) .setPublicKey(mMerchantPublicKey) .build(); getInstructionsAsync(); } protected void getInstructionsAsync() { LayoutUtil.showProgressLayout(this); mMercadoPago.getInstructions(mPayment.getId(), mPaymentMethod.getId(), mPaymentMethod.getPaymentTypeId(), new Callback<Instruction>() { @Override public void success(Instruction instruction, Response response) { showInstructions(instruction); LayoutUtil.showRegularLayout(mActivity); } @Override public void failure(RetrofitError error) { ApiUtil.showApiExceptionError(mActivity, error); failureRecovery = new FailureRecovery() { @Override public void recover() { getInstructionsAsync(); } }; } }); } protected void showInstructions(Instruction instruction) { setTitle(instruction.getTitle()); setInformationMessages(instruction); setReferencesInformation(instruction); mAccreditationMessage.setText(instruction.getAcreditationMessage()); setActions(instruction); } protected void setTitle(String title) { Spanned formattedTitle = CurrenciesUtil.formatCurrencyInText(mPayment.getTransactionAmount(), mPayment.getCurrencyId(), title, true, true); mTitle.setText(formattedTitle); } protected void setActions(Instruction instruction) { if(instruction.getActions() != null && !instruction.getActions().isEmpty()) { final InstructionActionInfo actionInfo = instruction.getActions().get(0); if(actionInfo.getUrl() != null && !actionInfo.getUrl().isEmpty()) { mActionButton.setVisibility(View.VISIBLE); mActionButton.setText(actionInfo.getLabel()); mActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(actionInfo.getUrl())); startActivity(browserIntent); } }); } } } protected void setReferencesInformation(Instruction instruction) { LinearLayout.LayoutParams marginParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); int marginTop = ScaleUtil.getPxFromDp(3, this); int marginBottom = ScaleUtil.getPxFromDp(20, this); marginParams.setMargins(0, marginTop, 0, marginBottom); for(InstructionReference reference : instruction.getReferences()) { MPTextView currentTitleTextView = new MPTextView(this); MPTextView currentValueTextView = new MPTextView(this); if(reference.hasValue()) { if (reference.hasLabel()) { currentTitleTextView.setText(reference.getLabel().toUpperCase()); currentTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.mpsdk_smaller_text)); mReferencesLayout.addView(currentTitleTextView); } String formattedReference = reference.getFormattedReference(); int referenceSize = getTextSizeForReference(formattedReference, reference.getSeparator()); currentValueTextView.setText(formattedReference); currentValueTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, referenceSize); currentValueTextView.setLayoutParams(marginParams); mReferencesLayout.addView(currentValueTextView); } } } private int getTextSizeForReference(String formattedReference, String separator) { int textSize; String referenceWithoutSeparator = separator == null ? formattedReference :formattedReference.replace(separator, ""); if(android.text.TextUtils.isDigitsOnly(referenceWithoutSeparator)) { textSize = getResources().getDimensionPixelSize(R.dimen.mpsdk_large_text); } else { textSize = getResources().getDimensionPixelSize(R.dimen.mpsdk_regular_text); } return textSize; } private void setInformationMessages(Instruction instruction) { if(instruction.getInfo() != null && !instruction.getInfo().isEmpty()) { mPrimaryInfo.setText(Html.fromHtml(getInfoHtmlText(instruction.getInfo()))); } else { mPrimaryInfo.setVisibility(View.GONE); } if(instruction.getSecondaryInfo() != null && !instruction.getSecondaryInfo().isEmpty()) { mSecondaryInfo.setText(Html.fromHtml(getInfoHtmlText(instruction.getSecondaryInfo()))); } else { mSecondaryInfo.setVisibility(View.GONE); } if(instruction.getTertiaryInfo() != null && !instruction.getTertiaryInfo().isEmpty()) { mTertiaryInfo.setText(Html.fromHtml(getInfoHtmlText(instruction.getTertiaryInfo()))); } else { mTertiaryInfo.setVisibility(View.GONE); } } protected String getInfoHtmlText(List<String> info) { StringBuilder stringBuilder = new StringBuilder(); for(String line : info) { stringBuilder.append(line); if(!line.equals(info.get(info.size() - 1))) { stringBuilder.append("<br/>"); } } return stringBuilder.toString(); } protected void getActivityParameters() { mPayment = (Payment) getIntent().getSerializableExtra("payment"); mMerchantPublicKey = this.getIntent().getStringExtra("merchantPublicKey"); mPaymentMethod = (PaymentMethod) getIntent().getSerializableExtra("paymentMethod"); } protected void initializeControls() { mReferencesLayout = (LinearLayout) findViewById(R.id.referencesLayout); mTitle = (MPTextView) findViewById(R.id.title); mPrimaryInfo = (MPTextView) findViewById(R.id.primaryInfo); mSecondaryInfo = (MPTextView) findViewById(R.id.secondaryInfo); mTertiaryInfo = (MPTextView) findViewById(R.id.tertiaryInfo); mAccreditationMessage = (MPTextView) findViewById(R.id.accreditationMessage); mActionButton = (MPButton) findViewById(R.id.actionButton); mExitTextView = (MPTextView) findViewById(R.id.exitTextView); mExitTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); animateOut(); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == ErrorUtil.ERROR_REQUEST_CODE) { if(resultCode == RESULT_OK) { recoverFromFailure(); } else { setResult(RESULT_CANCELED, data); finish(); } } } private void animateOut() { overridePendingTransition(R.anim.slide_right_to_left_in, R.anim.slide_right_to_left_out); } private void recoverFromFailure() { if(failureRecovery != null) { failureRecovery.recover(); } } @Override public void onBackPressed() { if(mBackPressedOnce) { super.onBackPressed(); } else { Snackbar.make(mTertiaryInfo, getString(R.string.mpsdk_press_again_to_leave), Snackbar.LENGTH_LONG).show(); mBackPressedOnce = true; resetBackPressedOnceIn(4000); } } private void resetBackPressedOnceIn(final int mills) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(mills); mBackPressedOnce = false; } catch (InterruptedException e) { //Do nothing } } }).start(); } }
package com.playseeds.android.sdk; import com.playseeds.android.sdk.inappmessaging.InAppMessage; import com.playseeds.android.sdk.inappmessaging.InAppMessageListener; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; @RunWith(SeedsTestsRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class SeedsTests { public static final String SERVER = "http://devdash.playseeds.com"; public static final String NO_ADS_APP_KEY = "ef2444ec9f590d24db5054fad8385991138a394b"; public static final String UNLIMITED_ADS_APP_KEY = "c30f02a55541cbe362449d29d83d777c125c8dd6"; @Test public void testSeedsCustomId() { Seeds.sharedInstance() .init(ShadowApplication.getInstance().getApplicationContext( ), null, SERVER, UNLIMITED_ADS_APP_KEY, "some fake"); } @Test public void testSeedsCustomIdExplicit() { Seeds.sharedInstance() .init(ShadowApplication.getInstance().getApplicationContext( ), null, SERVER, UNLIMITED_ADS_APP_KEY, "some fake", DeviceId.Type.DEVELOPER_SUPPLIED); } @Test public void testSeedsUDIDUsage() { Seeds.sharedInstance() .init(ShadowApplication.getInstance().getApplicationContext( ), null, SERVER, UNLIMITED_ADS_APP_KEY, null, DeviceId.Type.OPEN_UDID); } @Test public void testSeedsAdIdUsage() { Seeds.sharedInstance() .init(ShadowApplication.getInstance().getApplicationContext(), null, SERVER, UNLIMITED_ADS_APP_KEY, null, DeviceId.Type.ADVERTISING_ID); } @Test public void testSeedInAppMessageShown() { InAppMessageListener listener = new InAppMessageListener() { @Override public void inAppMessageClicked() { } @Override public void inAppMessageClosed(InAppMessage inAppMessage, boolean completed) { } @Override public void inAppMessageLoadSucceeded(InAppMessage inAppMessage) { } @Override public void inAppMessageShown(InAppMessage inAppMessage, boolean succeeded) { } @Override public void noInAppMessageFound() { } }; Seeds.sharedInstance() .init(ShadowApplication.getInstance().getApplicationContext(), listener, SERVER, UNLIMITED_ADS_APP_KEY); Seeds.sharedInstance().requestInAppMessage(); // WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class); // activity.findViewById(R.id.login).performClick(); // Intent expectedIntent = new Intent(activity, WelcomeActivity.class); // assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent); } // - (void)testSeedInAppMessageShown { // [Seeds.sharedInstance start:YOUR_APP_KEY withHost:YOUR_SERVER]; // NSDate *fiveSeconds = [NSDate dateWithTimeIntervalSinceNow:5.0]; // if ([[Seeds sharedInstance] isInAppMessageLoaded]) { // [[Seeds sharedInstance] showInAppMessageIn:_testVC]; // } else { // [[Seeds sharedInstance] requestInAppMessage]; // XCTAssertTrue(_seedsInAppMessageShown, @"in app message not shown"); // XCTAssertTrue(_seedsInAppMessageLoaded, @"not loaded"); // XCTAssertFalse(_seedsNotFound, @"not found"); // - (void)testSeedInAppMessageShownNeverAds { // [[Seeds sharedInstance] start:YOUR_APP_KEY_NEVER withHost:YOUR_SERVER]; // NSDate *fiveSeconds = [NSDate dateWithTimeIntervalSinceNow:5.0]; // if ([[Seeds sharedInstance] isInAppMessageLoaded]) { // [[Seeds sharedInstance] showInAppMessageIn:_testVC]; // } else { // [[Seeds sharedInstance] requestInAppMessage]; // XCTAssertFalse(_seedsInAppMessageLoadedNever, @"Message loaded"); // - (void)testSeedInAppMessageShownAlwaysAds { // [[Seeds sharedInstance] start:YOUR_APP_KEY_ALWAYS withHost:YOUR_SERVER]; // NSDate *fiveSeconds = [NSDate dateWithTimeIntervalSinceNow:5.0]; // if ([[Seeds sharedInstance] isInAppMessageLoaded]) { // [[Seeds sharedInstance] showInAppMessageIn:_testVC]; // } else { // [[Seeds sharedInstance] requestInAppMessage]; // XCTAssertTrue(_seedsInAppMessageLoadedAlways, @"Message not loaded"); // #pragma mark - SeedsInAppMessageDelegate // - (void)seedsInAppMessageShown:(SeedsInAppMessage*)inAppMessage withSuccess:(BOOL)success { // if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY]) { // _seedsInAppMessageShown = success; // } else if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY_NEVER]) { // _seedsInAppMessageShownNever = success; // } else if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY_ALWAYS]) { // _seedsInAppMessageShownAlways = success; // - (void)seedsInAppMessageLoadSucceeded:(SeedsInAppMessage*)inAppMessage { // if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY]) { // _seedsInAppMessageLoaded = YES; // } else if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY_NEVER]) { // _seedsInAppMessageLoadedNever = YES; // } else if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY_ALWAYS]) { // _seedsInAppMessageLoadedAlways = YES; // [[Seeds sharedInstance] showInAppMessageIn:_testVC]; // - (void)seedsNoInAppMessageFound { // if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY]) { // _seedsNotFound = YES; // } else if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY_NEVER]) { // _seedsNotFoundNever = YES; // } else if ([[[Seeds sharedInstance] getAppKey] isEqualToString:YOUR_APP_KEY_ALWAYS]) { // _seedsNotFoundAlways = YES; }
package com.xqbase.metric.collector; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Logger; import java.util.zip.InflaterInputStream; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.xqbase.metric.common.Metric; import com.xqbase.metric.common.MetricEntry; import com.xqbase.util.ByteArrayQueue; import com.xqbase.util.Conf; import com.xqbase.util.Log; import com.xqbase.util.Numbers; import com.xqbase.util.Runnables; import com.xqbase.util.ShutdownHook; import com.xqbase.util.Time; public class Collector { private static final int MAX_BUFFER_SIZE = 64000; private static String decode(String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } } private static BasicDBObject row(Map<String, String> tagMap, int now, int count, double sum, double max, double min, double sqr) { BasicDBObject row = new BasicDBObject(tagMap); row.put("_minute", Integer.valueOf(now)); row.put("_count", Integer.valueOf(count)); row.put("_sum", Double.valueOf(sum)); row.put("_max", Double.valueOf(max)); row.put("_min", Double.valueOf(min)); row.put("_sqr", Double.valueOf(sqr)); return row; } private static void put(HashMap<String, ArrayList<DBObject>> rowsMap, String name, DBObject row) { ArrayList<DBObject> rows = rowsMap.get(name); if (rows == null) { rows = new ArrayList<>(); rowsMap.put(name, rows); } rows.add(row); } private static void insert(DB db, HashMap<String, ArrayList<DBObject>> rowsMap) { for (Map.Entry<String, ArrayList<DBObject>> entry : rowsMap.entrySet()) { String name = entry.getKey(); ArrayList<DBObject> rows = entry.getValue(); db.getCollection(name).insert(rows); if (verbose) { Log.d("Inserted " + rows.size() + " rows into metric \"" + name + "\"."); } } } private static final BasicDBObject INDEX_KEY = new BasicDBObject("_minute", Integer.valueOf(1)); private static ShutdownHook hook = new ShutdownHook(); private static boolean verbose; public static void main(String[] args) { if (hook.isShutdown(args)) { return; } Logger logger = Log.getAndSet(Conf.openLogger("Collector.", 16777216, 10)); ExecutorService executor = Executors.newCachedThreadPool(); ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1); Log.i("Metric Collector Started"); Properties p = Conf.load("Collector"); String host = p.getProperty("host"); host = host == null || host.isEmpty() ? "0.0.0.0" : host; int port = Numbers.parseInt(p.getProperty("port"), 5514); int serverId = Numbers.parseInt(p.getProperty("server_id"), 0); int expire = Numbers.parseInt(p.getProperty("expire"), 43200); boolean enableRemoteAddr = Conf.getBoolean(p.getProperty("remote_addr"), true); String allowedRemote = p.getProperty("allowed_remote"); HashSet<String> allowedRemotes = null; if (allowedRemote != null) { allowedRemotes = new HashSet<>(Arrays.asList(allowedRemote.split("[,;]"))); } verbose = Conf.getBoolean(p.getProperty("verbose"), false); long start = System.currentTimeMillis(); AtomicInteger now = new AtomicInteger((int) (start / Time.MINUTE)); p = Conf.load("Mongo"); MongoClient mongo = null; Runnable schedule = null; try (DatagramSocket socket = new DatagramSocket(new InetSocketAddress(host, port))) { mongo = new MongoClient(p.getProperty("host"), Numbers.parseInt(p.getProperty("port"), 27017)); DB db = mongo.getDB(p.getProperty("db")); // Schedule Statistics and Index schedule = () -> { int now_ = now.getAndIncrement(); // Insert aggregation-during-collection metrics HashMap<String, ArrayList<DBObject>> rowsMap = new HashMap<>(); for (MetricEntry entry : Metric.removeAll()) { BasicDBObject row = row(entry.getTagMap(), now_, entry.getCount(), entry.getSum(), entry.getMax(), entry.getMin(), entry.getSqr()); put(rowsMap, entry.getName(), row); } if (!rowsMap.isEmpty()) { insert(db, rowsMap); } // Ensure index and calculate metric size by master collector if (serverId == 0) { ArrayList<DBObject> rows = new ArrayList<>(); for (String name : db.getCollectionNames()) { if (name.startsWith("system.")) { continue; } DBCollection collection = db.getCollection(name); collection.createIndex(INDEX_KEY); int count = (int) collection.count(); rows.add(row(Collections.singletonMap("name", name), now_, 1, count, count, count, count * count)); } if (!rows.isEmpty()) { db.getCollection("metric.size").insert(rows); } } }; timer.scheduleAtFixedRate(Runnables.wrap(schedule), Time.MINUTE - start % Time.MINUTE, Time.MINUTE, TimeUnit.MILLISECONDS); // Schedule removal of stale metrics by master collector if (serverId == 0) { timer.scheduleAtFixedRate(Runnables.wrap(() -> { Integer notBefore = Integer.valueOf(now.get() - expire); Integer notAfter = Integer.valueOf(now.get() + expire); for (String name : db.getCollectionNames()) { if (name.startsWith("system.")) { continue; } DBCollection collection = db.getCollection(name); collection.remove(new BasicDBObject("_minute", new BasicDBObject("$lt", notBefore))); collection.remove(new BasicDBObject("_minute", new BasicDBObject("$gt", notAfter))); } }), Time.HOUR - start % Time.HOUR + Time.MINUTE / 2, Time.HOUR, TimeUnit.MILLISECONDS); } hook.register(socket); while (!Thread.interrupted()) { // Receive byte[] buf = new byte[65536]; DatagramPacket packet = new DatagramPacket(buf, buf.length); // Blocked, or closed by shutdown handler socket.receive(packet); int len = packet.getLength(); String remoteAddr = packet.getAddress().getHostAddress(); if (allowedRemotes != null && !allowedRemotes.contains(remoteAddr)) { Log.w(remoteAddr + " not allowed"); continue; } if (enableRemoteAddr) { Metric.put("metric.throughput", len, "remote_addr", remoteAddr, "server_id", "" + serverId); } else { Metric.put("metric.throughput", len, "server_id", "" + serverId); } // Inflate ByteArrayQueue baq = new ByteArrayQueue(); byte[] buf_ = new byte[2048]; try (InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(buf, 0, len))) { int bytesRead; while ((bytesRead = inflater.read(buf_)) > 0) { baq.add(buf_, 0, bytesRead); // Prevent attack if (baq.length() > MAX_BUFFER_SIZE) { break; } } } catch (IOException e) { Log.w("Unable to inflate packet from " + remoteAddr); // Continue to parse rows } HashMap<String, ArrayList<DBObject>> rowsMap = new HashMap<>(); for (String line : baq.toString().split("\n")) { // Truncate tailing '\r' int length = line.length(); if (length > 0 && line.charAt(length - 1) == '\r') { line = line.substring(0, length - 1); } // Parse name, aggregation, value and tags // <name>/<aggregation>/<value>[?<tag>=<value>[&...]] String[] paths; HashMap<String, String> tagMap = new HashMap<>(); int index = line.indexOf('?'); if (index < 0) { paths = line.split("/"); } else { paths = line.substring(0, index).split("/"); String tags = line.substring(index + 1); for (String tag : tags.split("&")) { index = tag.indexOf('='); if (index > 0) { tagMap.put(decode(tag.substring(0, index)), decode(tag.substring(index + 1))); } } } if (paths.length < 2) { Log.w("Incorrect format: [" + line + "]"); continue; } String name = decode(paths[0]); if (name.isEmpty()) { Log.w("Incorrect format: [" + line + "]"); continue; } if (enableRemoteAddr) { tagMap.put("remote_addr", remoteAddr); Metric.put("metric.rows", 1, "name", name, "remote_addr", remoteAddr, "server_id", "" + serverId); } else { Metric.put("metric.rows", 1, "name", name, "server_id", "" + serverId); } if (paths.length < 6) { // For aggregation-during-collection metric, aggregate first Metric.put(name, Numbers.parseDouble(paths[1]), tagMap); } else { // For aggregation-before-collection metric, insert immediately int count = Numbers.parseInt(paths[2]); double sum = Numbers.parseDouble(paths[3]); put(rowsMap, name, row(tagMap, Numbers.parseInt(paths[1], now.get()), count, sum, Numbers.parseDouble(paths[4]), Numbers.parseDouble(paths[5]), paths.length == 6 ? sum * sum / count : Numbers.parseDouble(paths[6]))); } } // Insert aggregation-before-collection metrics if (!rowsMap.isEmpty()) { executor.execute(Runnables.wrap(() -> insert(db, rowsMap))); } } } catch (IOException e) { Log.w(e.getMessage()); } catch (Error | RuntimeException e) { Log.e(e); } finally { // Do not do Mongo operations in main thread (may be interrupted) if (schedule != null) { executor.execute(Runnables.wrap(schedule)); } Runnables.shutdown(executor); Runnables.shutdown(timer); if (mongo != null) { mongo.close(); } } Log.i("Metric Collector Stopped"); Conf.closeLogger(Log.getAndSet(logger)); } }
package roart.common.webflux; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.codec.json.Jackson2JsonDecoder; import org.springframework.http.codec.json.Jackson2JsonEncoder; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ExchangeStrategies; import org.springframework.web.reactive.function.client.WebClient; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import roart.common.constants.EurekaConstants; import roart.common.util.MathUtil; public class WebFluxUtil { private static Logger log = LoggerFactory.getLogger(WebFluxUtil.class); public static <T> T sendMe(Class<T> myclass, Object param, String host, String port, String path) { ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String url = "http://" + host + ":" + port + "/" + path; return sendMeInner(myclass, param, url, objectMapper); } public static <T> T sendCMe(Class<T> myclass, Object param, String path) { ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String url = "http://" + getHostname() + ":" + getPort() + "/" + path; return sendMeInner(myclass, param, url, objectMapper); } public static <T> T sendIMe(Class<T> myclass, Object param, String path) { ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String url = "http://" + getIHostname() + ":" + getIPort() + "/" + path; return sendMeInner(myclass, param, url, objectMapper); } public static <T> T sendIMe(Class<T> myclass, Object param, String path, ObjectMapper objectMapper) { String url = "http://" + getIHostname() + ":" + getIPort() + "/" + path; return sendMeInner(myclass, param, url, objectMapper); } public static <T> T sendAMe(Class<T> myclass, Object param, String path) { ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String url = "http://" + getAHostname() + ":" + getAPort() + "/" + path; return sendMeInner(myclass, param, url, objectMapper); } public static <T> T sendAMe(Class<T> myclass, Object param, String path, ObjectMapper objectMapper) { String url = "http://" + getAHostname() + ":" + getAPort() + "/" + path; return sendMeInner(myclass, param, url, objectMapper); } public static <T> T sendMe(Class<T> myclass, Object param, String url) { return sendMeInner(myclass, param, url, null); } public static <T> T sendMeInner(Class<T> myclass, Object param, String url, ObjectMapper objectMapper) { long time = System.currentTimeMillis(); if (objectMapper != null) { ExchangeStrategies jacksonStrategy = ExchangeStrategies.builder() .codecs(config -> { config.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON)); config.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON)); }).build(); WebClient.builder().exchangeStrategies(jacksonStrategy); } WebClient webClient = WebClient.create(); T result = webClient .post() .uri(url) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .body(BodyInserters.fromObject(param)) .retrieve() .bodyToMono(myclass) .onErrorMap(Exception::new) .block(); //Mono.just //log.info("resultme " + regr.getHeaders().size() + " " + regr.getHeaders().getContentLength() + " " + regr.toString()); log.info("Rq time {}s for {} ", MathUtil.round((double) (System.currentTimeMillis() - time) / 1000, 1), url); return result; } public static String getAHostname() { String hostname = System.getenv(EurekaConstants.MYASERVER.toUpperCase()); if (hostname == null) { hostname = System.getProperty(EurekaConstants.MYASERVER); } if (hostname == null) { hostname = EurekaConstants.LOCALHOST; } return hostname; } public static String getAPort() { String port = System.getenv(EurekaConstants.MYAPORT.toUpperCase()); if (port == null) { port = System.getProperty(EurekaConstants.MYAPORT); } if (port == null) { port = EurekaConstants.HTTP; } return port; } public static String getIHostname() { String hostname = System.getenv(EurekaConstants.MYISERVER.toUpperCase()); if (hostname == null) { hostname = System.getProperty(EurekaConstants.MYISERVER); } if (hostname == null) { hostname = EurekaConstants.LOCALHOST; } return hostname; } public static String getIPort() { String port = System.getenv(EurekaConstants.MYIPORT.toUpperCase()); if (port == null) { port = System.getProperty(EurekaConstants.MYIPORT); } if (port == null) { port = EurekaConstants.HTTP; } return port; } public static String getHostname() { String hostname = System.getenv(EurekaConstants.MYSERVER.toUpperCase()); if (hostname == null) { hostname = System.getProperty(EurekaConstants.MYSERVER); } if (hostname == null) { hostname = EurekaConstants.LOCALHOST; } return hostname; } public static String getPort() { String port = System.getenv(EurekaConstants.MYPORT.toUpperCase()); if (port == null) { port = System.getProperty(EurekaConstants.MYPORT); } if (port == null) { port = EurekaConstants.HTTP; } return port; } }
package net.ripe.commons.ip; import static java.math.BigInteger.ZERO; import static net.ripe.commons.ip.RangeUtils.checkRange; import java.math.BigInteger; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.google.common.base.Optional; public final class PrefixUtils { private PrefixUtils() { } public static <C extends AbstractIp<C, R>, R extends AbstractIpRange<C, R>> boolean isLegalPrefix(AbstractIpRange<C, R> range) { int prefixLength = range.start().getCommonPrefixLength(range.end()); C lowerBoundForPrefix = range.start().lowerBoundForPrefix(prefixLength); C upperBoundForPrefix = range.end().upperBoundForPrefix(prefixLength); return range.start().equals(lowerBoundForPrefix) && range.end().equals(upperBoundForPrefix); } public static <C extends AbstractIp<C, R>, R extends AbstractIpRange<C, R>> int getPrefixLength(AbstractIpRange<C, R> range) { Validate.isTrue(isLegalPrefix(range), range.toStringInRangeNotation() + " is not a legal prefix, cannot get prefix length!"); return range.start().getCommonPrefixLength(range.end()); } public static <C extends AbstractIp<C, R>, R extends AbstractIpRange<C, R>> Optional<R> findMinimumPrefixForPrefixLength(R range, int prefixLength) { checkRange(prefixLength, 0, range.start().bitSize()); return findPrefixForPrefixLength(range, prefixLength, SizeComparator.<C, R>getInstance()); } public static <C extends AbstractIp<C, R>, R extends AbstractIpRange<C, R>> Optional<R> findMaximumPrefixForPrefixLength(R range, int prefixLength) { checkRange(prefixLength, 0, range.start().bitSize()); return findPrefixForPrefixLength(range, prefixLength, Collections.reverseOrder(SizeComparator.<C, R>getInstance())); } private static <C extends AbstractIp<C, R>, R extends AbstractIpRange<C, R>> Optional<R> findPrefixForPrefixLength(R range, int prefixLength, Comparator<? super R> comparator) { List<R> prefixes = range.splitToPrefixes(); Collections.sort(prefixes, comparator); for (R prefix : prefixes) { if (prefixLength >= PrefixUtils.getPrefixLength(prefix)) { return Optional.of(prefix); } } return Optional.absent(); } // TODO(yg): generify and move to AbstractIp public static int findMaxPrefixLengthForAddress(Ipv6 address) { return getMaxValidPrefix(address.value()); } private static int getMaxValidPrefix(BigInteger number) { int powerOfTwo = 0; int maxPowerOfTwo = powerOfTwo; while (powerOfTwo <= Ipv6.NUMBER_OF_BITS && number.divideAndRemainder(BigInteger.ONE.shiftLeft(powerOfTwo))[1].compareTo(ZERO) == 0) { maxPowerOfTwo = powerOfTwo; powerOfTwo++; } return Ipv6.NUMBER_OF_BITS - maxPowerOfTwo; } }
package com.intellij.util.io; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.Strings; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.util.EnumSet; import java.util.Enumeration; import java.util.List; import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static com.intellij.util.BitUtil.isSet; public abstract class Decompressor { /** * The Tar decompressor automatically detects the compression of an input file/stream. */ public static class Tar extends Decompressor { public Tar(@NotNull Path file) { mySource = file.toFile(); } public Tar(@NotNull File file) { mySource = file; } public Tar(@NotNull InputStream stream) { mySource = stream; } public @NotNull Tar withSymlinks() { symlinks = true; return this; } //<editor-fold desc="Implementation"> private final Object mySource; private TarArchiveInputStream myStream; private boolean symlinks; @Override protected void openStream() throws IOException { InputStream input = new BufferedInputStream(mySource instanceof File ? new FileInputStream(((File)mySource)) : (InputStream)mySource); try { input = new CompressorStreamFactory().createCompressorInputStream(input); } catch (CompressorException e) { Throwable cause = e.getCause(); if (cause instanceof IOException) throw (IOException)cause; } myStream = new TarArchiveInputStream(input); } @Override @SuppressWarnings("OctalInteger") protected Entry nextEntry() throws IOException { TarArchiveEntry te; while ((te = myStream.getNextTarEntry()) != null && !(te.isFile() || te.isDirectory() || te.isSymbolicLink() && symlinks)) /* skips unsupported */; return te == null ? null : new Entry(te.getName(), type(te), isSet(te.getMode(), 0200), isSet(te.getMode(), 0100), te.getLinkName()); } private static Type type(TarArchiveEntry te) { return te.isSymbolicLink() ? Type.SYMLINK : te.isDirectory() ? Type.DIR : Type.FILE; } @Override protected InputStream openEntryStream(Entry entry) { return myStream; } @Override protected void closeEntryStream(InputStream stream) { } @Override protected void closeStream() throws IOException { if (mySource instanceof File) { myStream.close(); myStream = null; } } //</editor-fold> } //NOTE. This class should work without CommonsCompress! public static class Zip extends Decompressor { public Zip(@NotNull Path file) { mySource = file.toFile(); } public Zip(@NotNull File file) { mySource = file; } //<editor-fold desc="Implementation"> private final File mySource; private ZipFile myZip; private Enumeration<? extends ZipEntry> myEntries; private ZipEntry myEntry; @NotNull public Decompressor withUnixPermissionsAndSymlinks() { return new CommonsZip(mySource); } @Override protected void openStream() throws IOException { myZip = new ZipFile(mySource); myEntries = myZip.entries(); } @Override protected Entry nextEntry() { myEntry = myEntries.hasMoreElements() ? myEntries.nextElement() : null; return myEntry == null ? null : new Entry(myEntry.getName(), myEntry.isDirectory()); } @Override protected InputStream openEntryStream(Entry entry) throws IOException { return myZip.getInputStream(myEntry); } @Override protected void closeEntryStream(InputStream stream) throws IOException { stream.close(); } @Override protected void closeStream() throws IOException { if (myZip != null) { myZip.close(); myZip = null; } } //</editor-fold> } private static class CommonsZip extends Decompressor { CommonsZip(@NotNull File file) { mySource = file; } //<editor-fold desc="Implementation"> private final File mySource; private org.apache.commons.compress.archivers.zip.ZipFile myZip; private Enumeration<? extends ZipArchiveEntry> myEntries; private ZipArchiveEntry myEntry; @Override protected void openStream() throws IOException { myZip = new org.apache.commons.compress.archivers.zip.ZipFile(mySource); myEntries = myZip.getEntries(); } @Override protected Entry nextEntry() throws IOException { if (!myEntries.hasMoreElements()) { myEntry = null; return null; } myEntry = myEntries.nextElement(); if (myEntry == null) { return null; } String linkTarget = myEntry.isUnixSymlink() ? myZip.getUnixSymlink(myEntry) : null; //noinspection OctalInteger return new Entry(myEntry.getName(), type(myEntry), isSet(myEntry.getUnixMode(), 0200), isSet(myEntry.getUnixMode(), 0100), linkTarget); } private static Type type(ZipArchiveEntry te) { return te.isUnixSymlink() ? Type.SYMLINK : te.isDirectory() ? Type.DIR : Type.FILE; } @Override protected InputStream openEntryStream(Entry entry) throws IOException { return myZip.getInputStream(myEntry); } @Override protected void closeEntryStream(InputStream stream) throws IOException { stream.close(); } @Override protected void closeStream() throws IOException { myZip.close(); myZip = null; } //</editor-fold> } @Nullable private Predicate<? super String> myFilter = null; @Nullable private Condition<? super Entry> myEntryFilter = null; @Nullable private List<String> myPathsPrefix = null; private boolean myOverwrite = true; @Nullable private java.util.function.Consumer<? super Path> myConsumer; public Decompressor filter(@Nullable Predicate<? super String> filter) { myFilter = filter; return this; } /** * @deprecated Use {@link #filter(Predicate)} */ @Deprecated public Decompressor filter(@Nullable Condition<? super String> filter) { myFilter = filter == null ? null : it -> filter.value(it); return this; } public Decompressor filterEntries(@Nullable Condition<? super Entry> filter) { myEntryFilter = filter; return this; } public Decompressor overwrite(boolean overwrite) { myOverwrite = overwrite; return this; } /** * @deprecated Use {@link #postProcessor} */ @Deprecated public Decompressor postprocessor(@Nullable Consumer<? super File> consumer) { myConsumer = consumer == null ? null : path -> consumer.consume(path.toFile()); return this; } public Decompressor postProcessor(@Nullable java.util.function.Consumer<? super Path> consumer) { myConsumer = consumer; return this; } /** * Extracts only items whose paths starts with the normalized prefix of {@code prefix + '/'} <br/> * Paths are normalized before comparison. <br/> * The prefix test is applied after {@link #filter(Condition)} predicate is tested. <br/> * Some entries may clash, so use {@link #overwrite(boolean)} to control it. <br/> * Some items with path that does not start from the prefix could be ignored * * @param prefix prefix to remove from every archive entry paths * @return self */ @NotNull public Decompressor removePrefixPath(@Nullable final String prefix) throws IOException { myPathsPrefix = prefix != null ? normalizePathAndSplit(prefix) : null; return this; } /** * @deprecated Use {@link #extract(Path)} */ @Deprecated public final void extract(@NotNull File outputDir) throws IOException { extract(outputDir.toPath()); } public final void extract(@NotNull Path outputDir) throws IOException { openStream(); try { Entry entry; while ((entry = nextEntry()) != null) { if (myFilter != null) { String entryName = entry.type == Type.DIR && !Strings.endsWithChar(entry.name, '/') ? entry.name + '/' : entry.name; if (!myFilter.test(entryName)) { continue; } } if (myEntryFilter != null && !myEntryFilter.value(entry)) { continue; } if (myPathsPrefix != null) { entry = entry.mapPathPrefix(myPathsPrefix); if (entry == null) continue; } Path outputFile = entryFile(outputDir, entry.name); switch (entry.type) { case DIR: Files.createDirectories(outputFile); break; case FILE: if (!Files.exists(outputFile) || myOverwrite) { InputStream inputStream = openEntryStream(entry); try { Files.createDirectories(outputFile.getParent()); try (OutputStream outputStream = Files.newOutputStream(outputFile)) { StreamUtil.copy(inputStream, outputStream); } if (!entry.isWritable || entry.isExecutable) { if (SystemInfoRt.isWindows) { if (!entry.isWritable) { DosFileAttributeView attrs = Files.getFileAttributeView(outputFile, DosFileAttributeView.class); if (attrs != null) { attrs.setReadOnly(true); } } } else { PosixFileAttributeView attrs = Files.getFileAttributeView(outputFile, PosixFileAttributeView.class); if (attrs != null) { EnumSet<PosixFilePermission> permissions = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ); if (entry.isWritable) { permissions.add(PosixFilePermission.OWNER_WRITE); permissions.add(PosixFilePermission.GROUP_WRITE); } if (entry.isExecutable) { permissions.add(PosixFilePermission.OWNER_EXECUTE); } attrs.setPermissions(permissions); } } } } finally { closeEntryStream(inputStream); } } break; case SYMLINK: if (Strings.isEmpty(entry.linkTarget)) { throw new IOException("Invalid symlink entry: " + entry.name + " (empty target)"); } try { Path outputTarget = Paths.get(entry.linkTarget); Files.createDirectories(outputFile.getParent()); Files.createSymbolicLink(outputFile, outputTarget); } catch (InvalidPathException e) { throw new IOException("Invalid symlink entry: " + entry.name + " -> " + entry.linkTarget, e); } break; } if (myConsumer != null) { myConsumer.accept(outputFile); } } } finally { closeStream(); } } //<editor-fold desc="Internal interface"> protected Decompressor() { } public enum Type {FILE, DIR, SYMLINK} public static class Entry { public final String name; public final Type type; public final boolean isWritable; public final boolean isExecutable; public final String linkTarget; protected Entry(String name, boolean isDirectory) { this(name, isDirectory ? Type.DIR : Type.FILE, true, false, null); } protected Entry(String name, Type type, boolean isWritable, boolean isExecutable, String linkTarget) { this.name = name; this.type = type; this.isWritable = isWritable; this.isExecutable = isExecutable; this.linkTarget = linkTarget; } @Nullable protected Entry mapPathPrefix(@NotNull List<String> prefix) throws IOException { List<String> ourPathSplit = normalizePathAndSplit(name); if (prefix.size() >= ourPathSplit.size() || !ourPathSplit.subList(0, prefix.size()).equals(prefix)) { return null; } String newName = String.join("/", ourPathSplit.subList(prefix.size(), ourPathSplit.size())); return new Entry(newName, this.type, this.isWritable, isExecutable, linkTarget); } } protected abstract void openStream() throws IOException; protected abstract Entry nextEntry() throws IOException; protected abstract InputStream openEntryStream(Entry entry) throws IOException; protected abstract void closeEntryStream(InputStream stream) throws IOException; protected abstract void closeStream() throws IOException; //</editor-fold> private static @NotNull List<String> normalizePathAndSplit(@NotNull String path) throws IOException { ensureValidPath(path); String canonicalPath = FileUtilRt.toCanonicalPath(path, '/', true); return FileUtilRt.splitPath(StringUtil.trimLeading(canonicalPath, '/'), '/'); } private static void ensureValidPath(@NotNull String entryName) throws IOException { if (entryName.contains("..") && ArrayUtil.contains("..", entryName.split("[/\\\\]"))) { throw new IOException("Invalid entry name: " + entryName); } } public static @NotNull Path entryFile(@NotNull Path outputDir, @NotNull String entryName) throws IOException { ensureValidPath(entryName); return outputDir.resolve(StringUtil.trimLeading(entryName, '/')); } }
package com.sun.jna.platform.win32; import static com.sun.jna.platform.win32.WinioctlUtil.FSCTL_GET_COMPRESSION; import static com.sun.jna.platform.win32.WinioctlUtil.FSCTL_GET_REPARSE_POINT; import static com.sun.jna.platform.win32.WinioctlUtil.FSCTL_SET_COMPRESSION; import static com.sun.jna.platform.win32.WinioctlUtil.FSCTL_SET_REPARSE_POINT; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.TimeZone; import com.sun.jna.Function; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.NativeLibrary; import com.sun.jna.NativeMappedConverter; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.platform.win32.BaseTSD.SIZE_T; import com.sun.jna.platform.win32.Ntifs.REPARSE_DATA_BUFFER; import com.sun.jna.platform.win32.Ntifs.SymbolicLinkReparseBuffer; import com.sun.jna.platform.win32.WinBase.FILETIME; import com.sun.jna.platform.win32.WinBase.FILE_ATTRIBUTE_TAG_INFO; import com.sun.jna.platform.win32.WinBase.FILE_BASIC_INFO; import com.sun.jna.platform.win32.WinBase.FILE_COMPRESSION_INFO; import com.sun.jna.platform.win32.WinBase.FILE_DISPOSITION_INFO; import com.sun.jna.platform.win32.WinBase.FILE_ID_INFO; import com.sun.jna.platform.win32.WinBase.FILE_STANDARD_INFO; import com.sun.jna.platform.win32.WinBase.MEMORYSTATUSEX; import com.sun.jna.platform.win32.WinBase.SYSTEMTIME; import com.sun.jna.platform.win32.WinBase.SYSTEM_INFO; import com.sun.jna.platform.win32.WinBase.WIN32_FIND_DATA; import com.sun.jna.platform.win32.WinDef.DWORD; import com.sun.jna.platform.win32.WinDef.HMODULE; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinDef.USHORT; import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.platform.win32.WinNT.HANDLEByReference; import com.sun.jna.platform.win32.WinNT.MEMORY_BASIC_INFORMATION; import com.sun.jna.platform.win32.WinNT.OSVERSIONINFO; import com.sun.jna.platform.win32.WinNT.OSVERSIONINFOEX; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.ShortByReference; import junit.framework.TestCase; public class Kernel32Test extends TestCase { public static void main(String[] args) { OSVERSIONINFO lpVersionInfo = new OSVERSIONINFO(); assertTrue(Kernel32.INSTANCE.GetVersionEx(lpVersionInfo)); System.out.println("Operating system: " + lpVersionInfo.dwMajorVersion.longValue() + "." + lpVersionInfo.dwMinorVersion.longValue() + " (" + lpVersionInfo.dwBuildNumber + ")" + " [" + Native.toString(lpVersionInfo.szCSDVersion) + "]"); junit.textui.TestRunner.run(Kernel32Test.class); } public void testGetLastErrorNativeLibraryOverride() { assertFalse("Unexpected success", Kernel32.INSTANCE.CloseHandle(null)); assertEquals("Mismatched error code", WinError.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); } public void testNoDuplicateMethodsNames() { Collection<String> dupSet = AbstractWin32TestSupport.detectDuplicateMethods(Kernel32.class); if (dupSet.size() > 0) { for (String name : new String[] { // has 2 overloads by design since the API accepts both OSVERSIONINFO and OSVERSIONINFOEX "GetVersionEx" }) { dupSet.remove(name); } } assertTrue("Duplicate methods found: " + dupSet, dupSet.isEmpty()); } public void testGetDriveType() { if (!Platform.isWindows()) return; Kernel32 kernel = Kernel32.INSTANCE; assertEquals("Wrong drive type.", WinBase.DRIVE_FIXED, kernel.GetDriveType("c:")); } public void testStructureOutArgument() { Kernel32 kernel = Kernel32.INSTANCE; WinBase.SYSTEMTIME time = new WinBase.SYSTEMTIME(); kernel.GetSystemTime(time); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); assertEquals("Hour not properly set", cal.get(Calendar.HOUR_OF_DAY), time.wHour); assertEquals("Day not properly set", cal.get(Calendar.DAY_OF_WEEK)-1, time.wDayOfWeek); assertEquals("Year not properly set", cal.get(Calendar.YEAR), time.wYear); } public void testSetSystemTime() { Kernel32 kernel = Kernel32.INSTANCE; WinBase.SYSTEMTIME time = new WinBase.SYSTEMTIME(); kernel.GetSystemTime(time); try { WinBase.SYSTEMTIME expected = new WinBase.SYSTEMTIME(); expected.wYear = time.wYear; expected.wMonth = time.wMonth; expected.wDay = time.wDay; expected.wHour = time.wHour; expected.wMinute = time.wMinute; expected.wSecond = time.wSecond; expected.wMilliseconds = time.wMilliseconds; if (expected.wHour > 0) { expected.wHour } else { expected.wHour++; } if (assertTimeSettingOperationSucceeded("SetSystemTime", kernel.SetSystemTime(expected))) { WinBase.SYSTEMTIME actual = new WinBase.SYSTEMTIME(); kernel.GetSystemTime(actual); assertEquals("Mismatched hour value", expected.wHour, actual.wHour); } } finally { assertTimeSettingOperationSucceeded("Restore original system time", kernel.SetSystemTime(time)); } } public void testSetLocaltime() { Kernel32 kernel = Kernel32.INSTANCE; WinBase.SYSTEMTIME time = new WinBase.SYSTEMTIME(); kernel.GetLocalTime(time); try { WinBase.SYSTEMTIME expected = new WinBase.SYSTEMTIME(); expected.wYear = time.wYear; expected.wMonth = time.wMonth; expected.wDay = time.wDay; expected.wHour = time.wHour; expected.wMinute = time.wMinute; expected.wSecond = time.wSecond; expected.wMilliseconds = time.wMilliseconds; if (expected.wHour > 0) { expected.wHour } else { expected.wHour++; } if (assertTimeSettingOperationSucceeded("SetLocalTime", kernel.SetLocalTime(expected))) { WinBase.SYSTEMTIME actual = new WinBase.SYSTEMTIME(); kernel.GetLocalTime(actual); assertEquals("Mismatched hour value", expected.wHour, actual.wHour); } } finally { assertTimeSettingOperationSucceeded("Restore local time", kernel.SetLocalTime(time)); } } private static boolean assertTimeSettingOperationSucceeded(String message, boolean result) { if (result) { return result; } int hr=Kernel32.INSTANCE.GetLastError(); /* * Check special error in case the user running the test isn't allowed * to change the time. This can happen for hosts that are managed * by some central administrator using an automated time setting mechanism. * In such cases, the user running the tests might not have admin * privileges and it may be too much to ask to have them just for running * this JNA API test... */ if (hr == WinError.ERROR_PRIVILEGE_NOT_HELD) { return false; // don't fail the test, but signal the failure } if (hr != WinError.ERROR_SUCCESS) { fail(message + " failed: hr=" + hr); } else { fail(message + " unknown failure reason code"); } return false; } public void testGetLastError() { Kernel32 kernel = Kernel32.INSTANCE; int ERRCODE = 8; kernel.SetLastError(ERRCODE); int code = kernel.GetLastError(); assertEquals("Wrong error value after SetLastError", ERRCODE, code); if (kernel.GetProcessVersion(-1) == 0) { final int INVALID_PARAMETER = 87; code = kernel.GetLastError(); assertEquals("Wrong error value after failed syscall", INVALID_PARAMETER, code); } else { fail("GetProcessId(NULL) should fail"); } } public void testConvertHWND_BROADCAST() { HWND hwnd = WinUser.HWND_BROADCAST; NativeMappedConverter.getInstance(hwnd.getClass()).toNative(hwnd, null); } public void testGetComputerName() { IntByReference lpnSize = new IntByReference(0); assertFalse(Kernel32.INSTANCE.GetComputerName(null, lpnSize)); assertEquals(WinError.ERROR_BUFFER_OVERFLOW, Kernel32.INSTANCE.GetLastError()); char buffer[] = new char[WinBase.MAX_COMPUTERNAME_LENGTH + 1]; lpnSize.setValue(buffer.length); assertTrue(Kernel32.INSTANCE.GetComputerName(buffer, lpnSize)); } public void testGetComputerNameExSameAsGetComputerName() { IntByReference lpnSize = new IntByReference(0); char buffer[] = new char[WinBase.MAX_COMPUTERNAME_LENGTH + 1]; lpnSize.setValue(buffer.length); assertTrue("Failed to retrieve expected computer name", Kernel32.INSTANCE.GetComputerName(buffer, lpnSize)); String expected = Native.toString(buffer); // reset lpnSize.setValue(buffer.length); Arrays.fill(buffer, '\0'); assertTrue("Failed to retrieve extended computer name", Kernel32.INSTANCE.GetComputerNameEx(WinBase.COMPUTER_NAME_FORMAT.ComputerNameNetBIOS, buffer, lpnSize)); String actual = Native.toString(buffer); assertEquals("Mismatched names", expected, actual); } public void testWaitForSingleObject() { HANDLE handle = Kernel32.INSTANCE.CreateEvent(null, false, false, null); assertNotNull("Failed to create event: " + Kernel32.INSTANCE.GetLastError(), handle); try { // handle runs into timeout since it is not triggered // WAIT_TIMEOUT = 0x00000102 assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject(handle, 1000)); } finally { Kernel32Util.closeHandle(handle); } } public void testResetEvent() { HANDLE handle = Kernel32.INSTANCE.CreateEvent(null, true, false, null); assertNotNull("Failed to create event: " + Kernel32.INSTANCE.GetLastError(), handle); try { // set the event to the signaled state Kernel32.INSTANCE.SetEvent(handle); // This should return successfully assertEquals(WinBase.WAIT_OBJECT_0, Kernel32.INSTANCE.WaitForSingleObject( handle, 1000)); // now reset it to not signaled Kernel32.INSTANCE.ResetEvent(handle); // handle runs into timeout since it is not triggered // WAIT_TIMEOUT = 0x00000102 assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForSingleObject(handle, 1000)); } finally { Kernel32Util.closeHandle(handle); } } public void testWaitForMultipleObjects(){ HANDLE[] handles = new HANDLE[2]; try { for (int index = 0; index < handles.length; index++) { HANDLE h = Kernel32.INSTANCE.CreateEvent(null, false, false, null); assertNotNull("Failed to create event #" + index + ": " + Kernel32.INSTANCE.GetLastError(), h); handles[index] = h; } // handle runs into timeout since it is not triggered // WAIT_TIMEOUT = 0x00000102 assertEquals(WinError.WAIT_TIMEOUT, Kernel32.INSTANCE.WaitForMultipleObjects( handles.length, handles, false, 1000)); } finally { Kernel32Util.closeHandles(handles); } // invalid Handle handles[0] = WinBase.INVALID_HANDLE_VALUE; handles[1] = Kernel32.INSTANCE.CreateEvent(null, false, false, null); assertNotNull("Failed to create valid event: " + Kernel32.INSTANCE.GetLastError(), handles[1]); try { // returns WAIT_FAILED since handle is invalid assertEquals(WinBase.WAIT_FAILED, Kernel32.INSTANCE.WaitForMultipleObjects( handles.length, handles, false, 5000)); } finally { Kernel32Util.closeHandle(handles[1]); } } public void testGetCurrentThreadId() { assertTrue(Kernel32.INSTANCE.GetCurrentThreadId() > 0); } public void testGetCurrentThread() { HANDLE h = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull("No current thread handle", h); assertFalse("Null current thread handle", h.equals(0)); // Calling the CloseHandle function with this handle has no effect Kernel32Util.closeHandle(h); } public void testOpenThread() { HANDLE h = Kernel32.INSTANCE.OpenThread(WinNT.THREAD_ALL_ACCESS, false, Kernel32.INSTANCE.GetCurrentThreadId()); assertNotNull(h); assertFalse(h.equals(0)); Kernel32Util.closeHandle(h); } public void testGetCurrentProcessId() { assertTrue(Kernel32.INSTANCE.GetCurrentProcessId() > 0); } public void testGetCurrentProcess() { HANDLE h = Kernel32.INSTANCE.GetCurrentProcess(); assertNotNull("No current process handle", h); assertFalse("Null current process handle", h.equals(0)); // Calling the CloseHandle function with a pseudo handle has no effect Kernel32Util.closeHandle(h); } public void testOpenProcess() { HANDLE h = Kernel32.INSTANCE.OpenProcess(0, false, Kernel32.INSTANCE.GetCurrentProcessId()); assertNull(h); // opening your own process fails with access denied assertEquals(WinError.ERROR_ACCESS_DENIED, Kernel32.INSTANCE.GetLastError()); } public void testQueryFullProcessImageName() { int pid = Kernel32.INSTANCE.GetCurrentProcessId(); HANDLE h = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, pid); assertNotNull("Failed (" + Kernel32.INSTANCE.GetLastError() + ") to get process ID=" + pid + " handle", h); try { char[] path = new char[WinDef.MAX_PATH]; IntByReference lpdwSize = new IntByReference(path.length); boolean b = Kernel32.INSTANCE.QueryFullProcessImageName(h, 0, path, lpdwSize); assertTrue("Failed (" + Kernel32.INSTANCE.GetLastError() + ") to query process image name", b); assertTrue("Failed to query process image name, empty path returned", lpdwSize.getValue() > 0); } finally { Kernel32Util.closeHandle(h); } } public void testGetTempPath() { char[] buffer = new char[WinDef.MAX_PATH]; assertTrue(Kernel32.INSTANCE.GetTempPath(new DWORD(WinDef.MAX_PATH), buffer).intValue() > 0); } public void testGetTickCount() throws InterruptedException { // Tick count rolls over every 49.7 days, so to safeguard from // roll-over, we will get two time spans. At least one should // yield a positive. int tick1 = Kernel32.INSTANCE.GetTickCount(); Thread.sleep(10); int tick2 = Kernel32.INSTANCE.GetTickCount(); Thread.sleep(10); int tick3 = Kernel32.INSTANCE.GetTickCount(); assertTrue(tick2 > tick1 || tick3 > tick2); } public void testGetTickCount64() throws InterruptedException { long tick1 = Kernel32.INSTANCE.GetTickCount64(); Thread.sleep(100); long tick2 = Kernel32.INSTANCE.GetTickCount64(); assertTrue(tick2 > tick1); } public void testGetVersion() { DWORD version = Kernel32.INSTANCE.GetVersion(); assertTrue("Version high should be non-zero: 0x" + Integer.toHexString(version.getHigh().intValue()), version.getHigh().intValue() != 0); assertTrue("Version low should be >= 0: 0x" + Integer.toHexString(version.getLow().intValue()), version.getLow().intValue() >= 0); } public void testGetVersionEx_OSVERSIONINFO() { OSVERSIONINFO lpVersionInfo = new OSVERSIONINFO(); assertEquals(lpVersionInfo.size(), lpVersionInfo.dwOSVersionInfoSize.longValue()); assertTrue(Kernel32.INSTANCE.GetVersionEx(lpVersionInfo)); assertTrue(lpVersionInfo.dwMajorVersion.longValue() > 0); assertTrue(lpVersionInfo.dwMinorVersion.longValue() >= 0); assertEquals(lpVersionInfo.size(), lpVersionInfo.dwOSVersionInfoSize.longValue()); assertTrue(lpVersionInfo.dwPlatformId.longValue() > 0); assertTrue(lpVersionInfo.dwBuildNumber.longValue() > 0); assertTrue(Native.toString(lpVersionInfo.szCSDVersion).length() >= 0); } public void testGetVersionEx_OSVERSIONINFOEX() { OSVERSIONINFOEX lpVersionInfo = new OSVERSIONINFOEX(); assertEquals(lpVersionInfo.size(), lpVersionInfo.dwOSVersionInfoSize.longValue()); assertTrue(Kernel32.INSTANCE.GetVersionEx(lpVersionInfo)); assertTrue(lpVersionInfo.getMajor() > 0); assertTrue(lpVersionInfo.getMinor() >= 0); assertEquals(lpVersionInfo.size(), lpVersionInfo.dwOSVersionInfoSize.longValue()); assertTrue(lpVersionInfo.getPlatformId() > 0); assertTrue(lpVersionInfo.getBuildNumber() > 0); assertTrue(lpVersionInfo.getServicePack().length() >= 0); assertTrue(lpVersionInfo.getProductType() >= 0); } public void testGetSystemInfo() { SYSTEM_INFO lpSystemInfo = new SYSTEM_INFO(); Kernel32.INSTANCE.GetSystemInfo(lpSystemInfo); assertTrue(lpSystemInfo.dwNumberOfProcessors.intValue() > 0); } public void testGetSystemTimes() { Kernel32 kernel = Kernel32.INSTANCE; FILETIME lpIdleTime = new FILETIME(); FILETIME lpKernelTime = new FILETIME(); FILETIME lpUserTime = new FILETIME(); boolean succ = kernel.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime); assertTrue(succ); long idleTime = lpIdleTime.toDWordLong().longValue(); long kernelTime = lpKernelTime.toDWordLong().longValue(); long userTime = lpUserTime.toDWordLong().longValue(); // All should be >= 0. kernel includes idle. assertTrue(idleTime >= 0); assertTrue(kernelTime >= idleTime); assertTrue(userTime >= 0); } public void testIsWow64Process() { try { IntByReference isWow64 = new IntByReference(42); HANDLE hProcess = Kernel32.INSTANCE.GetCurrentProcess(); assertTrue(Kernel32.INSTANCE.IsWow64Process(hProcess, isWow64)); assertTrue(0 == isWow64.getValue() || 1 == isWow64.getValue()); } catch (UnsatisfiedLinkError e) { // IsWow64Process is not available on this OS } } public void testGetNativeSystemInfo() { try { SYSTEM_INFO lpSystemInfo = new SYSTEM_INFO(); Kernel32.INSTANCE.GetNativeSystemInfo(lpSystemInfo); assertTrue(lpSystemInfo.dwNumberOfProcessors.intValue() > 0); } catch (UnsatisfiedLinkError e) { // only available under WOW64 } } public void testGlobalMemoryStatusEx() { MEMORYSTATUSEX lpBuffer = new MEMORYSTATUSEX(); assertTrue(Kernel32.INSTANCE.GlobalMemoryStatusEx(lpBuffer)); assertTrue(lpBuffer.ullTotalPhys.longValue() > 0); assertTrue(lpBuffer.dwMemoryLoad.intValue() >= 0 && lpBuffer.dwMemoryLoad.intValue() <= 100); assertEquals(0, lpBuffer.ullAvailExtendedVirtual.intValue()); } public void testDeleteFile() { String filename = Kernel32Util.getTempPath() + "\\FileDoesNotExist.jna"; assertFalse(Kernel32.INSTANCE.DeleteFile(filename)); assertEquals(WinError.ERROR_FILE_NOT_FOUND, Kernel32.INSTANCE.GetLastError()); } public void testReadFile() throws IOException { String expected = "jna - testReadFile"; File tmp = File.createTempFile("testReadFile", "jna"); tmp.deleteOnExit(); FileWriter fw = new FileWriter(tmp); try { fw.append(expected); } finally { fw.close(); } HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse("Failed to create file handle: " + tmp, WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { byte[] readBuffer=new byte[expected.length() + Byte.MAX_VALUE]; IntByReference lpNumberOfBytesRead = new IntByReference(0); assertTrue("Failed to read from file", Kernel32.INSTANCE.ReadFile(hFile, readBuffer, readBuffer.length, lpNumberOfBytesRead, null)); int read = lpNumberOfBytesRead.getValue(); assertEquals("Mismatched read size", expected.length(), read); assertEquals("Mismatched read content", expected, new String(readBuffer, 0, read)); } finally { Kernel32Util.closeHandle(hFile); } } public void testSetHandleInformation() throws IOException { File tmp = File.createTempFile("testSetHandleInformation", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { assertTrue(Kernel32.INSTANCE.SetHandleInformation(hFile, WinBase.HANDLE_FLAG_PROTECT_FROM_CLOSE, 0)); } finally { Kernel32Util.closeHandle(hFile); } } public void testCreatePipe() { HANDLEByReference hReadPipe = new HANDLEByReference(); HANDLEByReference hWritePipe = new HANDLEByReference(); try { assertTrue(Kernel32.INSTANCE.CreatePipe(hReadPipe, hWritePipe, null, 0)); } finally { Kernel32Util.closeHandleRefs(hReadPipe, hWritePipe); } } public void testGetExitCodeProcess() { IntByReference lpExitCode = new IntByReference(0); assertTrue(Kernel32.INSTANCE.GetExitCodeProcess(Kernel32.INSTANCE.GetCurrentProcess(), lpExitCode)); assertEquals(WinBase.STILL_ACTIVE, lpExitCode.getValue()); } public void testTerminateProcess() throws IOException { File tmp = File.createTempFile("testTerminateProcess", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { assertFalse(Kernel32.INSTANCE.TerminateProcess(hFile, 1)); assertEquals(WinError.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); } finally { Kernel32Util.closeHandle(hFile); } } public void testGetFileAttributes() { assertTrue(WinBase.INVALID_FILE_ATTRIBUTES != Kernel32.INSTANCE.GetFileAttributes(".")); } public void testDeviceIoControlFsctlCompression() throws IOException { File tmp = File.createTempFile("testDeviceIoControlFsctlCompression", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_ALL, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { ShortByReference lpBuffer = new ShortByReference(); IntByReference lpBytes = new IntByReference(); if (false == Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_GET_COMPRESSION, null, 0, lpBuffer.getPointer(), USHORT.SIZE, lpBytes, null)) { fail("DeviceIoControl failed with " + Kernel32.INSTANCE.GetLastError()); } assertEquals(WinNT.COMPRESSION_FORMAT_NONE, lpBuffer.getValue()); assertEquals(USHORT.SIZE, lpBytes.getValue()); lpBuffer = new ShortByReference((short)WinNT.COMPRESSION_FORMAT_LZNT1); if (false == Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_SET_COMPRESSION, lpBuffer.getPointer(), USHORT.SIZE, null, 0, lpBytes, null)) { fail("DeviceIoControl failed with " + Kernel32.INSTANCE.GetLastError()); } if (false == Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_GET_COMPRESSION, null, 0, lpBuffer.getPointer(), USHORT.SIZE, lpBytes, null)) { fail("DeviceIoControl failed with " + Kernel32.INSTANCE.GetLastError()); } assertEquals(WinNT.COMPRESSION_FORMAT_LZNT1, lpBuffer.getValue()); assertEquals(USHORT.SIZE, lpBytes.getValue()); } finally { Kernel32Util.closeHandle(hFile); } } /** * NOTE: Due to process elevation, this test must be run as administrator * @throws IOException */ public void testDeviceIoControlFsctlReparse() throws IOException { Path folder = Files.createTempDirectory("testDeviceIoControlFsctlReparse_FOLDER"); Path link = Files.createTempDirectory("testDeviceIoControlFsctlReparse_LINK"); File delFolder = folder.toFile(); delFolder.deleteOnExit(); File delLink = link.toFile(); delLink.deleteOnExit(); // Required for FSCTL_SET_REPARSE_POINT Advapi32Util.Privilege restore = new Advapi32Util.Privilege(WinNT.SE_RESTORE_NAME); try { restore.enable(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(link.toAbsolutePath().toString(), WinNT.GENERIC_READ | WinNT.FILE_WRITE_ATTRIBUTES | WinNT.FILE_WRITE_EA, WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE | WinNT.FILE_SHARE_DELETE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_DIRECTORY | WinNT.FILE_FLAG_BACKUP_SEMANTICS | WinNT.FILE_FLAG_OPEN_REPARSE_POINT, null); if (WinBase.INVALID_HANDLE_VALUE.equals(hFile)) { fail("CreateFile failed with " + Kernel32.INSTANCE.GetLastError()); } try { SymbolicLinkReparseBuffer symLinkReparseBuffer = new SymbolicLinkReparseBuffer(folder.getFileName().toString(), folder.getFileName().toString(), Ntifs.SYMLINK_FLAG_RELATIVE); REPARSE_DATA_BUFFER lpBuffer = new REPARSE_DATA_BUFFER(WinNT.IO_REPARSE_TAG_SYMLINK, (short) 0, symLinkReparseBuffer); assertTrue(Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_SET_REPARSE_POINT, lpBuffer.getPointer(), lpBuffer.getSize(), null, 0, null, null)); Memory p = new Memory(REPARSE_DATA_BUFFER.sizeOf()); IntByReference lpBytes = new IntByReference(); assertTrue(Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, null, 0, p, (int) p.size(), lpBytes, null)); // Is a reparse point lpBuffer = new REPARSE_DATA_BUFFER(p); assertTrue(lpBytes.getValue() > 0); assertTrue(lpBuffer.ReparseTag == WinNT.IO_REPARSE_TAG_SYMLINK); assertEquals(folder.getFileName().toString(), lpBuffer.u.symLinkReparseBuffer.getPrintName()); assertEquals(folder.getFileName().toString(), lpBuffer.u.symLinkReparseBuffer.getSubstituteName()); } finally { Kernel32Util.closeHandle(hFile); } } finally { restore.close(); } } public void testCopyFile() throws IOException { File source = File.createTempFile("testCopyFile", "jna"); source.deleteOnExit(); File destination = new File(source.getParent(), source.getName() + "-destination"); destination.deleteOnExit(); Kernel32.INSTANCE.CopyFile(source.getCanonicalPath(), destination.getCanonicalPath(), true); assertTrue(destination.exists()); } public void testMoveFile() throws IOException { File source = File.createTempFile("testMoveFile", "jna"); source.deleteOnExit(); File destination = new File(source.getParent(), source.getName() + "-destination"); destination.deleteOnExit(); Kernel32.INSTANCE.MoveFile(source.getCanonicalPath(), destination.getCanonicalPath()); assertTrue(destination.exists()); assertFalse(source.exists()); } public void testMoveFileEx() throws IOException { File source = File.createTempFile("testMoveFileEx", "jna"); source.deleteOnExit(); File destination = File.createTempFile("testCopyFile", "jna"); destination.deleteOnExit(); Kernel32.INSTANCE.MoveFileEx(source.getCanonicalPath(), destination.getCanonicalPath(), new DWORD(WinBase.MOVEFILE_REPLACE_EXISTING)); assertTrue(destination.exists()); assertFalse(source.exists()); } public void testCreateProcess() { WinBase.STARTUPINFO startupInfo = new WinBase.STARTUPINFO(); WinBase.PROCESS_INFORMATION.ByReference processInformation = new WinBase.PROCESS_INFORMATION.ByReference(); boolean status = Kernel32.INSTANCE.CreateProcess( null, "cmd.exe /c echo hi", null, null, true, new WinDef.DWORD(0), Pointer.NULL, System.getProperty("java.io.tmpdir"), startupInfo, processInformation); assertTrue(status); assertTrue(processInformation.dwProcessId.longValue() > 0); } public void testFindFirstFile() throws IOException { Path tmpDir = Files.createTempDirectory("testFindFirstFile"); File tmpFile = new File(Files.createTempFile(tmpDir, "testFindFirstFile", ".jna").toString()); Memory p = new Memory(WIN32_FIND_DATA.sizeOf()); HANDLE hFile = Kernel32.INSTANCE.FindFirstFile(tmpDir.toAbsolutePath().toString() + "\\*", p); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { // Get data and confirm the 1st name is . for the directory itself. WIN32_FIND_DATA fd = new WIN32_FIND_DATA(p); String actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals(".")); // Get data and confirm the 2nd name is .. for the directory's parent assertTrue(Kernel32.INSTANCE.FindNextFile(hFile, p)); fd = new WIN32_FIND_DATA(p); actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals("..")); // Get data and confirm the 3rd name is the tmp file name assertTrue(Kernel32.INSTANCE.FindNextFile(hFile, p)); fd = new WIN32_FIND_DATA(p); actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals(tmpFile.getName())); // No more files in directory assertFalse(Kernel32.INSTANCE.FindNextFile(hFile, p)); assertEquals(WinNT.ERROR_NO_MORE_FILES, Kernel32.INSTANCE.GetLastError()); } finally { Kernel32.INSTANCE.FindClose(hFile); tmpFile.delete(); Files.delete(tmpDir); } } public void testFindFirstFileExFindExInfoStandard() throws IOException { Path tmpDir = Files.createTempDirectory("testFindFirstFileExFindExInfoStandard"); File tmpFile = new File(Files.createTempFile(tmpDir, "testFindFirstFileExFindExInfoStandard", ".jna").toString()); Memory p = new Memory(WIN32_FIND_DATA.sizeOf()); HANDLE hFile = Kernel32.INSTANCE.FindFirstFileEx(tmpDir.toAbsolutePath().toString() + "\\*", WinBase.FindExInfoStandard, p, WinBase.FindExSearchNameMatch, null, new DWORD(0)); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { // Get data and confirm the 1st name is . for the directory itself. WIN32_FIND_DATA fd = new WIN32_FIND_DATA(p); String actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals(".")); // Get data and confirm the 2nd name is .. for the directory's parent assertTrue(Kernel32.INSTANCE.FindNextFile(hFile, p)); fd = new WIN32_FIND_DATA(p); actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals("..")); // Get data and confirm the 3rd name is the tmp file name assertTrue(Kernel32.INSTANCE.FindNextFile(hFile, p)); fd = new WIN32_FIND_DATA(p); actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals(tmpFile.getName())); // No more files in directory assertFalse(Kernel32.INSTANCE.FindNextFile(hFile, p)); assertEquals(WinNT.ERROR_NO_MORE_FILES, Kernel32.INSTANCE.GetLastError()); } finally { Kernel32.INSTANCE.FindClose(hFile); tmpFile.delete(); Files.delete(tmpDir); } } public void testFindFirstFileExFindExInfoBasic() throws IOException { Path tmpDir = Files.createTempDirectory("testFindFirstFileExFindExInfoBasic"); File tmpFile = new File(Files.createTempFile(tmpDir, "testFindFirstFileExFindExInfoBasic", ".jna").toString()); Memory p = new Memory(WIN32_FIND_DATA.sizeOf()); // Add the file name to the search to get just that one entry HANDLE hFile = Kernel32.INSTANCE.FindFirstFileEx(tmpDir.toAbsolutePath().toString() + "\\" + tmpFile.getName(), WinBase.FindExInfoBasic, p, WinBase.FindExSearchNameMatch, null, new DWORD(0)); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { // Get data and confirm the 1st name is for the file itself WIN32_FIND_DATA fd = new WIN32_FIND_DATA(p); String actualFileName = new String(fd.getFileName()); actualFileName = new String(fd.getFileName()); assertTrue(actualFileName.contentEquals(tmpFile.getName())); // FindExInfoBasic does not return the short name, so confirm that its empty String alternateFileName = fd.getAlternateFileName(); assertTrue(alternateFileName.isEmpty()); // No more files in directory assertFalse(Kernel32.INSTANCE.FindNextFile(hFile, p)); assertEquals(WinNT.ERROR_NO_MORE_FILES, Kernel32.INSTANCE.GetLastError()); } finally { Kernel32.INSTANCE.FindClose(hFile); tmpFile.delete(); Files.delete(tmpDir); } } public void testGetFileInformationByHandleEx() throws IOException { File tmp = File.createTempFile("testGetFileInformationByHandleEx", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_WRITE, WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { Memory p = new Memory(FILE_BASIC_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileBasicInfo, p, new DWORD(p.size()))) { fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); } FILE_BASIC_INFO fbi = new FILE_BASIC_INFO(p); // New file has non-zero creation time assertTrue(0 != fbi.CreationTime.getValue()); p = new Memory(FILE_STANDARD_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileStandardInfo, p, new DWORD(p.size()))) { fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); } FILE_STANDARD_INFO fsi = new FILE_STANDARD_INFO(p); // New file has 1 link assertEquals(1, fsi.NumberOfLinks); p = new Memory(FILE_COMPRESSION_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileCompressionInfo, p, new DWORD(p.size()))) { fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); } FILE_COMPRESSION_INFO fci = new FILE_COMPRESSION_INFO(p); // Uncompressed file should be zero assertEquals(0, fci.CompressionFormat); p = new Memory(FILE_ATTRIBUTE_TAG_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileAttributeTagInfo, p, new DWORD(p.size()))) { fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); } FILE_ATTRIBUTE_TAG_INFO fati = new FILE_ATTRIBUTE_TAG_INFO(p); // New files have the archive bit assertEquals(WinNT.FILE_ATTRIBUTE_ARCHIVE, fati.FileAttributes); p = new Memory(FILE_ID_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileIdInfo, p, new DWORD(p.size()))) { fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); } FILE_ID_INFO fii = new FILE_ID_INFO(p); // Volume serial number should be non-zero assertFalse(fii.VolumeSerialNumber == 0); } finally { Kernel32.INSTANCE.CloseHandle(hFile); } } public void testSetFileInformationByHandleFileBasicInfo() throws IOException, InterruptedException { File tmp = File.createTempFile("testSetFileInformationByHandleFileBasicInfo", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { Memory p = new Memory(FILE_BASIC_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileBasicInfo, p, new DWORD(p.size()))) fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); FILE_BASIC_INFO fbi = new FILE_BASIC_INFO(p); // Add TEMP attribute fbi.FileAttributes = fbi.FileAttributes | WinNT.FILE_ATTRIBUTE_TEMPORARY; fbi.ChangeTime = new WinNT.LARGE_INTEGER(0); fbi.CreationTime = new WinNT.LARGE_INTEGER(0); fbi.LastAccessTime = new WinNT.LARGE_INTEGER(0); fbi.LastWriteTime = new WinNT.LARGE_INTEGER(0); fbi.write(); if (false == Kernel32.INSTANCE.SetFileInformationByHandle(hFile, WinBase.FileBasicInfo, fbi.getPointer(), new DWORD(FILE_BASIC_INFO.sizeOf()))) fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileBasicInfo, p, new DWORD(p.size()))) fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); fbi = new FILE_BASIC_INFO(p); assertTrue((fbi.FileAttributes & WinNT.FILE_ATTRIBUTE_TEMPORARY) != 0); } finally { Kernel32.INSTANCE.CloseHandle(hFile); } } public void testSetFileInformationByHandleFileDispositionInfo() throws IOException, InterruptedException { File tmp = File.createTempFile("testSetFileInformationByHandleFileDispositionInfo", "jna"); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_WRITE | WinNT.DELETE, WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { FILE_DISPOSITION_INFO fdi = new FILE_DISPOSITION_INFO(true); if (false == Kernel32.INSTANCE.SetFileInformationByHandle(hFile, WinBase.FileDispositionInfo, fdi.getPointer(), new DWORD(FILE_DISPOSITION_INFO.sizeOf()))) fail("SetFileInformationByHandle failed with " + Kernel32.INSTANCE.GetLastError()); } finally { Kernel32.INSTANCE.CloseHandle(hFile); } assertFalse(Files.exists(Paths.get(tmp.getAbsolutePath()))); } public void testGetSetFileTime() throws IOException { File tmp = File.createTempFile("testGetSetFileTime", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_WRITE, WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { WinBase.FILETIME.ByReference creationTime = new WinBase.FILETIME.ByReference(); WinBase.FILETIME.ByReference accessTime = new WinBase.FILETIME.ByReference(); WinBase.FILETIME.ByReference modifiedTime = new WinBase.FILETIME.ByReference(); Kernel32.INSTANCE.GetFileTime(hFile, creationTime, accessTime, modifiedTime); assertEquals(creationTime.toDate().getYear(), new Date().getYear()); assertEquals(accessTime.toDate().getYear(), new Date().getYear()); assertEquals(modifiedTime.toDate().getYear(), new Date().getYear()); Kernel32.INSTANCE.SetFileTime(hFile, null, null, new WinBase.FILETIME(new Date(2010, 1, 1))); assertEquals(2010, new Date(tmp.lastModified()).getYear()); } finally { Kernel32Util.closeHandle(hFile); } } public void testSetFileAttributes() throws IOException { File tmp = File.createTempFile("testSetFileAttributes", "jna"); tmp.deleteOnExit(); Kernel32.INSTANCE.SetFileAttributes(tmp.getCanonicalPath(), new DWORD(WinNT.FILE_ATTRIBUTE_HIDDEN)); int attributes = Kernel32.INSTANCE.GetFileAttributes(tmp.getCanonicalPath()); assertTrue((attributes & WinNT.FILE_ATTRIBUTE_HIDDEN) != 0); } public void testGetProcessList() throws IOException { HANDLE processEnumHandle = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL, new WinDef.DWORD(0)); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(processEnumHandle)); try { Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); assertTrue(Kernel32.INSTANCE.Process32First(processEnumHandle, processEntry)); List<Long> processIdList = new ArrayList<Long>(); processIdList.add(processEntry.th32ProcessID.longValue()); while (Kernel32.INSTANCE.Process32Next(processEnumHandle, processEntry)) { processIdList.add(processEntry.th32ProcessID.longValue()); } assertTrue(processIdList.size() > 4); } finally { Kernel32Util.closeHandle(processEnumHandle); } } public final void testGetPrivateProfileInt() throws IOException { final File tmp = File.createTempFile("testGetPrivateProfileInt", "ini"); tmp.deleteOnExit(); final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp))); writer.println("[Section]"); writer.println("existingKey = 123"); writer.close(); assertEquals(123, Kernel32.INSTANCE.GetPrivateProfileInt("Section", "existingKey", 456, tmp.getCanonicalPath())); assertEquals(456, Kernel32.INSTANCE.GetPrivateProfileInt("Section", "missingKey", 456, tmp.getCanonicalPath())); } public final void testGetPrivateProfileString() throws IOException { final File tmp = File.createTempFile("testGetPrivateProfileString", ".ini"); tmp.deleteOnExit(); final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp))); writer.println("[Section]"); writer.println("existingKey = ABC"); writer.close(); final char[] buffer = new char[8]; DWORD len = Kernel32.INSTANCE.GetPrivateProfileString("Section", "existingKey", "DEF", buffer, new DWORD(buffer.length), tmp.getCanonicalPath()); assertEquals(3, len.intValue()); assertEquals("ABC", Native.toString(buffer)); len = Kernel32.INSTANCE.GetPrivateProfileString("Section", "missingKey", "DEF", buffer, new DWORD(buffer.length), tmp.getCanonicalPath()); assertEquals(3, len.intValue()); assertEquals("DEF", Native.toString(buffer)); } public final void testWritePrivateProfileString() throws IOException { final File tmp = File.createTempFile("testWritePrivateProfileString", ".ini"); tmp.deleteOnExit(); final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp))); writer.println("[Section]"); writer.println("existingKey = ABC"); writer.println("removedKey = JKL"); writer.close(); assertTrue(Kernel32.INSTANCE.WritePrivateProfileString("Section", "existingKey", "DEF", tmp.getCanonicalPath())); assertTrue(Kernel32.INSTANCE.WritePrivateProfileString("Section", "addedKey", "GHI", tmp.getCanonicalPath())); assertTrue(Kernel32.INSTANCE.WritePrivateProfileString("Section", "removedKey", null, tmp.getCanonicalPath())); final BufferedReader reader = new BufferedReader(new FileReader(tmp)); assertEquals(reader.readLine(), "[Section]"); assertTrue(reader.readLine().matches("existingKey\\s*=\\s*DEF")); assertTrue(reader.readLine().matches("addedKey\\s*=\\s*GHI")); assertEquals(reader.readLine(), null); reader.close(); } public final void testGetPrivateProfileSection() throws IOException { final File tmp = File.createTempFile("testGetPrivateProfileSection", ".ini"); tmp.deleteOnExit(); final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp))); try { writer.println("[X]"); writer.println("A=1"); writer.println("B=X"); } finally { writer.close(); } final char[] buffer = new char[9]; final DWORD len = Kernel32.INSTANCE.GetPrivateProfileSection("X", buffer, new DWORD(buffer.length), tmp.getCanonicalPath()); assertEquals(len.intValue(), 7); assertEquals(new String(buffer), "A=1\0B=X\0\0"); } public final void testGetPrivateProfileSectionNames() throws IOException { final File tmp = File.createTempFile("testGetPrivateProfileSectionNames", ".ini"); tmp.deleteOnExit(); final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp))); try { writer.println("[S1]"); writer.println("[S2]"); } finally { writer.close(); } final char[] buffer = new char[7]; final DWORD len = Kernel32.INSTANCE.GetPrivateProfileSectionNames(buffer, new DWORD(buffer.length), tmp.getCanonicalPath()); assertEquals(len.intValue(), 5); assertEquals(new String(buffer), "S1\0S2\0\0"); } public final void testWritePrivateProfileSection() throws IOException { final File tmp = File.createTempFile("testWritePrivateProfileSection", ".ini"); tmp.deleteOnExit(); final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(tmp))); try { writer.println("[S1]"); writer.println("A=1"); writer.println("B=X"); } finally { writer.close(); } final boolean result = Kernel32.INSTANCE.WritePrivateProfileSection("S1", "A=3\0E=Z\0\0", tmp.getCanonicalPath()); assertTrue(result); final BufferedReader reader = new BufferedReader(new FileReader(tmp)); assertEquals(reader.readLine(), "[S1]"); assertTrue(reader.readLine().matches("A\\s*=\\s*3")); assertTrue(reader.readLine().matches("E\\s*=\\s*Z")); reader.close(); } /** * Test both SystemTimeToFileTime and FileTimeToSystemTime * @throws IOException */ public final void testSystemTimeToFileTimeAndFileTimeToSystemTime() throws IOException { WinBase.SYSTEMTIME systemTime = new WinBase.SYSTEMTIME(); Kernel32.INSTANCE.GetSystemTime(systemTime); WinBase.FILETIME fileTime = new WinBase.FILETIME(); if (false == Kernel32.INSTANCE.SystemTimeToFileTime(systemTime, fileTime)) { fail("SystemTimeToFileTime failed with " + Kernel32.INSTANCE.GetLastError()); } WinBase.SYSTEMTIME newSystemTime = new WinBase.SYSTEMTIME(); if (false == Kernel32.INSTANCE.FileTimeToSystemTime(fileTime, newSystemTime)) { fail("FileTimeToSystemTime failed with " + Kernel32.INSTANCE.GetLastError()); } assertEquals(systemTime.wYear, newSystemTime.wYear); assertEquals(systemTime.wDay, newSystemTime.wDay); assertEquals(systemTime.wMonth, newSystemTime.wMonth); assertEquals(systemTime.wHour, newSystemTime.wHour); assertEquals(systemTime.wMinute, newSystemTime.wMinute); assertEquals(systemTime.wSecond, newSystemTime.wSecond); assertEquals(systemTime.wMilliseconds, newSystemTime.wMilliseconds); } /** * Test FILETIME's LARGE_INTEGER constructor * @throws IOException */ public final void testFileTimeFromLargeInteger() throws IOException { File tmp = File.createTempFile("testGetFileInformationByHandleEx", "jna"); tmp.deleteOnExit(); HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_WRITE, WinNT.FILE_SHARE_WRITE, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile)); try { Memory p = new Memory(FILE_BASIC_INFO.sizeOf()); if (false == Kernel32.INSTANCE.GetFileInformationByHandleEx(hFile, WinBase.FileBasicInfo, p, new DWORD(p.size()))) { fail("GetFileInformationByHandleEx failed with " + Kernel32.INSTANCE.GetLastError()); } FILE_BASIC_INFO fbi = new FILE_BASIC_INFO(p); FILETIME ft = new FILETIME(fbi.LastWriteTime); SYSTEMTIME stUTC = new SYSTEMTIME(); SYSTEMTIME stLocal = new SYSTEMTIME(); Kernel32.INSTANCE.FileTimeToSystemTime(ft, stUTC); // Covert to local Kernel32.INSTANCE.SystemTimeToTzSpecificLocalTime(null, stUTC, stLocal); FileTime calculatedCreateTime = FileTime.fromMillis(stLocal.toCalendar().getTimeInMillis()); // Actual file's createTime FileTime createTime = Files.getLastModifiedTime(Paths.get(tmp.getAbsolutePath())); assertEquals(createTime.toMillis(), calculatedCreateTime.toMillis()); } finally { Kernel32.INSTANCE.CloseHandle(hFile); } } public final void testCreateRemoteThread() throws IOException { HANDLE hThrd = Kernel32.INSTANCE.CreateRemoteThread(null, null, 0, null, null, null, null); assertNull(hThrd); assertEquals(Kernel32.INSTANCE.GetLastError(), WinError.ERROR_INVALID_HANDLE); } public void testWriteProcessMemory() { Kernel32 kernel = Kernel32.INSTANCE; boolean successWrite = kernel.WriteProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null); assertFalse(successWrite); assertEquals(kernel.GetLastError(), WinError.ERROR_INVALID_HANDLE); ByteBuffer bufDest = ByteBuffer.allocateDirect(4); bufDest.put(new byte[]{0,1,2,3}); ByteBuffer bufSrc = ByteBuffer.allocateDirect(4); bufSrc.put(new byte[]{5,10,15,20}); Pointer ptrSrc = Native.getDirectBufferPointer(bufSrc); Pointer ptrDest = Native.getDirectBufferPointer(bufDest); HANDLE selfHandle = kernel.GetCurrentProcess(); kernel.WriteProcessMemory(selfHandle, ptrDest, ptrSrc, 3, null);//Write only the first three assertEquals(bufDest.get(0),5); assertEquals(bufDest.get(1),10); assertEquals(bufDest.get(2),15); assertEquals(bufDest.get(3),3); } public void testReadProcessMemory() { Kernel32 kernel = Kernel32.INSTANCE; boolean successRead = kernel.ReadProcessMemory(null, Pointer.NULL, Pointer.NULL, 1, null); assertFalse(successRead); assertEquals(kernel.GetLastError(), WinError.ERROR_INVALID_HANDLE); ByteBuffer bufSrc = ByteBuffer.allocateDirect(4); bufSrc.put(new byte[]{5,10,15,20}); ByteBuffer bufDest = ByteBuffer.allocateDirect(4); bufDest.put(new byte[]{0,1,2,3}); Pointer ptrSrc = Native.getDirectBufferPointer(bufSrc); Pointer ptrDest = Native.getDirectBufferPointer(bufDest); HANDLE selfHandle = kernel.GetCurrentProcess(); kernel.ReadProcessMemory(selfHandle, ptrSrc, ptrDest, 3, null);//Read only the first three assertEquals(bufDest.get(0),5); assertEquals(bufDest.get(1),10); assertEquals(bufDest.get(2),15); assertEquals(bufDest.get(3),3); } public void testVirtualQueryEx() { HANDLE selfHandle = Kernel32.INSTANCE.GetCurrentProcess(); MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); SIZE_T bytesRead = Kernel32.INSTANCE.VirtualQueryEx(selfHandle, Pointer.NULL, mbi, new SIZE_T(mbi.size())); assertTrue(bytesRead.intValue() > 0); } public void testGetCommState() { WinBase.DCB lpDCB = new WinBase.DCB(); // Here we test a com port that definitely does not exist! HANDLE handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\comDummy", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); int lastError = Kernel32.INSTANCE.GetLastError(); assertEquals(lastError, WinNT.ERROR_FILE_NOT_FOUND); //try to read the com port state using the invalid handle assertFalse(Kernel32.INSTANCE.GetCommState(handleSerialPort, lpDCB)); // Check if we can open a connection to com port1 // If yes, we try to read the com state // If no com port exists we have to skip this test handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\com1", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); lastError = Kernel32.INSTANCE.GetLastError(); if (WinNT.NO_ERROR == lastError) { assertFalse(WinNT.INVALID_HANDLE_VALUE.equals(handleSerialPort)); try { lpDCB = new WinBase.DCB(); assertTrue(Kernel32.INSTANCE.GetCommState(handleSerialPort, lpDCB)); switch (lpDCB.BaudRate.intValue()) { case WinBase.CBR_110: case WinBase.CBR_1200: case WinBase.CBR_128000: case WinBase.CBR_14400: case WinBase.CBR_19200: case WinBase.CBR_2400: case WinBase.CBR_256000: case WinBase.CBR_300: case WinBase.CBR_38400: case WinBase.CBR_4800: case WinBase.CBR_56000: case WinBase.CBR_600: case WinBase.CBR_9600: break; default: fail("Received value of WinBase.DCB.BaudRate is not valid"); } } finally { Kernel32Util.closeHandle(handleSerialPort); } } } public void testSetCommState() { WinBase.DCB lpDCB = new WinBase.DCB(); // Here we test a com port that definitely does not exist! HANDLE handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\comDummy", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); int lastError = Kernel32.INSTANCE.GetLastError(); assertEquals(lastError, WinNT.ERROR_FILE_NOT_FOUND); // try to read the com port state using the invalid handle assertFalse(Kernel32.INSTANCE.SetCommState(handleSerialPort, lpDCB)); // Check if we can open a connection to com port1 // If yes, we try to read the com state // If no com port exists we have to skip this test handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\com1", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); lastError = Kernel32.INSTANCE.GetLastError(); if (WinNT.NO_ERROR == lastError) { assertFalse(WinNT.INVALID_HANDLE_VALUE.equals(handleSerialPort)); try { lpDCB = new WinBase.DCB(); assertTrue(Kernel32.INSTANCE.GetCommState(handleSerialPort, lpDCB)); DWORD oldBaudRate = new DWORD(lpDCB.BaudRate.longValue()); lpDCB.BaudRate = new DWORD(WinBase.CBR_110); assertTrue(Kernel32.INSTANCE.SetCommState(handleSerialPort, lpDCB)); WinBase.DCB lpNewDCB = new WinBase.DCB(); assertTrue(Kernel32.INSTANCE.GetCommState(handleSerialPort, lpNewDCB)); assertEquals(WinBase.CBR_110, lpNewDCB.BaudRate.intValue()); lpDCB.BaudRate = oldBaudRate; assertTrue(Kernel32.INSTANCE.SetCommState(handleSerialPort, lpDCB)); } finally { Kernel32Util.closeHandle(handleSerialPort); } } } public void testGetCommTimeouts() { WinBase.COMMTIMEOUTS lpCommTimeouts = new WinBase.COMMTIMEOUTS(); // Here we test a com port that definitely does not exist! HANDLE handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\comDummy", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); int lastError = Kernel32.INSTANCE.GetLastError(); assertEquals(lastError, WinNT.ERROR_FILE_NOT_FOUND); // try to read the com port timeouts using the invalid handle assertFalse(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpCommTimeouts)); // Check if we can open a connection to com port1 // If yes, we try to read the com state // If no com port exists we have to skip this test handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\com1", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); lastError = Kernel32.INSTANCE.GetLastError(); if (WinNT.NO_ERROR == lastError) { assertFalse(WinNT.INVALID_HANDLE_VALUE.equals(handleSerialPort)); try { lpCommTimeouts = new WinBase.COMMTIMEOUTS(); assertTrue(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpCommTimeouts)); } finally { Kernel32Util.closeHandle(handleSerialPort); } } } public void testSetCommTimeouts() { WinBase.COMMTIMEOUTS lpCommTimeouts = new WinBase.COMMTIMEOUTS(); // Here we test a com port that definitely does not exist! HANDLE handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\comDummy", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); int lastError = Kernel32.INSTANCE.GetLastError(); assertEquals(lastError, WinNT.ERROR_FILE_NOT_FOUND); // try to store the com port timeouts using the invalid handle assertFalse(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts)); // Check if we can open a connection to com port1 // If yes, we try to store the com timeouts // If no com port exists we have to skip this test handleSerialPort = Kernel32.INSTANCE.CreateFile("\\\\.\\com1", WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); lastError = Kernel32.INSTANCE.GetLastError(); if (WinNT.NO_ERROR == lastError) { assertFalse(WinNT.INVALID_HANDLE_VALUE.equals(handleSerialPort)); try { lpCommTimeouts = new WinBase.COMMTIMEOUTS(); assertTrue(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpCommTimeouts)); DWORD oldReadIntervalTimeout = new DWORD(lpCommTimeouts.ReadIntervalTimeout.longValue()); lpCommTimeouts.ReadIntervalTimeout = new DWORD(20); assertTrue(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts)); WinBase.COMMTIMEOUTS lpNewCommTimeouts = new WinBase.COMMTIMEOUTS(); assertTrue(Kernel32.INSTANCE.GetCommTimeouts(handleSerialPort, lpNewCommTimeouts)); assertEquals(20, lpNewCommTimeouts.ReadIntervalTimeout.intValue()); lpCommTimeouts.ReadIntervalTimeout = oldReadIntervalTimeout; assertTrue(Kernel32.INSTANCE.SetCommTimeouts(handleSerialPort, lpCommTimeouts)); } finally { Kernel32Util.closeHandle(handleSerialPort); } } } public void testProcessIdToSessionId() { int myProcessID = Kernel32.INSTANCE.GetCurrentProcessId(); IntByReference pSessionId = new IntByReference(); boolean result = Kernel32.INSTANCE.ProcessIdToSessionId(myProcessID, pSessionId); // should give us our session ID assertTrue("ProcessIdToSessionId should return true.", result); // on Win Vista and later we'll never be session 0 // due to service isolation // anything negative would be a definite error. assertTrue("Session should be 1 or higher because of service isolation", pSessionId.getValue() > 0); } public void testLoadLibraryEx() { String winDir = Kernel32Util.getEnvironmentVariable("WINDIR"); assertNotNull("No WINDIR value returned", winDir); assertTrue("Specified WINDIR does not exist: " + winDir, new File(winDir).exists()); HMODULE hModule = null; try { hModule = Kernel32.INSTANCE.LoadLibraryEx(new File(winDir, "explorer.exe").getAbsolutePath(), null, Kernel32.LOAD_LIBRARY_AS_DATAFILE); if (hModule == null) { throw new Win32Exception(Native.getLastError()); } assertNotNull("hModule should not be null.", hModule); } finally { if (hModule != null) { if (!Kernel32.INSTANCE.FreeLibrary(hModule)) { throw new Win32Exception(Native.getLastError()); } } } } public void testEnumResourceNames() { // "14" is the type name of the My Computer icon in explorer.exe Pointer pointer = new Memory(Native.WCHAR_SIZE * 3); pointer.setWideString(0, "14"); WinBase.EnumResNameProc ernp = new WinBase.EnumResNameProc() { @Override public boolean invoke(HMODULE module, Pointer type, Pointer name, Pointer lParam) { return true; } }; // null HMODULE means use this process / its EXE // there are no type "14" resources in it. boolean result = Kernel32.INSTANCE.EnumResourceNames(null, pointer, ernp, null); assertFalse("EnumResourceNames should have failed.", result); assertEquals("GetLastError should be set to 1813", WinError.ERROR_RESOURCE_TYPE_NOT_FOUND, Kernel32.INSTANCE.GetLastError()); } public void testEnumResourceTypes() { final List<String> types = new ArrayList<String>(); WinBase.EnumResTypeProc ertp = new WinBase.EnumResTypeProc() { @Override public boolean invoke(HMODULE module, Pointer type, Pointer lParam) { // simulate IS_INTRESOURCE macro defined in WinUser.h // basically that means that if "type" is less than or equal to 65,535 // it assumes it's an ID. // otherwise it assumes it's a pointer to a string if (Pointer.nativeValue(type) <= 65535) { types.add(Pointer.nativeValue(type) + ""); } else { types.add(type.getWideString(0)); } return true; } }; // null HMODULE means use this process / its EXE // there are no type "14" resources in it. boolean result = Kernel32.INSTANCE.EnumResourceTypes(null, ertp, null); assertTrue("EnumResourceTypes should not have failed.", result); assertEquals("GetLastError should be set to 0", WinError.ERROR_SUCCESS, Kernel32.INSTANCE.GetLastError()); assertTrue("EnumResourceTypes should return some resource type names", types.size() > 0); } public void testModule32FirstW() { HANDLE snapshot = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPMODULE, new DWORD(Kernel32.INSTANCE.GetCurrentProcessId())); if (snapshot == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } Win32Exception we = null; Tlhelp32.MODULEENTRY32W first = new Tlhelp32.MODULEENTRY32W(); try { if (!Kernel32.INSTANCE.Module32FirstW(snapshot, first)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } // not sure if this will be run against java.exe or javaw.exe but this // check tests both assertTrue("The first module in the current process should be java.exe or javaw.exe", first.szModule().startsWith("java")); assertEquals("The process ID of the module ID should be our process ID", Kernel32.INSTANCE.GetCurrentProcessId(), first.th32ProcessID.intValue()); } catch (Win32Exception e) { we = e; throw we; // re-throw so finally block is executed } finally { try { Kernel32Util.closeHandle(snapshot); } catch(Win32Exception e) { if (we == null) { we = e; } else { we.addSuppressed(e); } } if (we != null) { throw we; } } } public void testModule32NextW() { HANDLE snapshot = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPMODULE, new DWORD(Kernel32.INSTANCE.GetCurrentProcessId())); if (snapshot == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } Win32Exception we = null; Tlhelp32.MODULEENTRY32W first = new Tlhelp32.MODULEENTRY32W(); try { if (!Kernel32.INSTANCE.Module32NextW(snapshot, first)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } // not sure if this will be run against java.exe or javaw.exe but this // check tests both assertTrue("The first module in the current process should be java.exe or javaw.exe", first.szModule().startsWith("java")); assertEquals("The process ID of the module ID should be our process ID", Kernel32.INSTANCE.GetCurrentProcessId(), first.th32ProcessID.intValue()); } catch (Win32Exception e) { we = e; throw we; // re-throw so finally block is executed } finally { try { Kernel32Util.closeHandle(snapshot); } catch(Win32Exception e) { if (we == null) { we = e; } else { we.addSuppressed(e); } } if (we != null) { throw we; } } } public void testSetErrorMode() { // Set bit flags to 0x0001 int previousMode = Kernel32.INSTANCE.SetErrorMode(0x0001); // Restore to previous state; 0x0001 is now "previous" assertEquals(Kernel32.INSTANCE.SetErrorMode(previousMode), 0x0001); } // Testcase is disabled, as kernel32 ordinal values are not stable. // a library with a stable function <-> ordinal value is needed. // /** // * Test that a named function on win32 can be equally resolved by its ordinal // * value. // * // * From link.exe /dump /exports c:\\Windows\\System32\\kernel32.dll // * // * 746 2E9 0004FA20 GetTapeStatus // * 747 2EA 0002DB20 GetTempFileNameA // * 748 2EB 0002DB30 GetTempFileNameW // * 749 2EC 0002DB40 GetTempPathA // * 750 2ED 0002DB50 GetTempPathW // * 751 2EE 00026780 GetThreadContext // * // * The tested function is GetTempPathW which is mapped to the ordinal 750. // */ // public void testGetProcAddress() { // NativeLibrary kernel32Library = NativeLibrary.getInstance("kernel32"); // // get module handle needed to resolve function pointer via GetProcAddress // HMODULE kernel32Module = Kernel32.INSTANCE.GetModuleHandle("kernel32"); // Function namedFunction = kernel32Library.getFunction("GetTempPathW"); // long namedFunctionPointerValue = Pointer.nativeValue(namedFunction); // Pointer ordinalFunction = Kernel32.INSTANCE.GetProcAddress(kernel32Module, 750); // long ordinalFunctionPointerValue = Pointer.nativeValue(ordinalFunction); // assertEquals(namedFunctionPointerValue, ordinalFunctionPointerValue); public void testSetThreadExecutionState() { int originalExecutionState = Kernel32.INSTANCE.SetThreadExecutionState( WinBase.ES_CONTINUOUS | WinBase.ES_SYSTEM_REQUIRED | WinBase.ES_AWAYMODE_REQUIRED ); assert originalExecutionState > 0; int intermediateExecutionState = Kernel32.INSTANCE.SetThreadExecutionState( WinBase.ES_CONTINUOUS ); assertEquals(WinBase.ES_CONTINUOUS | WinBase.ES_SYSTEM_REQUIRED | WinBase.ES_AWAYMODE_REQUIRED, intermediateExecutionState); Kernel32.INSTANCE.SetThreadExecutionState(originalExecutionState); } }
package javaa.javassist; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; public class JavassistDemo2 { // : no such field: start -- javaassit public static void main(String[] args) throws Exception { ClassPool pool = ClassPool.getDefault(); CtClass clazz = pool.get("javaa.javassist.Target2"); if (clazz.isFrozen()) { clazz.defrost(); } CtMethod[] allMethods = clazz.getDeclaredMethods(); for (CtMethod _method : allMethods) { String name = _method.getName(); String _name = "_"+name; _method.setName(_name); StringBuilder sb = new StringBuilder(); sb.append("{\n"); sb.append("long start = System.nanoTime();\n"); sb.append(_name+"($$);\n"); //_foo(). $$ sb.append("long end = System.nanoTime();\nSystem.out.println(\"szw javassit exec "+name+"() : \" + (end - start));\n"); sb.append("}"); CtMethod method = CtNewMethod.make(sb.toString(), clazz); clazz.addMethod(method); } clazz.writeFile(); clazz.detach(); Target2 obj = new Target2(); obj.exeStrings(); obj.exeStringBuilder(); } }
package test.SVPA; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Test; import org.sat4j.specs.TimeoutException; import automata.AutomataException; import automata.svpa.Call; import automata.svpa.ImportCharSVPA; import automata.svpa.Internal; import automata.svpa.Return; import automata.svpa.SVPA; import automata.svpa.SVPAMove; import automata.svpa.TaggedSymbol; import automata.svpa.TaggedSymbol.SymbolTag; import theory.BooleanAlgebra; import theory.characters.BinaryCharPred; import theory.characters.CharPred; import theory.characters.ICharPred; import theory.characters.StdCharPred; import theory.intervals.EqualitySolver; import theory.intervals.UnaryCharIntervalSolver; public class SVPAUnitTest { @Test public void testCreateDot() { autA.createDotFile("vpaA", ""); } @Test public void testPropertiesAccessors() throws TimeoutException { assertTrue(autA.isDeterministic(ba)); assertTrue(autA.stateCount == 2); assertTrue(autA.transitionCount == 6); } @Test public void testEmptyFull() { SVPA<ICharPred, Character> empty = SVPA.getEmptySVPA(ba); SVPA<ICharPred, Character> full = SVPA.getFullSVPA(ba); assertTrue(empty.isEmpty); assertFalse(full.isEmpty); } @Test public void testAccept() { assertTrue(autA.accepts(ab, ba)); assertTrue(autA.accepts(anotb, ba)); assertFalse(autA.accepts(notab, ba)); assertFalse(autA.accepts(notanotb, ba)); assertTrue(autB.accepts(ab, ba)); assertFalse(autB.accepts(anotb, ba)); assertTrue(autB.accepts(notab, ba)); assertFalse(autB.accepts(notanotb, ba)); } @Test public void testIntersectionWith() throws TimeoutException { // Compute intersection SVPA<ICharPred, Character> inters = autA.intersectionWith(autB, ba); assertTrue(inters.accepts(ab, ba)); assertFalse(inters.accepts(anotb, ba)); assertFalse(inters.accepts(notab, ba)); assertFalse(inters.accepts(notanotb, ba)); } @Test public void testUnion() { // Compute union SVPA<ICharPred, Character> inters = autA.unionWith(autB, ba); assertTrue(inters.accepts(ab, ba)); assertTrue(inters.accepts(anotb, ba)); assertTrue(inters.accepts(notab, ba)); assertFalse(inters.accepts(notanotb, ba)); } @Test public void testMkTotal() throws TimeoutException { SVPA<ICharPred, Character> totA = autA.mkTotal(ba); assertTrue(totA.accepts(ab, ba)); assertTrue(totA.accepts(anotb, ba)); assertFalse(totA.accepts(notab, ba)); assertFalse(totA.accepts(notanotb, ba)); assertTrue(totA.stateCount == autA.stateCount + 1); assertTrue(totA.transitionCount == 21); } // @Test // public void testComplement() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> complementA = autA // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> autB = getSVPAb(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> complementB= autB // .complement(ba); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> la = Arrays.asList(i1); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lb = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lnot = Arrays.asList(c1,r5); // assertTrue(autA.accepts(la, ba)); // assertFalse(autA.accepts(lb, ba)); // assertTrue(autA.accepts(lab, ba)); // assertFalse(autA.accepts(lnot, ba)); // assertFalse(complementA.accepts(la, ba)); // assertTrue(complementA.accepts(lb, ba)); // assertFalse(complementA.accepts(lab, ba)); // assertTrue(complementA.accepts(lnot, ba)); // assertFalse(autB.accepts(la, ba)); // assertTrue(autB.accepts(lb, ba)); // assertTrue(autB.accepts(lab, ba)); // assertFalse(autB.accepts(lnot, ba)); // assertTrue(complementB.accepts(la, ba)); // assertFalse(complementB.accepts(lb, ba)); // assertFalse(complementB.accepts(lab, ba)); // assertTrue(complementB.accepts(lnot, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testDeterminization() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> detA= autA // .determinize(ba); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> la = Arrays.asList(c5,i1,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lb = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lnot = Arrays.asList(c1,r5); // assertTrue(autA.accepts(la, ba)); // assertFalse(autA.accepts(lb, ba)); // assertTrue(autA.accepts(lab, ba)); // assertFalse(autA.accepts(lnot, ba)); // assertTrue(detA.accepts(la, ba)); // assertFalse(detA.accepts(lb, ba)); // assertTrue(detA.accepts(lab, ba)); // assertFalse(detA.accepts(lnot, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testEpsilonRem() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> epsFree= autA // .removeEpsilonMoves(ba); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> la = Arrays.asList(i1); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lb = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lnot = Arrays.asList(c1,r5); // assertTrue(autA.accepts(la, ba)); // assertFalse(autA.accepts(lb, ba)); // assertTrue(autA.accepts(lab, ba)); // assertFalse(autA.accepts(lnot, ba)); // assertTrue(epsFree.accepts(la, ba)); // assertFalse(epsFree.accepts(lb, ba)); // assertTrue(epsFree.accepts(lab, ba)); // assertFalse(epsFree.accepts(lnot, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testDiff() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> autB = getSVPAb(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> diff = autA // .minus(autB, z3p); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> a = Arrays.asList(i1); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> b = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> ab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> notab = Arrays.asList(c1,r5); // assertTrue(autA.accepts(a, ba)); // assertFalse(autA.accepts(b, ba)); // assertTrue(autA.accepts(ab, ba)); // assertFalse(autA.accepts(notab, ba)); // assertTrue(autB.accepts(b, ba)); // assertFalse(autB.accepts(a, ba)); // assertTrue(autB.accepts(ab, ba)); // assertFalse(autB.accepts(notab, ba)); // assertFalse(diff.accepts(ab, ba)); // assertTrue(diff.accepts(a, ba)); // assertFalse(diff.accepts(b, ba)); // assertFalse(diff.accepts(notab, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testEquivalence() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> cA = autA // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> cUcA = autA // .unionWith(cA, ba); // SVPA<Predicate<IntExpr>, IntExpr> ccA = cA // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> autB = getSVPAb(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> cB = autB // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> cUcB = autB // .unionWith(cB, ba); // SVPA<Predicate<IntExpr>, IntExpr> ccB = cB // .complement(ba); // assertFalse(autA.isEquivalentTo(autB, ba)); // autA.createDotFile("a", ""); // autA.removeEpsilonMoves(ba).createDotFile("ae", ""); // autA.removeEpsilonMoves(ba).mkTotal(ba).createDotFile("at", ""); // autA.createDotFile("a1", ""); // autA.createDotFile("a1", ""); // autA.minus(ccA, ba).createDotFile("diff1", ""); // ccA.minus(autA, ba).createDotFile("diff2", ""); // cA.createDotFile("ca", ""); // ccA.createDotFile("cca", ""); // assertTrue(autA.isEquivalentTo(ccA, ba)); // assertTrue(autB.isEquivalentTo(ccB, ba)); // assertTrue(autA.isEquivalentTo(autA.intersectionWith(autA, ba), ba)); // assertTrue(SVPA.getEmptySVPA(ba).isEquivalentTo(autA.minus(autA, ba), // assertTrue(cUcA.isEquivalentTo(SVPA.getFullSVPA(ba), ba)); // assertTrue(cUcB.isEquivalentTo(SVPA.getFullSVPA(ba), ba)); // assertTrue(cUcB.isEquivalentTo(cUcA, ba)); // assertFalse(autB.isEquivalentTo(autA, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testEpsRemove() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // //First Automaton // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // //Second Automaton // SVPA<Predicate<IntExpr>, IntExpr> autAnoEps = // autA.removeEpsilonMoves(ba); // assertFalse(autA.isEpsilonFree); // assertTrue(autAnoEps.isEpsilonFree); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testGetWitness() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // autA.getWitness(ba); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testReachRem() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // Predicate<IntExpr> geq0 = new Predicate<IntExpr>("x", c.MkGe( // (IntExpr) c.MkConst(c.MkSymbol("x"), c.IntSort()), // c.MkInt(0)), c.IntSort()); // Collection<SVPAMove<Predicate<IntExpr>, IntExpr>> transA = new // LinkedList<SVPAMove<Predicate<IntExpr>, IntExpr>>(); // transA.add(new Call<Predicate<IntExpr>, IntExpr>(0,1,0, // geq0)); // transA.add(new Return<Predicate<IntExpr>, IntExpr>(1,2,0, // geq0)); // //First Automaton // SVPA<Predicate<IntExpr>, IntExpr> autA = SVPA.MkSVPA(transA, // Arrays.asList(0), Arrays.asList(2), ba); // assertFalse(autA.isEmpty); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // Predicates UnaryCharIntervalSolver uba = new UnaryCharIntervalSolver(); EqualitySolver ba = new EqualitySolver(); CharPred alpha = StdCharPred.LOWER_ALPHA; CharPred allAlpha = StdCharPred.ALPHA; CharPred a = new CharPred('a'); CharPred num = StdCharPred.NUM; CharPred trueChar = StdCharPred.TRUE; CharPred trueRetChar = new CharPred(CharPred.MIN_CHAR, CharPred.MAX_CHAR, true); CharPred comma = new CharPred(','); Integer onlyX = 1; BinaryCharPred equality = new BinaryCharPred(StdCharPred.TRUE, true); TaggedSymbol<Character> ca = new TaggedSymbol<>('a', SymbolTag.Call); TaggedSymbol<Character> ra = new TaggedSymbol<>('a', SymbolTag.Return); TaggedSymbol<Character> cb = new TaggedSymbol<Character>('b', SymbolTag.Call); TaggedSymbol<Character> rb = new TaggedSymbol<Character>('b', SymbolTag.Return); TaggedSymbol<Character> c1 = new TaggedSymbol<Character>('1', SymbolTag.Call); TaggedSymbol<Character> r1 = new TaggedSymbol<Character>('1', SymbolTag.Return); TaggedSymbol<Character> ia = new TaggedSymbol<Character>('a', SymbolTag.Internal); TaggedSymbol<Character> ib = new TaggedSymbol<Character>('b', SymbolTag.Internal); TaggedSymbol<Character> i1 = new TaggedSymbol<Character>('1', SymbolTag.Internal); List<TaggedSymbol<Character>> matchedAlpha = Arrays.asList(ca, ra); List<TaggedSymbol<Character>> unmatchedAlpha = Arrays.asList(ca, ca, rb, ra); List<TaggedSymbol<Character>> hasNum = Arrays.asList(c1, r1, ca); List<TaggedSymbol<Character>> internalAlpha = Arrays.asList(ia, ib); List<TaggedSymbol<Character>> internalNum = Arrays.asList(ia, ib, i1); List<TaggedSymbol<Character>> ab = Arrays.asList(cb, ia, rb); List<TaggedSymbol<Character>> notab = Arrays.asList(cb, ia); List<TaggedSymbol<Character>> anotb = Arrays.asList(cb, ib, ca, ra, rb); List<TaggedSymbol<Character>> notanotb = Arrays.asList(ca, ib); SVPA<ICharPred, Character> autA = getSVPAa(ba); SVPA<ICharPred, Character> autB = getSVPAb(ba); SVPA<ICharPred, Character> autPeter = getCFGAutomata(ba); // Only accepts well-matched nested words of lower alphabetic chars private SVPA<ICharPred, Character> getSVPAa(BooleanAlgebra<ICharPred, Character> ba) { Collection<SVPAMove<ICharPred, Character>> transitions = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions.add(new Internal<ICharPred, Character>(0, 0, alpha)); transitions.add(new Internal<ICharPred, Character>(1, 1, alpha)); transitions.add(new Call<ICharPred, Character>(0, 1, 0, alpha)); transitions.add(new Return<ICharPred, Character>(1, 0, 0, equality)); transitions.add(new Call<ICharPred, Character>(1, 1, 1, alpha)); transitions.add(new Return<ICharPred, Character>(1, 1, 1, equality)); try { return SVPA.MkSVPA(transitions, Arrays.asList(0), Arrays.asList(0), ba); } catch (AutomataException e) { return null; } catch (TimeoutException e) { return null; } } // Contains a somewhere as internal doesn't care about other symbols private SVPA<ICharPred, Character> getSVPAb(BooleanAlgebra<ICharPred, Character> ba){ Collection<SVPAMove<ICharPred, Character>> transitions = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions.add(new Internal<ICharPred, Character>(0, 0, trueChar)); transitions.add(new Internal<ICharPred, Character>(1, 1, trueChar)); transitions.add(new Internal<ICharPred, Character>(0, 1, a)); transitions.add(new Call<ICharPred, Character>(0, 0, 0, trueChar)); transitions.add(new Return<ICharPred, Character>(0, 0, 0, trueRetChar)); transitions.add(new Call<ICharPred, Character>(1, 1, 0, trueChar)); transitions.add(new Return<ICharPred, Character>(1, 1, 0, trueRetChar)); try { return SVPA.MkSVPA(transitions, Arrays.asList(0), Arrays.asList(1), ba); } catch (AutomataException e) { return null; } catch (TimeoutException e) { return null; } } // Test from Peter Ohman private SVPA<ICharPred, Character> getCFGAutomata(BooleanAlgebra<ICharPred, Character> ba) { Collection<SVPAMove<ICharPred, Character>> transitions = new LinkedList<SVPAMove<ICharPred, Character>>(); // extra state "0" is prior to the entry of "main" transitions.add(new Internal<ICharPred, Character>(0, 1, new CharPred('1'))); transitions.add(new Call<ICharPred, Character>(1, 2, 1, new CharPred('2'))); transitions.add(new Internal<ICharPred, Character>(2, 3, new CharPred('3'))); transitions.add(new Internal<ICharPred, Character>(2, 4, new CharPred('4'))); transitions.add(new Call<ICharPred, Character>(3, 2, 3, new CharPred('2'))); transitions.add(new Return<ICharPred, Character>(4, 5, 3, new CharPred('5',true))); transitions.add(new Return<ICharPred, Character>(4, 6, 1, new CharPred('6',true))); transitions.add(new Return<ICharPred, Character>(4, 8, 7, new CharPred('8',true))); transitions.add(new Internal<ICharPred, Character>(5, 4, new CharPred('4'))); transitions.add(new Internal<ICharPred, Character>(6, 7, new CharPred('7'))); transitions.add(new Call<ICharPred, Character>(7, 2, 7, new CharPred('2'))); transitions.add(new Internal<ICharPred, Character>(8, 9, new CharPred('9'))); try { SVPA<ICharPred, Character> svpa = SVPA.MkSVPA(transitions, Arrays.asList(0), Arrays.asList(5), ba); //List<TaggedSymbol<Character>> l = svpa.getWitness(ba); //System.out.println(l); return svpa; } catch (AutomataException e) { return null; } catch (TimeoutException e) { return null; } } // Utility function for getBigIntersection() test private CharPred allCharsExcept(Character excluded, boolean returnPred){ if(excluded == null){ if(returnPred) return(trueRetChar); else return(StdCharPred.TRUE); } // weird stuff to avoid Java errors for increment/decrementing chars char prev = excluded; prev char next = excluded; next++; return(new CharPred(ImmutableList.of(ImmutablePair.of(CharPred.MIN_CHAR, prev), ImmutablePair.of(next, CharPred.MAX_CHAR)), returnPred)); } // Another test from Peter @Test public void testBigIntersection() throws TimeoutException{ try { SVPA<ICharPred, Character> svpa = getBigIntersection(); assertFalse(svpa.isEmpty); } catch (AutomataException e) { e.printStackTrace(); assertTrue(false); } } public SVPA<ICharPred, Character> getBigIntersection() throws AutomataException, TimeoutException { EqualitySolver ba = new EqualitySolver(); Collection<SVPAMove<ICharPred, Character>> transitions1 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions1.add(new Internal<ICharPred, Character>(0, 1, new CharPred((char)0x0000))); transitions1.add(new Internal<ICharPred, Character>(3, 2, new CharPred((char)0x0001))); transitions1.add(new Internal<ICharPred, Character>(5, 4, new CharPred((char)0x0003))); transitions1.add(new Internal<ICharPred, Character>(4, 6, new CharPred((char)0x0005))); transitions1.add(new Internal<ICharPred, Character>(6, 7, new CharPred((char)0x0006))); transitions1.add(new Internal<ICharPred, Character>(7, 3, new CharPred((char)0x0002))); transitions1.add(new Internal<ICharPred, Character>(9, 8, new CharPred((char)0x0007))); transitions1.add(new Internal<ICharPred, Character>(11, 10, new CharPred((char)0x0009))); transitions1.add(new Internal<ICharPred, Character>(10, 12, new CharPred((char)0x000B))); transitions1.add(new Internal<ICharPred, Character>(14, 13, new CharPred((char)0x000C))); transitions1.add(new Internal<ICharPred, Character>(15, 14, new CharPred((char)0x000D))); transitions1.add(new Internal<ICharPred, Character>(17, 16, new CharPred((char)0x000F))); transitions1.add(new Internal<ICharPred, Character>(17, 18, new CharPred((char)0x0011))); transitions1.add(new Internal<ICharPred, Character>(18, 19, new CharPred((char)0x0012))); transitions1.add(new Internal<ICharPred, Character>(21, 20, new CharPred((char)0x0013))); transitions1.add(new Internal<ICharPred, Character>(21, 22, new CharPred((char)0x0015))); transitions1.add(new Internal<ICharPred, Character>(22, 17, new CharPred((char)0x0010))); transitions1.add(new Internal<ICharPred, Character>(24, 23, new CharPred((char)0x0016))); transitions1.add(new Internal<ICharPred, Character>(23, 21, new CharPred((char)0x0014))); transitions1.add(new Internal<ICharPred, Character>(25, 9, new CharPred((char)0x0008))); transitions1.add(new Internal<ICharPred, Character>(27, 26, new CharPred((char)0x0019))); transitions1.add(new Internal<ICharPred, Character>(27, 28, new CharPred((char)0x001B))); transitions1.add(new Internal<ICharPred, Character>(30, 29, new CharPred((char)0x001C))); transitions1.add(new Internal<ICharPred, Character>(32, 31, new CharPred((char)0x001E))); transitions1.add(new Internal<ICharPred, Character>(33, 31, new CharPred((char)0x001E))); transitions1.add(new Internal<ICharPred, Character>(34, 32, new CharPred((char)0x001F))); transitions1.add(new Internal<ICharPred, Character>(34, 33, new CharPred((char)0x0020))); transitions1.add(new Internal<ICharPred, Character>(36, 35, new CharPred((char)0x0022))); transitions1.add(new Internal<ICharPred, Character>(38, 37, new CharPred((char)0x0024))); transitions1.add(new Internal<ICharPred, Character>(38, 36, new CharPred((char)0x0023))); transitions1.add(new Internal<ICharPred, Character>(28, 39, new CharPred((char)0x0026))); transitions1.add(new Internal<ICharPred, Character>(41, 40, new CharPred((char)0x0027))); transitions1.add(new Internal<ICharPred, Character>(43, 42, new CharPred((char)0x0029))); transitions1.add(new Internal<ICharPred, Character>(35, 43, new CharPred((char)0x002A))); transitions1.add(new Internal<ICharPred, Character>(35, 44, new CharPred((char)0x002B))); transitions1.add(new Internal<ICharPred, Character>(46, 45, new CharPred((char)0x002C))); transitions1.add(new Internal<ICharPred, Character>(45, 47, new CharPred((char)0x002E))); transitions1.add(new Internal<ICharPred, Character>(47, 48, new CharPred((char)0x002F))); transitions1.add(new Internal<ICharPred, Character>(48, 49, new CharPred((char)0x0030))); transitions1.add(new Internal<ICharPred, Character>(49, 50, new CharPred((char)0x0031))); transitions1.add(new Internal<ICharPred, Character>(50, 51, new CharPred((char)0x0032))); transitions1.add(new Internal<ICharPred, Character>(51, 52, new CharPred((char)0x0033))); transitions1.add(new Internal<ICharPred, Character>(52, 53, new CharPred((char)0x0034))); transitions1.add(new Internal<ICharPred, Character>(53, 54, new CharPred((char)0x0035))); transitions1.add(new Internal<ICharPred, Character>(54, 55, new CharPred((char)0x0036))); transitions1.add(new Internal<ICharPred, Character>(56, 34, new CharPred((char)0x0021))); transitions1.add(new Internal<ICharPred, Character>(56, 57, new CharPred((char)0x0038))); transitions1.add(new Internal<ICharPred, Character>(59, 58, new CharPred((char)0x0039))); transitions1.add(new Internal<ICharPred, Character>(59, 60, new CharPred((char)0x003B))); transitions1.add(new Internal<ICharPred, Character>(57, 61, new CharPred((char)0x003C))); transitions1.add(new Internal<ICharPred, Character>(62, 59, new CharPred((char)0x003A))); transitions1.add(new Internal<ICharPred, Character>(64, 63, new CharPred((char)0x003E))); transitions1.add(new Internal<ICharPred, Character>(64, 65, new CharPred((char)0x0040))); transitions1.add(new Internal<ICharPred, Character>(67, 66, new CharPred((char)0x0041))); transitions1.add(new Internal<ICharPred, Character>(60, 64, new CharPred((char)0x003F))); transitions1.add(new Internal<ICharPred, Character>(69, 68, new CharPred((char)0x0043))); transitions1.add(new Internal<ICharPred, Character>(71, 70, new CharPred((char)0x0045))); transitions1.add(new Internal<ICharPred, Character>(70, 67, new CharPred((char)0x0042))); transitions1.add(new Internal<ICharPred, Character>(65, 69, new CharPred((char)0x0044))); transitions1.add(new Internal<ICharPred, Character>(73, 72, new CharPred((char)0x0047))); transitions1.add(new Internal<ICharPred, Character>(68, 73, new CharPred((char)0x0048))); transitions1.add(new Internal<ICharPred, Character>(75, 74, new CharPred((char)0x0049))); transitions1.add(new Internal<ICharPred, Character>(77, 76, new CharPred((char)0x004B))); transitions1.add(new Internal<ICharPred, Character>(79, 78, new CharPred((char)0x004D))); transitions1.add(new Internal<ICharPred, Character>(12, 79, new CharPred((char)0x004E))); transitions1.add(new Internal<ICharPred, Character>(31, 80, new CharPred((char)0x004F))); transitions1.add(new Internal<ICharPred, Character>(81, 21, new CharPred((char)0x0014))); transitions1.add(new Internal<ICharPred, Character>(82, 81, new CharPred((char)0x0050))); transitions1.add(new Internal<ICharPred, Character>(20, 82, new CharPred((char)0x0051))); transitions1.add(new Internal<ICharPred, Character>(16, 24, new CharPred((char)0x0017))); transitions1.add(new Internal<ICharPred, Character>(83, 15, new CharPred((char)0x000E))); transitions1.add(new Internal<ICharPred, Character>(72, 83, new CharPred((char)0x0052))); transitions1.add(new Internal<ICharPred, Character>(1, 84, new CharPred((char)0x0053))); transitions1.add(new Internal<ICharPred, Character>(84, 82, new CharPred((char)0x0051))); transitions1.add(new Internal<ICharPred, Character>(84, 85, new CharPred((char)0x0054))); transitions1.add(new Internal<ICharPred, Character>(85, 24, new CharPred((char)0x0017))); transitions1.add(new Internal<ICharPred, Character>(8, 86, new CharPred((char)0x0055))); transitions1.add(new Internal<ICharPred, Character>(86, 87, new CharPred((char)0x0056))); transitions1.add(new Internal<ICharPred, Character>(89, 88, new CharPred((char)0x0057))); transitions1.add(new Internal<ICharPred, Character>(90, 89, new CharPred((char)0x0058))); transitions1.add(new Internal<ICharPred, Character>(91, 75, new CharPred((char)0x004A))); transitions1.add(new Internal<ICharPred, Character>(55, 91, new CharPred((char)0x005A))); transitions1.add(new Internal<ICharPred, Character>(74, 92, new CharPred((char)0x005B))); transitions1.add(new Internal<ICharPred, Character>(92, 77, new CharPred((char)0x004C))); transitions1.add(new Internal<ICharPred, Character>(93, 90, new CharPred((char)0x0059))); transitions1.add(new Internal<ICharPred, Character>(76, 93, new CharPred((char)0x005C))); transitions1.add(new Internal<ICharPred, Character>(58, 64, new CharPred((char)0x003F))); transitions1.add(new Internal<ICharPred, Character>(95, 94, new CharPred((char)0x005D))); transitions1.add(new Internal<ICharPred, Character>(95, 96, new CharPred((char)0x005F))); transitions1.add(new Internal<ICharPred, Character>(98, 97, new CharPred((char)0x0060))); transitions1.add(new Internal<ICharPred, Character>(98, 99, new CharPred((char)0x0062))); transitions1.add(new Internal<ICharPred, Character>(97, 100, new CharPred((char)0x0063))); transitions1.add(new Internal<ICharPred, Character>(100, 101, new CharPred((char)0x0064))); transitions1.add(new Internal<ICharPred, Character>(101, 73, new CharPred((char)0x0048))); transitions1.add(new Internal<ICharPred, Character>(99, 100, new CharPred((char)0x0063))); transitions1.add(new Internal<ICharPred, Character>(94, 98, new CharPred((char)0x0061))); transitions1.add(new Internal<ICharPred, Character>(103, 102, new CharPred((char)0x0065))); transitions1.add(new Internal<ICharPred, Character>(63, 69, new CharPred((char)0x0044))); transitions1.add(new Internal<ICharPred, Character>(105, 104, new CharPred((char)0x0067))); transitions1.add(new Internal<ICharPred, Character>(107, 106, new CharPred((char)0x0069))); transitions1.add(new Internal<ICharPred, Character>(104, 108, new CharPred((char)0x006B))); transitions1.add(new Internal<ICharPred, Character>(108, 109, new CharPred((char)0x006C))); transitions1.add(new Internal<ICharPred, Character>(109, 11, new CharPred((char)0x000A))); transitions1.add(new Internal<ICharPred, Character>(111, 110, new CharPred((char)0x006D))); transitions1.add(new Internal<ICharPred, Character>(110, 105, new CharPred((char)0x0068))); transitions1.add(new Internal<ICharPred, Character>(113, 112, new CharPred((char)0x006F))); transitions1.add(new Internal<ICharPred, Character>(114, 113, new CharPred((char)0x0070))); transitions1.add(new Internal<ICharPred, Character>(115, 114, new CharPred((char)0x0071))); transitions1.add(new Internal<ICharPred, Character>(78, 116, new CharPred((char)0x0073))); transitions1.add(new Internal<ICharPred, Character>(117, 1, new CharPred((char)0x0000))); transitions1.add(new Internal<ICharPred, Character>(118, 5, new CharPred((char)0x0004))); transitions1.add(new Internal<ICharPred, Character>(29, 115, new CharPred((char)0x0072))); transitions1.add(new Internal<ICharPred, Character>(13, 119, new CharPred((char)0x0076))); transitions1.add(new Internal<ICharPred, Character>(96, 98, new CharPred((char)0x0061))); transitions1.add(new Internal<ICharPred, Character>(19, 120, new CharPred((char)0x0077))); transitions1.add(new Internal<ICharPred, Character>(122, 121, new CharPred((char)0x0078))); transitions1.add(new Internal<ICharPred, Character>(121, 111, new CharPred((char)0x006E))); transitions1.add(new Internal<ICharPred, Character>(124, 123, new CharPred((char)0x007A))); transitions1.add(new Internal<ICharPred, Character>(123, 125, new CharPred((char)0x007C))); transitions1.add(new Internal<ICharPred, Character>(127, 126, new CharPred((char)0x007D))); transitions1.add(new Internal<ICharPred, Character>(126, 124, new CharPred((char)0x007B))); transitions1.add(new Internal<ICharPred, Character>(129, 128, new CharPred((char)0x007F))); transitions1.add(new Internal<ICharPred, Character>(128, 127, new CharPred((char)0x007E))); transitions1.add(new Internal<ICharPred, Character>(88, 130, new CharPred((char)0x0081))); transitions1.add(new Internal<ICharPred, Character>(130, 129, new CharPred((char)0x0080))); transitions1.add(new Internal<ICharPred, Character>(125, 131, new CharPred((char)0x0082))); transitions1.add(new Internal<ICharPred, Character>(131, 132, new CharPred((char)0x0083))); transitions1.add(new Internal<ICharPred, Character>(87, 117, new CharPred((char)0x0074))); transitions1.add(new Internal<ICharPred, Character>(134, 133, new CharPred((char)0x0084))); transitions1.add(new Internal<ICharPred, Character>(133, 107, new CharPred((char)0x006A))); transitions1.add(new Internal<ICharPred, Character>(136, 135, new CharPred((char)0x0086))); transitions1.add(new Internal<ICharPred, Character>(135, 137, new CharPred((char)0x0088))); transitions1.add(new Internal<ICharPred, Character>(2, 136, new CharPred((char)0x0087))); transitions1.add(new Internal<ICharPred, Character>(139, 138, new CharPred((char)0x0089))); transitions1.add(new Internal<ICharPred, Character>(138, 134, new CharPred((char)0x0085))); transitions1.add(new Internal<ICharPred, Character>(137, 140, new CharPred((char)0x008B))); transitions1.add(new Internal<ICharPred, Character>(140, 139, new CharPred((char)0x008A))); transitions1.add(new Internal<ICharPred, Character>(141, 122, new CharPred((char)0x0079))); transitions1.add(new Internal<ICharPred, Character>(142, 141, new CharPred((char)0x008C))); transitions1.add(new Internal<ICharPred, Character>(143, 142, new CharPred((char)0x008D))); transitions1.add(new Internal<ICharPred, Character>(144, 143, new CharPred((char)0x008E))); transitions1.add(new Internal<ICharPred, Character>(145, 144, new CharPred((char)0x008F))); transitions1.add(new Internal<ICharPred, Character>(146, 145, new CharPred((char)0x0090))); transitions1.add(new Internal<ICharPred, Character>(148, 147, new CharPred((char)0x0092))); transitions1.add(new Internal<ICharPred, Character>(132, 146, new CharPred((char)0x0091))); transitions1.add(new Internal<ICharPred, Character>(61, 103, new CharPred((char)0x0066))); transitions1.add(new Internal<ICharPred, Character>(61, 149, new CharPred((char)0x0094))); transitions1.add(new Internal<ICharPred, Character>(149, 102, new CharPred((char)0x0065))); transitions1.add(new Internal<ICharPred, Character>(150, 40, new CharPred((char)0x0027))); transitions1.add(new Internal<ICharPred, Character>(40, 56, new CharPred((char)0x0037))); transitions1.add(new Internal<ICharPred, Character>(26, 39, new CharPred((char)0x0026))); transitions1.add(new Internal<ICharPred, Character>(39, 150, new CharPred((char)0x0095))); transitions1.add(new Internal<ICharPred, Character>(39, 41, new CharPred((char)0x0028))); transitions1.add(new Internal<ICharPred, Character>(152, 151, new CharPred((char)0x0096))); transitions1.add(new Internal<ICharPred, Character>(153, 152, new CharPred((char)0x0097))); transitions1.add(new Internal<ICharPred, Character>(106, 153, new CharPred((char)0x0098))); transitions1.add(new Internal<ICharPred, Character>(155, 154, new CharPred((char)0x0099))); transitions1.add(new Internal<ICharPred, Character>(156, 155, new CharPred((char)0x009A))); transitions1.add(new Internal<ICharPred, Character>(157, 156, new CharPred((char)0x009B))); transitions1.add(new Internal<ICharPred, Character>(151, 157, new CharPred((char)0x009C))); transitions1.add(new Internal<ICharPred, Character>(158, 46, new CharPred((char)0x002D))); transitions1.add(new Internal<ICharPred, Character>(154, 158, new CharPred((char)0x009D))); transitions1.add(new Internal<ICharPred, Character>(160, 159, new CharPred((char)0x009E))); transitions1.add(new Internal<ICharPred, Character>(66, 161, new CharPred((char)0x00A0))); transitions1.add(new Internal<ICharPred, Character>(162, 71, new CharPred((char)0x0046))); transitions1.add(new Internal<ICharPred, Character>(159, 162, new CharPred((char)0x00A1))); transitions1.add(new Internal<ICharPred, Character>(161, 25, new CharPred((char)0x0018))); transitions1.add(new Internal<ICharPred, Character>(116, 160, new CharPred((char)0x009F))); transitions1.add(new Internal<ICharPred, Character>(102, 80, new CharPred((char)0x004F))); transitions1.add(new Internal<ICharPred, Character>(112, 118, new CharPred((char)0x0075))); transitions1.add(new Internal<ICharPred, Character>(163, 27, new CharPred((char)0x001A))); transitions1.add(new Internal<ICharPred, Character>(164, 163, new CharPred((char)0x00A2))); transitions1.add(new Internal<ICharPred, Character>(164, 38, new CharPred((char)0x0025))); transitions1.add(new Internal<ICharPred, Character>(165, 164, new CharPred((char)0x00A3))); transitions1.add(new Internal<ICharPred, Character>(147, 165, new CharPred((char)0x00A4))); transitions1.add(new Internal<ICharPred, Character>(166, 148, new CharPred((char)0x0093))); transitions1.add(new Internal<ICharPred, Character>(120, 166, new CharPred((char)0x00A5))); transitions1.add(new Internal<ICharPred, Character>(80, 62, new CharPred((char)0x003D))); transitions1.add(new Internal<ICharPred, Character>(80, 95, new CharPred((char)0x005E))); transitions1.add(new Internal<ICharPred, Character>(37, 35, new CharPred((char)0x0022))); transitions1.add(new Internal<ICharPred, Character>(42, 56, new CharPred((char)0x0037))); transitions1.add(new Internal<ICharPred, Character>(44, 42, new CharPred((char)0x0029))); // 2 goes here (it's still slow even without this one)... Collection<SVPAMove<ICharPred, Character>> transitions3 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions3.add(new Internal<ICharPred, Character>(0, 0, allCharsExcept((char)0x000F, false))); transitions3.add(new Call<ICharPred, Character>(0, 0, 0, allCharsExcept((char)0x000F, false))); transitions3.add(new Return<ICharPred, Character>(0, 0, 0, allCharsExcept((char)0x000F, true))); Collection<SVPAMove<ICharPred, Character>> transitions4 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions4.add(new Internal<ICharPred, Character>(0, 0, StdCharPred.TRUE)); transitions4.add(new Call<ICharPred, Character>(0, 0, 0, StdCharPred.TRUE)); transitions4.add(new Return<ICharPred, Character>(0, 0, 0, trueRetChar)); transitions4.add(new Internal<ICharPred, Character>(0, 1, new CharPred((char)0x0016))); transitions4.add(new Internal<ICharPred, Character>(1, 1, StdCharPred.TRUE)); transitions4.add(new Call<ICharPred, Character>(1, 1, 0, StdCharPred.TRUE)); transitions4.add(new Return<ICharPred, Character>(1, 1, 0, trueRetChar)); transitions4.add(new Internal<ICharPred, Character>(1, 2, new CharPred((char)0x0014))); transitions4.add(new Internal<ICharPred, Character>(2, 2, StdCharPred.TRUE)); transitions4.add(new Call<ICharPred, Character>(2, 2, 0, StdCharPred.TRUE)); transitions4.add(new Return<ICharPred, Character>(2, 2, 0, trueRetChar)); Collection<SVPAMove<ICharPred, Character>> transitions5 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions5.add(new Internal<ICharPred, Character>(0, 0, StdCharPred.TRUE)); transitions5.add(new Call<ICharPred, Character>(0, 0, 0, StdCharPred.TRUE)); transitions5.add(new Return<ICharPred, Character>(0, 0, 0, trueRetChar)); transitions5.add(new Internal<ICharPred, Character>(0, 1, new CharPred((char)0x0050))); transitions5.add(new Internal<ICharPred, Character>(1, 1, StdCharPred.TRUE)); transitions5.add(new Call<ICharPred, Character>(1, 1, 0, StdCharPred.TRUE)); transitions5.add(new Return<ICharPred, Character>(1, 1, 0, trueRetChar)); transitions5.add(new Internal<ICharPred, Character>(1, 2, new CharPred((char)0x0014))); transitions5.add(new Internal<ICharPred, Character>(2, 2, StdCharPred.TRUE)); transitions5.add(new Call<ICharPred, Character>(2, 2, 0, StdCharPred.TRUE)); transitions5.add(new Return<ICharPred, Character>(2, 2, 0, trueRetChar)); SVPA<ICharPred, Character> svpa1 = SVPA.MkSVPA(transitions1, Arrays.asList(0), Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166), ba); SVPA<ICharPred, Character> svpa3 = SVPA.MkSVPA(transitions3, Arrays.asList(0), Arrays.asList(0), ba); SVPA<ICharPred, Character> svpa4 = SVPA.MkSVPA(transitions4, Arrays.asList(0), Arrays.asList(2), ba); SVPA<ICharPred, Character> svpa5 = SVPA.MkSVPA(transitions5, Arrays.asList(0), Arrays.asList(2), ba); SVPA<ICharPred, Character> result = svpa1.intersectionWith(svpa3, ba); result = result.intersectionWith(svpa4, ba); result = result.intersectionWith(svpa5, ba); return result; } // Testing char SVPA importer @Test public void testSmallImport() throws TimeoutException{ EqualitySolver ba = new EqualitySolver(); SVPA<ICharPred, Character> cfgAutomaton = getCFGAutomata(ba); // TODO: how can we assert equality here? // For now: just make sure we don't get an exception try { ImportCharSVPA.importSVPA(cfgAutomaton.toString()); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } } @Test public void testLargeImport(){ try { SVPA<ICharPred, Character> bigAutomaton = getBigIntersection(); // TODO: how can we assert equality here? // For now: just make sure we don't get an exception ImportCharSVPA.importSVPA(bigAutomaton.toString()); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } } // slow intersection test (first_svpa_intersect is large) @Test public void testFileIntersectionImport(){ try { SVPA<ICharPred, Character> first = ImportCharSVPA.importSVPA(new File(getClass().getClassLoader().getResource("first_svpa_intersect").getFile())); SVPA<ICharPred, Character> second = ImportCharSVPA.importSVPA(new File(getClass().getClassLoader().getResource("second_svpa_intersect").getFile())); SVPA<ICharPred, Character> third = ImportCharSVPA.importSVPA(new File(getClass().getClassLoader().getResource("third_svpa_intersect").getFile())); EqualitySolver ba = new EqualitySolver(); SVPA<ICharPred, Character> result = first.intersectionWith(second, ba); result = result.intersectionWith(third, ba); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } } }
/* * $Log: IbisException.java,v $ * Revision 1.24 2008-08-12 15:13:48 europe\L190409 * removed duplicate parts in getMessage * * Revision 1.23 2008/03/28 14:50:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed position of XML location info * * Revision 1.22 2008/03/20 11:57:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * do not skip Exception from classname * * Revision 1.21 2007/07/17 15:08:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * tune SQL exception * * Revision 1.20 2007/07/17 10:46:01 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added SQLException specific fields * * Revision 1.19 2005/10/17 08:52:04 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * included location info for TransformerExceptions * * Revision 1.18 2005/08/08 09:40:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed dedicated toString() * * Revision 1.17 2005/07/28 07:28:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * reduced extensive toString, as it was too much, recursively * * Revision 1.16 2005/07/19 12:12:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved rendering of SaxParseException * * Revision 1.15 2005/07/05 11:01:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved rendering of errormessage * * Revision 1.14 2005/04/26 15:14:51 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved rendering of errormessage * * Revision 1.13 2005/02/10 08:14:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added exception type in message * * Revision 1.12 2004/07/20 13:56:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved message parsing * * Revision 1.11 2004/07/20 13:50:32 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved message parsing * * Revision 1.10 2004/07/08 08:55:58 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * cosmetic changes in toString() * * Revision 1.9 2004/07/07 14:30:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * toString(): classes, messages and root cause * * Revision 1.8 2004/07/07 13:55:06 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved toString() method, including fields of causes * * Revision 1.7 2004/07/06 06:57:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved workings of getMessage() * * Revision 1.6 2004/03/30 07:29:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.5 2004/03/26 10:42:50 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.4 2004/03/23 16:48:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modified getMessage() to avoid endless-loop * */ package nl.nn.adapterframework.core; import java.sql.SQLException; import javax.mail.internet.AddressException; import javax.xml.transform.SourceLocator; import javax.xml.transform.TransformerException; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang.exception.NestableException; import org.xml.sax.SAXParseException; /** * Base Exception with compact but informative getMessage(). * * @version Id * @author Gerrit van Brakel */ public class IbisException extends NestableException { // private Logger log = LogUtil.getLogger(this); static { // add methodname to find cause of JMS-Exceptions ExceptionUtils.addCauseMethodName("getLinkedException"); } public IbisException() { super(); } public IbisException(String message) { super(message); } public IbisException(String message, Throwable cause) { super(message, cause); } public IbisException(Throwable cause) { super(cause); } public String getExceptionType(Throwable t) { String name = t.getClass().getName(); int dotpos=name.lastIndexOf("."); name=name.substring(dotpos+1); return name; } public String addPart(String part1, String separator, String part2) { if (StringUtils.isEmpty(part1)) { return part2; } if (StringUtils.isEmpty(part2)) { return part1; } return part1+separator+part2; } public String getExceptionSpecificDetails(Throwable t) { String result=null; if (t instanceof AddressException) { AddressException ae = (AddressException)t; String parsedString=ae.getRef(); if (StringUtils.isNotEmpty(parsedString)) { result = addPart(result, " ", "["+parsedString+"]"); } int column = ae.getPos()+1; if (column>0) { result = addPart(result, " ", "at column ["+column+"]"); } } if (t instanceof SAXParseException) { SAXParseException spe = (SAXParseException)t; int line = spe.getLineNumber(); int col = spe.getColumnNumber(); String sysid = spe.getSystemId(); String locationInfo=null; if (StringUtils.isNotEmpty(sysid)) { locationInfo = "SystemId ["+sysid+"]"; } if (line>=0) { locationInfo = addPart(locationInfo, " ", "line ["+line+"]"); } if (col>=0) { locationInfo = addPart(locationInfo, " ", "column ["+col+"]"); } result = addPart(locationInfo, ": ", result); } if (t instanceof TransformerException) { TransformerException te = (TransformerException)t; SourceLocator locator = te.getLocator(); if (locator!=null) { int line = locator.getLineNumber(); int col = locator.getColumnNumber(); String sysid = locator.getSystemId(); String locationInfo=null; if (StringUtils.isNotEmpty(sysid)) { locationInfo = "SystemId ["+sysid+"]"; } if (line>=0) { locationInfo = addPart(locationInfo, " ", "line ["+line+"]"); } if (col>=0) { locationInfo = addPart(locationInfo, " ", "column ["+col+"]"); } result = addPart(locationInfo, ": ", result); } } if (t instanceof SQLException) { SQLException sqle = (SQLException)t; int errorCode = sqle.getErrorCode(); String sqlState = sqle.getSQLState(); if (errorCode!=0) { result = addPart("errorCode ["+errorCode+"]", ", ", result); } if (StringUtils.isNotEmpty(sqlState)) { result = addPart("SQLState ["+sqlState+"]", ", ", result); } } return result; } public String getMessage() { Throwable throwables[]=getThrowables(); String result=null; String prev_message=null; for(int i=getThrowableCount()-1; i>=0; i String cur_message=getMessage(i); // if (log.isDebugEnabled()) { // log.debug("t["+i+"], ["+ClassUtils.nameOf(throwables[i])+"], cur ["+cur_message+"], prev ["+prev_message+"]"); String newPart=null; // prefix the result with the message of this exception. // if the new message ends with the previous, remove the part that is already known if (StringUtils.isNotEmpty(cur_message)) { newPart = addPart(cur_message, " ", newPart); if (StringUtils.isNotEmpty(newPart) && StringUtils.isNotEmpty(prev_message) && newPart.endsWith(prev_message)) { newPart=newPart.substring(0,newPart.length()-prev_message.length()); } if (StringUtils.isNotEmpty(newPart) && newPart.endsWith(": ")) { newPart=newPart.substring(0,newPart.length()-2); } prev_message=cur_message; } String specificDetails = getExceptionSpecificDetails(throwables[i]); if (StringUtils.isNotEmpty(specificDetails) && (result==null || result.indexOf(specificDetails)<0)) { newPart= addPart(specificDetails,": ",newPart); } if (!(throwables[i] instanceof IbisException)) { String exceptionType = "("+getExceptionType(throwables[i])+")"; newPart = addPart(exceptionType, " ", newPart); } result = addPart(newPart, ": ", result); } if (result==null) { // log.debug("no message found, returning fields by inspection"); // do not replace the following with toString(), this causes an endless loop. GvB result="no message, fields of this exception: "+ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE); } return result; } /* public String toString() { String result = super.toString(); Throwable t = getCause(); if (t != null && !(t instanceof IbisException)) { t=ExceptionUtils.getRootCause(this); result += "\nroot cause:\n"+ToStringBuilder.reflectionToString(t,ToStringStyle.MULTI_LINE_STYLE)+"\n"; } return result; } */ }
package com.charlieroberts.Control; import android.os.Bundle; import com.phonegap.*; import android.view.WindowManager; public class Control extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setIntegerProperty("loadUrlTimeoutValue", 600000); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN ); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.loadUrl("file:///android_asset/www/index.html"); } }
package devopsdistilled.operp.client; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import devopsdistilled.operp.client.context.AppContext; import devopsdistilled.operp.client.main.MainWindow; public class ClientApp { public static void main(String[] args) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { System.err .println("Nimbus Look and Feel not available.\nReverting to default"); } ApplicationContext context = new AnnotationConfigApplicationContext( AppContext.class); MainWindow window = context.getBean(MainWindow.class); window.init(); System.out.println(context); } }
package net.sourceforge.texlipse.builder; import java.util.Stack; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.properties.TexlipseProperties; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; /** * Run the external latex program. * * @author Kimmo Karlsson * @author Oskar Ojala * @author Boris von Loesch */ public class LatexRunner extends AbstractProgramRunner { private Stack<String> parsingStack; /** * Create a new ProgramRunner. */ public LatexRunner() { super(); this.parsingStack = new Stack<String>(); } protected String getWindowsProgramName() { return "latex.exe"; } protected String getUnixProgramName() { return "latex"; } public String getDescription() { return "Latex program"; } public String getDefaultArguments() { return "-interaction=nonstopmode --src-specials %input"; } public String getInputFormat() { return TexlipseProperties.INPUT_FORMAT_TEX; } /** * Used by the DviBuilder to figure out what the latex program produces. * * @return output file format (dvi) */ public String getOutputFormat() { return TexlipseProperties.OUTPUT_FORMAT_DVI; } protected String[] getQueryString() { return new String[] { "\nPlease type another input file name:" , "\nEnter file name:" }; } /** * Adds a problem marker * * @param error The error or warning string * @param causingSourceFile name of the sourcefile * @param linenr where the error occurs * @param severity * @param resource * @param layout true, if this is a layout warning */ private void addProblemMarker(String error, String causingSourceFile, int linenr, int severity, IResource resource, boolean layout) { IProject project = resource.getProject(); IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project); IResource extResource = null; if (causingSourceFile != null) { extResource = sourceDir.findMember(causingSourceFile); if (extResource == null) { extResource = resource.getParent().findMember(causingSourceFile); } } if (extResource == null) createMarker(resource, null, error + (causingSourceFile != null ? " (Occurance: " + causingSourceFile + ")" : ""), severity); else { if (linenr >= 0) { if (layout) createLayoutMarker(extResource, new Integer(linenr), error); else createMarker(extResource, new Integer(linenr), error, severity); } else createMarker(extResource, null, error, severity); } } /** * Parse the output of the LaTeX program. * * @param resource the input file that was processed * @param output the output of the external program * @return true, if error messages were found in the output, false otherwise */ protected boolean parseErrors(IResource resource, String output) { TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, null); TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, null); parsingStack.clear(); boolean errorsFound = false; boolean citeNotfound = false; StringTokenizer st = new StringTokenizer(output, "\r\n"); final Pattern LATEXERROR = Pattern.compile("^! LaTeX Error: (.*)$"); final Pattern TEXERROR = Pattern.compile("^!\\s+(.*)$"); final Pattern FULLBOX = Pattern.compile("^(?:Over|Under)full \\\\[hv]box .* at lines? (\\d+)-?-?(\\d+)?"); final Pattern WARNING = Pattern.compile("^.+[Ww]arning.*: (.*)$"); final Pattern ATLINE = Pattern.compile("^l\\.(\\d+)(.*)$"); final Pattern ATLINE2 = Pattern.compile(".* line (\\d+).*"); final Pattern NOBIBFILE = Pattern.compile("^No file .+\\.bbl\\.$"); final Pattern NOTOCFILE = Pattern.compile("^No file .+\\.toc\\.$"); String line; boolean hasProblem = false; String error = null; int severity = IMarker.SEVERITY_WARNING; int linenr = -1; String occurance = null; while (st.hasMoreTokens()) { line = st.nextToken(); line = line.replaceAll(" {2,}", " ").trim(); Matcher m = TEXERROR.matcher(line); if (m.matches() && line.toLowerCase().indexOf("warning") == -1) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; } hasProblem = true; errorsFound = true; severity = IMarker.SEVERITY_ERROR; occurance = determineSourceFile(); Matcher m2 = LATEXERROR.matcher(line); if (m2.matches()) { // LaTex error error = m2.group(1); String part2 = st.nextToken().trim(); if (Character.isLowerCase(part2.charAt(0))) { error += ' ' + part2; } updateParsedFile(part2); continue; } if (line.startsWith("! Undefined control sequence.")){ // Undefined Control Sequence error = "Undefined control sequence: "; continue; } m2 = WARNING.matcher(line); if (m2.matches()) severity = IMarker.SEVERITY_WARNING; error = m.group(1); continue; } m = WARNING.matcher(line); if (m.matches()){ if (hasProblem){ // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } if (line.indexOf("Label(s) may have changed.") > -1) { // prepare to re-run latex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, "true"); continue; } else if (line.indexOf("There were undefined") > -1) { if (citeNotfound) { // prepare to run bibtex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); } continue; } // Ignore undefined references or citations because they are // found by the parser if (line.indexOf("Warning: Reference `") > -1) continue; if (line.indexOf("Warning: Citation `") > -1) { citeNotfound = true; continue; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); hasProblem = true; if (line.startsWith("LaTeX Warning: ") || line.indexOf("pdfTeX warning") != -1) { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } String nextLine = st.nextToken().replaceAll(" {2,}", " "); pM = ATLINE2.matcher(nextLine); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } updateParsedFile(nextLine); error += nextLine; if (linenr != -1) { addProblemMarker(line, occurance, linenr, severity, resource, false); hasProblem = false; linenr = -1; } continue; } else { error = m.group(1); //Try to get the line number Matcher pM = ATLINE2.matcher(line); if (pM.matches()) { linenr = Integer.parseInt(pM.group(1)); } continue; } } m = FULLBOX.matcher(line); if (m.matches()) { if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; } severity = IMarker.SEVERITY_WARNING; occurance = determineSourceFile(); error = line; linenr = Integer.parseInt(m.group(1)); addProblemMarker(line, occurance, linenr, severity, resource, true); hasProblem = false; linenr = -1; continue; } m = NOBIBFILE.matcher(line); if (m.matches()){ // prepare to run bibtex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_BIBTEX_RERUN, "true"); continue; } m = NOTOCFILE.matcher(line); if (m.matches()){ // prepare to re-run latex TexlipseProperties.setSessionProperty(resource.getProject(), TexlipseProperties.SESSION_LATEX_RERUN, "true"); continue; } m = ATLINE.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); String part2 = st.nextToken(); int index = line.indexOf(' '); if (index > -1) { error += " " + line.substring(index).trim() + " (followed by: " + part2.trim() + ")"; addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } } m = ATLINE2.matcher(line); if (hasProblem && m.matches()) { linenr = Integer.parseInt(m.group(1)); addProblemMarker(error, occurance, linenr, severity, resource, false); linenr = -1; hasProblem = false; continue; } updateParsedFile(line); } if (hasProblem) { // We have a not reported problem addProblemMarker(error, occurance, linenr, severity, resource, false); } return errorsFound; } /** * Updates the stack that determines which file we are currently * parsing, so that errors can be annotated in the correct file. * * @param logLine A line from latex' output containing which file we are in */ private void updateParsedFile(String logLine) { if (logLine.indexOf('(') == -1 && logLine.indexOf(')') == -1) return; for (int i = 0; i < logLine.length(); i++) { if (logLine.charAt(i) == '(') { int j; for (j = i + 1; j < logLine.length() && isAllowedinName(logLine.charAt(j)); j++) ; parsingStack.push(logLine.substring(i, j).trim()); i = j - 1; } else if (logLine.charAt(i) == ')' && !parsingStack.isEmpty()) { parsingStack.pop(); } else if (logLine.charAt(i) == ')') { // There was a parsing error, this is very rare TexlipsePlugin.log("Error while parsing the LaTeX output. " + "Please consult the console output", null); } } } private boolean isAllowedinName(char c) { if (c == '(' || c == ')' || c == '[') return false; else return true; } private static boolean isValidName(String name) { //File must have a file ending int p = name.lastIndexOf('.'); if (p < 0) return false; //File ending must be shorter than 9 characters if (name.length()-p > 10) return false; return true; } /** * Determines the source file we are currently parsing. * * @return The filename or null if no file could be determined */ private String determineSourceFile() { int i = parsingStack.size()-1; while (i >= 0) { String fileName = parsingStack.get(i).substring(1); //Remove " if (fileName.startsWith("\"") && fileName.endsWith("\"")) { fileName = fileName.substring(1, fileName.length() - 1); } if (isValidName(fileName)) return fileName; i } return null; } }
package central; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import com.opencsv.CSVReader; import util.RunStrategy; public class Main { // choice of data structure might be crucial static List<Point> points = new LinkedList<Point>(); // number of data points static int n = 10000; static int k = 10; static int iterations = 100; // default static String filePath = "points.csv"; public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException, ExecutionException { if (args.length > 0) { if (args.length > 1) { System.err.println("Too many arguments"); } else { filePath = args[0]; } } final KMeans kmeans = new KMeans(); // parsing a a data set or creating random points is possible points = parseCSVFile(); // points = createRandomPoints(n); // make list of points immutable points = Collections.unmodifiableList(points); // very simple form of time measurement (doesn't measure initialization // phase, as well) // beware of JVM cashing, garbage collection // sequential // benchmarkXRuns(1, RunStrategy.SEQUENTIAL); // parallel // benchmarkXRuns(1, RunStrategy.PARALLEL); // reducemap System.out.println("Running the reducemap algorithm.."); System.out.println(" "); KMeans.run(points, k, 10, RunStrategy.REDUCEMAP); } private static void benchmarkXRuns(int runs, RunStrategy runStrategy) throws InterruptedException, ExecutionException { System.out.println("Running the " + runStrategy.toString().toLowerCase() + " algorithm " + runs + " times.."); System.out.println(" "); long start = System.currentTimeMillis(); for (int i = 0; i < runs; i++) { KMeans.run(points, k, iterations, runStrategy); // hint garbage collector to do a collection // TODO: do this correctly System.gc(); } long time = System.currentTimeMillis() - start; System.out.println("The " + runStrategy.toString().toLowerCase() + " algorithm ran " + time / 5 + " milliseconds on average"); System.out.println(" "); } /** * reads csv file with data points and returns a list of these points * * @throws NumberFormatException * @throws IOException */ public static List<Point> parseCSVFile() throws NumberFormatException, IOException { // TODO: create list type interface // TODO: adapt for arbitrary number of variables // create CSVReader object CSVReader reader = new CSVReader(new FileReader(filePath), ','); List<Point> readPoints = new ArrayList<Point>(); // read line by line String[] record = null; // skip header row reader.readNext(); while ((record = reader.readNext()) != null) { Point readPoint = new Point(Double.parseDouble(record[0]), Double.parseDouble(record[1])); // System.out.println("Adding Point " readPoint.toString()); readPoints.add(readPoint); // or: addPoint(Set<Point> list, Point) as interface method } reader.close(); return readPoints; } /** * Generates random data points and fills list with them * * @param n * amount of points to be generated */ public static List<Point> createRandomPoints(int n) { Random r = new Random(); List<Point> points = new ArrayList<Point>(); for (int i = 0; i < n; i++) { points.add(new Point(r.nextDouble(), r.nextDouble())); } // printPoints(); return points; } private static void printPoints() { for (Point p : points) { System.out.println(p.toString()); } } }
package hangman; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; import java.util.ArrayList; import java.util.List; /* Hangman is a Java implementation of the classic paper and pencil guessing game. */ public class Game { public static void main(String[] args) throws FileNotFoundException { Scanner game_state = new Scanner(new FileReader("src/main/resources/game_state.txt")); game_state.useDelimiter("\\s*;\\s*"); Scanner in = new Scanner(new FileReader("src/main/resources/words.txt")); List<String> words = new ArrayList<String>(); while (in.hasNextLine()) { words.add(in.nextLine()); } in.close(); // String[] wordsArray = words.toArray(new String[words.size()]); // System.out.println(Arrays.toString(wordsArray)); System.out.println("-=+ W E L C O M E T O H A N G M A N +=-"); printGameStateString(game_state); /* * Game code here * */ game_state.close(); } //Each time it's called it will print next set of characters surrounded by ; and ; in file game_state.txt private static void printGameStateString(Scanner state) throws FileNotFoundException{ if( state.hasNext() ){ System.out.println(state.next()); }else System.out.println("Game has already ended!"); } }
package org.jasig.portal.groups; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.jasig.portal.EntityTypes; import org.jasig.portal.RDBMServices; import org.jasig.portal.services.LogService; import org.jasig.portal.services.SequenceGenerator; import org.jasig.portal.utils.SqlTransaction; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.services.GroupService; /** * Store for <code>EntityGroupImpl</code>. * @author Dan Ellentuck * @version $Revision$ */ public class RDBMEntityGroupStore implements IEntityGroupStore, IGroupConstants { private static RDBMEntityGroupStore singleton; // Constant strings for GROUP table: private static String GROUP_TABLE = "UP_GROUP"; private static String GROUP_TABLE_ALIAS = "T1"; private static String GROUP_ID_COLUMN = "GROUP_ID"; private static String GROUP_CREATOR_COLUMN = "CREATOR_ID"; private static String GROUP_TYPE_COLUMN = "ENTITY_TYPE_ID"; private static String GROUP_NAME_COLUMN = "GROUP_NAME"; private static String GROUP_DESCRIPTION_COLUMN = "DESCRIPTION"; // SQL strings for GROUP crud: private static String allGroupColumns; private static String allGroupColumnsWithTableAlias; private static String findContainingGroupsForEntitySql; private static String findContainingGroupsForGroupSql; private static String findGroupSql; private static String findGroupsByCreatorSql; private static String findMemberGroupKeysSql; private static String findMemberGroupSql; private static String findMemberGroupsSql; private static String insertGroupSql; private static String updateGroupSql; // Constant strings for MEMBERS table: private static String MEMBER_TABLE = "UP_GROUP_MEMBERSHIP"; private static String MEMBER_TABLE_ALIAS = "T2"; private static String MEMBER_GROUP_ID_COLUMN = "GROUP_ID"; private static String MEMBER_MEMBER_SERVICE_COLUMN = "MEMBER_SERVICE"; private static String MEMBER_MEMBER_KEY_COLUMN = "MEMBER_KEY"; private static String MEMBER_IS_GROUP_COLUMN = "MEMBER_IS_GROUP"; private static String MEMBER_IS_ENTITY = "F"; private static String MEMBER_IS_GROUP = "T"; // SQL strings for group MEMBERS crud: private static String allMemberColumns; private static String deleteMembersInGroupSql; private static String deleteMemberGroupSql; private static String deleteMemberEntitySql; private static String insertMemberSql; // SQL group search string private static String searchGroupsPartial = "SELECT "+GROUP_ID_COLUMN+" FROM "+GROUP_TABLE+" WHERE "+GROUP_TYPE_COLUMN+"=? AND "+GROUP_NAME_COLUMN+" LIKE ?"; private static String searchGroups = "SELECT "+GROUP_ID_COLUMN+" FROM "+GROUP_TABLE+" WHERE "+GROUP_TYPE_COLUMN+"=? AND "+GROUP_NAME_COLUMN+" = ?"; private IGroupService groupService; /** * RDBMEntityGroupStore constructor. */ public RDBMEntityGroupStore() { super(); } /** * @param conn java.sql.Connection * @exception java.sql.SQLException */ protected static void commit(Connection conn) throws java.sql.SQLException { SqlTransaction.commit(conn); } /** * If this entity exists, delete it. * @param group org.jasig.portal.groups.IEntityGroup */ public void delete(IEntityGroup group) throws GroupsException { if ( existsInDatabase(group) ) { try { primDelete(group); } catch (SQLException sqle) { throw new GroupsException("Problem deleting " + group + ": " + sqle.getMessage()); } } } /** * Answer if the IEntityGroup entity exists in the database. * @return boolean * @param group IEntityGroup */ private boolean existsInDatabase(IEntityGroup group) throws GroupsException { IEntityGroup ug = this.find(group.getLocalKey()); return ug != null; } /** * Find and return an instance of the group. * @return org.jasig.portal.groups.IEntityGroup * @param key java.lang.Object */ public IEntityGroup find(String groupID) throws GroupsException { return primFind(groupID, false); } /** * Find the groups that this entity belongs to. * @return java.util.Iterator * @param group org.jasig.portal.groups.IEntity */ public java.util.Iterator findContainingGroups(IEntity ent) throws GroupsException { String memberKey = ent.getKey(); Integer type = EntityTypes.getEntityTypeID(ent.getLeafType()); return findContainingGroupsForEntity(memberKey, type.intValue(), false); } /** * Find the groups that this group belongs to. * @return java.util.Iterator * @param group org.jasig.portal.groups.IEntityGroup */ public java.util.Iterator findContainingGroups(IEntityGroup group) throws GroupsException { String memberKey = group.getLocalKey(); String serviceName = group.getServiceName().toString(); Integer type = EntityTypes.getEntityTypeID(group.getLeafType()); return findContainingGroupsForGroup(serviceName, memberKey, type.intValue(), true); } /** * Find the groups that this group member belongs to. * @return java.util.Iterator * @param group org.jasig.portal.groups.IGroupMember */ public Iterator findContainingGroups(IGroupMember gm) throws GroupsException { if ( gm.isGroup() ) { IEntityGroup group = (IEntityGroup) gm; return findContainingGroups(group); } else { IEntity ent = (IEntity) gm; return findContainingGroups(ent); } } /** * Find the groups associated with this member key. * @return java.util.Iterator * @param String memberKey */ private java.util.Iterator findContainingGroupsForEntity(String memberKey, int type, boolean isGroup) throws GroupsException { java.sql.Connection conn = null; Collection groups = new ArrayList(); IEntityGroup eg = null; String groupOrEntity = isGroup ? MEMBER_IS_GROUP : MEMBER_IS_ENTITY; try { conn = RDBMServices.getConnection(); String sql = getFindContainingGroupsForEntitySql(); RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, sql); try { ps.setString(1, memberKey); ps.setInt(2, type); ps.setString(3, groupOrEntity); LogService.log (LogService.DEBUG, "RDBMEntityGroupStore.findContainingGroupsForEntity(): " + ps + " (" + memberKey + ", " + type + ", " + groupOrEntity + ")"); java.sql.ResultSet rs = ps.executeQuery(); try { while (rs.next()) { eg = instanceFromResultSet(rs); groups.add(eg); } } finally { rs.close(); } } finally { ps.close(); } } catch (Exception e) { LogService.log (LogService.ERROR, "RDBMEntityGroupStore.findContainingGroupsForEntity(): " + e); throw new GroupsException("Problem retrieving containing groups: " + e); } finally { RDBMServices.releaseConnection(conn); } return groups.iterator(); } /** * Find the groups associated with this member key. * @return java.util.Iterator * @param String memberKey */ private java.util.Iterator findContainingGroupsForGroup(String serviceName, String memberKey, int type, boolean isGroup) throws GroupsException { java.sql.Connection conn = null; Collection groups = new ArrayList(); IEntityGroup eg = null; String groupOrEntity = isGroup ? MEMBER_IS_GROUP : MEMBER_IS_ENTITY; try { conn = RDBMServices.getConnection(); String sql = getFindContainingGroupsForGroupSql(); RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, sql); try { ps.setString(1, serviceName); ps.setString(2, memberKey); ps.setInt(3, type); ps.setString(4, groupOrEntity); LogService.log (LogService.DEBUG, "RDBMEntityGroupStore.findContainingGroupsForGroup(): " + ps + " (" + memberKey + ", " + type + ", " + groupOrEntity + ")"); java.sql.ResultSet rs = ps.executeQuery(); try { while (rs.next()) { eg = instanceFromResultSet(rs); groups.add(eg); } } finally { rs.close(); } } finally { ps.close(); } } catch (Exception e) { LogService.log (LogService.ERROR, "RDBMEntityGroupStore.findContainingGroupsForGroup(): " + e); throw new GroupsException("Problem retrieving containing groups: " + e); } finally { RDBMServices.releaseConnection(conn); } return groups.iterator(); } /** * Find the <code>IEntities</code> that are members of the <code>IEntityGroup</code>. * @return java.util.Iterator * @param group org.jasig.portal.groups.IEntityGroup */ public Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException { Collection entities = new ArrayList(); Connection conn = null; String groupID = group.getLocalKey(); Class cls = group.getLeafType(); try { conn = RDBMServices.getConnection(); Statement stmnt = conn.createStatement(); try { String query = "SELECT " + MEMBER_MEMBER_KEY_COLUMN + " FROM " + MEMBER_TABLE + " WHERE " + MEMBER_GROUP_ID_COLUMN + " = '" + groupID + "' AND " + MEMBER_IS_GROUP_COLUMN + " = '" + MEMBER_IS_ENTITY + "'"; ResultSet rs = stmnt.executeQuery(query); try { while (rs.next()) { String key = rs.getString(1); IEntity e = newEntity(cls, key); entities.add(e); } } finally { rs.close(); } } finally { stmnt.close(); } } catch (SQLException sqle) { LogService.log(LogService.ERROR, sqle); throw new GroupsException("Problem retrieving Entities for Group: " + sqle.getMessage()); } finally { RDBMServices.releaseConnection(conn); } return entities.iterator(); } /** * Find the groups with this creatorID. * @return java.util.Iterator * @param String creatorID */ public java.util.Iterator findGroupsByCreator(String creatorID) throws GroupsException { java.sql.Connection conn = null; Collection groups = new ArrayList(); IEntityGroup eg = null; try { conn = RDBMServices.getConnection(); String sql = getFindGroupsByCreatorSql(); RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, sql); try { ps.setString(1, creatorID); LogService.log (LogService.DEBUG, "RDBMEntityGroupStore.findGroupsByCreator(): " + ps); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { eg = instanceFromResultSet(rs); groups.add(eg); } } finally { rs.close(); } } finally { ps.close(); } } catch (Exception e) { LogService.log (LogService.ERROR, "RDBMEntityGroupStore.findGroupsByCreator(): " + e); throw new GroupsException("Problem retrieving groups: " + e); } finally { RDBMServices.releaseConnection(conn); } return groups.iterator(); } /** * Find and return an instance of the group. * @return org.jasig.portal.groups.ILockableEntityGroup * @param key java.lang.Object */ public ILockableEntityGroup findLockable(String groupID) throws GroupsException { return (ILockableEntityGroup) primFind(groupID, true); } /** * Find the keys of groups that are members of group. * @return String[] * @param group org.jasig.portal.groups.IEntityGroup */ public String[] findMemberGroupKeys(IEntityGroup group) throws GroupsException { java.sql.Connection conn = null; Collection groupKeys = new ArrayList(); String groupKey = null; try { conn = RDBMServices.getConnection(); String sql = getFindMemberGroupKeysSql(); RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, sql); try { ps.setString(1, group.getLocalKey()); LogService.log (LogService.DEBUG, "RDBMEntityGroupStore.findMemberGroupKeys(): " + ps + " (" + group.getLocalKey() + ")"); java.sql.ResultSet rs = ps.executeQuery(); try { while (rs.next()) { groupKey = rs.getString(1) + NODE_SEPARATOR + rs.getString(2); groupKeys.add(groupKey); } } finally { rs.close(); } } finally { ps.close(); } } catch (Exception sqle) { LogService.log (LogService.ERROR, "RDBMEntityGroupStore.findMemberGroupKeys(): " + sqle); throw new GroupsException("Problem retrieving member group keys: " + sqle); } finally { RDBMServices.releaseConnection(conn); } return (String[]) groupKeys.toArray(new String[groupKeys.size()]); } /** * Find the IUserGroups that are members of the group. * @return java.util.Iterator * @param group org.jasig.portal.groups.IEntityGroup */ public Iterator findMemberGroups(IEntityGroup group) throws GroupsException { java.sql.Connection conn = null; Collection groups = new ArrayList(); IEntityGroup eg = null; String serviceName = group.getServiceName().toString(); String localKey = group.getLocalKey(); try { conn = RDBMServices.getConnection(); String sql = getFindMemberGroupsSql(); RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, sql); try { ps.setString(1, localKey); ps.setString(2, serviceName); LogService.log (LogService.DEBUG, "RDBMEntityGroupStore.findMemberGroups(): " + ps + " (" + localKey + ", " + serviceName + ")"); java.sql.ResultSet rs = ps.executeQuery(); try { while (rs.next()) { eg = instanceFromResultSet(rs); groups.add(eg); } } finally { rs.close(); } } finally { ps.close(); } } catch (Exception sqle) { LogService.log (LogService.ERROR, "RDBMEntityGroupStore.findMemberGroups(): " + sqle); throw new GroupsException("Problem retrieving member groups: " + sqle); } finally { RDBMServices.releaseConnection(conn); } return groups.iterator(); } /** * @return java.lang.String */ private static java.lang.String getAllGroupColumns() { if ( allGroupColumns == null ) { StringBuffer buff = new StringBuffer(100); buff.append(GROUP_ID_COLUMN); buff.append(", "); buff.append(GROUP_CREATOR_COLUMN); buff.append(", "); buff.append(GROUP_TYPE_COLUMN); buff.append(", "); buff.append(GROUP_NAME_COLUMN); buff.append(", "); buff.append(GROUP_DESCRIPTION_COLUMN); allGroupColumns = buff.toString(); } return allGroupColumns; } /** * @return java.lang.String */ private static java.lang.String getAllGroupColumnsWithTableAlias() { if ( allGroupColumnsWithTableAlias == null ) { StringBuffer buff = new StringBuffer(100); buff.append(prependGroupTableAlias(GROUP_ID_COLUMN)); buff.append(", "); buff.append(prependGroupTableAlias(GROUP_CREATOR_COLUMN)); buff.append(", "); buff.append(prependGroupTableAlias(GROUP_TYPE_COLUMN)); buff.append(", "); buff.append(prependGroupTableAlias(GROUP_NAME_COLUMN)); buff.append(", "); buff.append(prependGroupTableAlias(GROUP_DESCRIPTION_COLUMN)); allGroupColumnsWithTableAlias = buff.toString(); } return allGroupColumnsWithTableAlias; } /** * @return java.lang.String */ private static java.lang.String getAllMemberColumns() { if ( allMemberColumns == null ) { StringBuffer buff = new StringBuffer(100); buff.append(MEMBER_GROUP_ID_COLUMN); buff.append(", "); buff.append(MEMBER_MEMBER_SERVICE_COLUMN); buff.append(", "); buff.append(MEMBER_MEMBER_KEY_COLUMN); buff.append(", "); buff.append(MEMBER_IS_GROUP_COLUMN); allMemberColumns = buff.toString(); } return allMemberColumns; } /** * @return java.lang.String */ private static java.lang.String getDeleteGroupSql(IEntityGroup group) { StringBuffer buff = new StringBuffer(100); buff.append("DELETE FROM "); buff.append(GROUP_TABLE); buff.append(" WHERE "); buff.append(GROUP_ID_COLUMN); buff.append(" = '"); buff.append(group.getLocalKey()); buff.append("'"); return buff.toString(); } /** * @return java.lang.String */ private static java.lang.String getDeleteMemberEntitySql() { if ( deleteMemberEntitySql == null ) { StringBuffer buff = new StringBuffer(100); buff.append("DELETE FROM "); buff.append(MEMBER_TABLE); buff.append(" WHERE "); buff.append(MEMBER_GROUP_ID_COLUMN); buff.append(" = ? AND "); buff.append(MEMBER_MEMBER_KEY_COLUMN); buff.append(" = ? AND "); buff.append(MEMBER_IS_GROUP_COLUMN); buff.append(" = ? "); deleteMemberEntitySql = buff.toString(); } return deleteMemberEntitySql; } /** * @return java.lang.String */ private static java.lang.String getDeleteMemberGroupSql() { if ( deleteMemberGroupSql == null ) { StringBuffer buff = new StringBuffer(100); buff.append("DELETE FROM "); buff.append(MEMBER_TABLE); buff.append(" WHERE "); buff.append(MEMBER_GROUP_ID_COLUMN); buff.append(" = ? AND "); buff.append(MEMBER_MEMBER_SERVICE_COLUMN); buff.append(" = ? AND "); buff.append(MEMBER_MEMBER_KEY_COLUMN); buff.append(" = ? AND "); buff.append(MEMBER_IS_GROUP_COLUMN); buff.append(" = ? "); deleteMemberGroupSql = buff.toString(); } return deleteMemberGroupSql; } /** * @return java.lang.String */ private static java.lang.String getDeleteMembersInGroupSql() { if ( deleteMembersInGroupSql == null ) { StringBuffer buff = new StringBuffer(100); buff.append("DELETE FROM "); buff.append(MEMBER_TABLE); buff.append(" WHERE "); buff.append(GROUP_ID_COLUMN); buff.append(" = "); deleteMembersInGroupSql = buff.toString(); } return deleteMembersInGroupSql; } /** * @return java.lang.String */ private static java.lang.String getDeleteMembersInGroupSql(IEntityGroup group) { StringBuffer buff = new StringBuffer(getDeleteMembersInGroupSql()); buff.append("'"); buff.append(group.getLocalKey()); buff.append("'"); return buff.toString(); } /** * @return java.lang.String */ private static java.lang.String getFindContainingGroupsForEntitySql() { if ( findContainingGroupsForEntitySql == null) { StringBuffer buff = new StringBuffer(500); buff.append("SELECT "); buff.append(getAllGroupColumnsWithTableAlias()); buff.append(" FROM "); buff.append(GROUP_TABLE + " " + GROUP_TABLE_ALIAS); buff.append(", "); buff.append(MEMBER_TABLE + " " + MEMBER_TABLE_ALIAS); buff.append(" WHERE "); buff.append(prependGroupTableAlias(GROUP_ID_COLUMN)); buff.append(" = "); buff.append(prependMemberTableAlias(MEMBER_GROUP_ID_COLUMN)); buff.append(" AND "); buff.append(prependMemberTableAlias(MEMBER_MEMBER_KEY_COLUMN)); buff.append(" = ? AND "); buff.append(prependGroupTableAlias(GROUP_TYPE_COLUMN)); buff.append(" = ? AND "); buff.append(prependMemberTableAlias(MEMBER_IS_GROUP_COLUMN)); buff.append(" = ? "); findContainingGroupsForEntitySql = buff.toString(); } return findContainingGroupsForEntitySql; } /** * @return java.lang.String */ private static java.lang.String getFindContainingGroupsForGroupSql() { if ( findContainingGroupsForGroupSql == null) { StringBuffer buff = new StringBuffer(500); buff.append("SELECT "); buff.append(getAllGroupColumnsWithTableAlias()); buff.append(" FROM "); buff.append(GROUP_TABLE + " " + GROUP_TABLE_ALIAS); buff.append(", "); buff.append(MEMBER_TABLE + " " + MEMBER_TABLE_ALIAS); buff.append(" WHERE "); buff.append(prependGroupTableAlias(GROUP_ID_COLUMN)); buff.append(" = "); buff.append(prependMemberTableAlias(MEMBER_GROUP_ID_COLUMN)); buff.append(" AND "); buff.append(prependMemberTableAlias(MEMBER_MEMBER_SERVICE_COLUMN)); buff.append(" = ? AND "); buff.append(prependMemberTableAlias(MEMBER_MEMBER_KEY_COLUMN)); buff.append(" = ? AND "); buff.append(prependGroupTableAlias(GROUP_TYPE_COLUMN)); buff.append(" = ? AND "); buff.append(prependMemberTableAlias(MEMBER_IS_GROUP_COLUMN)); buff.append(" = ? "); findContainingGroupsForGroupSql = buff.toString(); } return findContainingGroupsForGroupSql; } /** * @return java.lang.String */ private static java.lang.String getFindGroupsByCreatorSql() { if ( findGroupsByCreatorSql == null ) { StringBuffer buff = new StringBuffer(200); buff.append("SELECT "); buff.append(getAllGroupColumns()); buff.append(" FROM "); buff.append(GROUP_TABLE); buff.append(" WHERE "); buff.append(GROUP_CREATOR_COLUMN); buff.append(" = ? "); findGroupsByCreatorSql = buff.toString(); } return findGroupsByCreatorSql; } /** * @return java.lang.String */ private static java.lang.String getFindGroupSql() { if ( findGroupSql == null ) { StringBuffer buff = new StringBuffer(200); buff.append("SELECT "); buff.append(getAllGroupColumns()); buff.append(" FROM "); buff.append(GROUP_TABLE); buff.append(" WHERE "); buff.append(GROUP_ID_COLUMN); buff.append(" = ? "); findGroupSql = buff.toString(); } return findGroupSql; } /** * @return java.lang.String */ private static java.lang.String getFindMemberGroupKeysSql() { if (findMemberGroupKeysSql == null) { StringBuffer buff = new StringBuffer(200); buff.append("SELECT "); buff.append(MEMBER_MEMBER_SERVICE_COLUMN + ", " + MEMBER_MEMBER_KEY_COLUMN); buff.append(" FROM "); buff.append(MEMBER_TABLE); buff.append(" WHERE "); buff.append(MEMBER_GROUP_ID_COLUMN); buff.append(" = ? AND "); buff.append(MEMBER_IS_GROUP_COLUMN); buff.append(" = '"); buff.append(MEMBER_IS_GROUP); buff.append("'");; findMemberGroupKeysSql = buff.toString(); } return findMemberGroupKeysSql; } /** * @return java.lang.String */ private static java.lang.String getFindMemberGroupSql() { if ( findMemberGroupSql == null ) { StringBuffer buff = new StringBuffer(getFindMemberGroupsSql()); buff.append("AND "); buff.append(GROUP_TABLE_ALIAS); buff.append("."); buff.append(GROUP_NAME_COLUMN); buff.append(" = ?"); findMemberGroupSql = buff.toString(); } return findMemberGroupSql; } /** * @return java.lang.String */ private static java.lang.String getFindMemberGroupsSql() { if (findMemberGroupsSql == null) { StringBuffer buff = new StringBuffer(500); buff.append("SELECT "); buff.append(getAllGroupColumnsWithTableAlias()); buff.append(" FROM "); buff.append(GROUP_TABLE + " " + GROUP_TABLE_ALIAS); buff.append(", "); buff.append(MEMBER_TABLE + " " + MEMBER_TABLE_ALIAS); buff.append(" WHERE "); buff.append(prependGroupTableAlias(GROUP_ID_COLUMN)); buff.append(" = "); buff.append(prependMemberTableAlias(MEMBER_MEMBER_KEY_COLUMN)); buff.append(" AND "); buff.append(prependMemberTableAlias(MEMBER_IS_GROUP_COLUMN)); buff.append(" = '"); buff.append(MEMBER_IS_GROUP); buff.append("' AND "); buff.append(prependMemberTableAlias(MEMBER_GROUP_ID_COLUMN)); buff.append(" = ? "); buff.append(" AND "); buff.append(prependMemberTableAlias(MEMBER_MEMBER_SERVICE_COLUMN)); buff.append(" = ? "); findMemberGroupsSql = buff.toString(); } return findMemberGroupsSql; } /** * @return org.jasig.portal.groups.IGroupService */ public IGroupService getGroupService() { return groupService; } /** * @return java.lang.String */ private static java.lang.String getInsertGroupSql() { if ( insertGroupSql == null ) { StringBuffer buff = new StringBuffer(200); buff.append("INSERT INTO "); buff.append(GROUP_TABLE); buff.append(" ("); buff.append(getAllGroupColumns()); buff.append(") VALUES (?, ?, ?, ?, ?)"); insertGroupSql = buff.toString(); } return insertGroupSql; } /** * @return java.lang.String */ private static java.lang.String getInsertMemberSql() { if ( insertMemberSql == null ) { StringBuffer buff = new StringBuffer(200); buff.append("INSERT INTO "); buff.append(MEMBER_TABLE); buff.append(" ("); buff.append(getAllMemberColumns()); buff.append(") VALUES (?, ?, ?, ? )"); insertMemberSql = buff.toString(); } return insertMemberSql; } /** * @return java.lang.String * @exception java.lang.Exception */ private String getNextKey() throws java.lang.Exception { return SequenceGenerator.instance().getNext(GROUP_TABLE); } /** * @return java.lang.String */ private static java.lang.String getUpdateGroupSql() { if ( updateGroupSql == null ) { StringBuffer buff = new StringBuffer(200); buff.append("UPDATE "); buff.append(GROUP_TABLE); buff.append(" SET "); buff.append(GROUP_CREATOR_COLUMN); buff.append(" = ?, "); buff.append(GROUP_TYPE_COLUMN); buff.append(" = ?, "); buff.append(GROUP_NAME_COLUMN); buff.append(" = ?, "); buff.append(GROUP_DESCRIPTION_COLUMN); buff.append(" = ? WHERE "); buff.append(GROUP_ID_COLUMN); buff.append(" = ? "); updateGroupSql = buff.toString(); } return updateGroupSql; } /** * Find and return an instance of the group. * @return org.jasig.portal.groups.IEntityGroup * @param key java.lang.Object */ private IEntityGroup instanceFromResultSet(java.sql.ResultSet rs) throws SQLException, GroupsException { IEntityGroup eg = null; String key = rs.getString(1); String creatorID = rs.getString(2); Integer entityTypeID = new Integer(rs.getInt(3)); Class entityType = EntityTypes.getEntityType(entityTypeID); String groupName = rs.getString(4); String description = rs.getString(5); if ( key != null ) { eg = newInstance(key, entityType, creatorID, groupName, description); } return eg; } /** * Find and return an instance of the group. * @return org.jasig.portal.groups.ILockableEntityGroup * @param key java.lang.Object */ private ILockableEntityGroup lockableInstanceFromResultSet(java.sql.ResultSet rs) throws SQLException, GroupsException { ILockableEntityGroup eg = null; String key = rs.getString(1); String creatorID = rs.getString(2); Integer entityTypeID = new Integer(rs.getInt(3)); Class entityType = EntityTypes.getEntityType(entityTypeID); String groupName = rs.getString(4); String description = rs.getString(5); if ( key != null ) { eg = newLockableInstance(key, entityType, creatorID, groupName, description); } return eg; } protected static void logNoTransactionWarning() { String msg = "You are running the portal on a database that does not support transactions. " + "This is not a supported production environment for uPortal. " + "Sooner or later, your database will become corrupt."; LogService.instance().log(LogService.WARN, msg); } /** * @return org.jasig.portal.groups.IEntity */ public IEntity newEntity(Class type, String key) throws GroupsException { if ( EntityTypes.getEntityTypeID(type) == null ) { throw new GroupsException("Invalid group type: " + type); } return GroupService.getEntity(key, type); } /** * @return org.jasig.portal.groups.IEntityGroup */ public IEntityGroup newInstance(Class type) throws GroupsException { if ( EntityTypes.getEntityTypeID(type) == null ) { throw new GroupsException("Invalid group type: " + type); } try { return new EntityGroupImpl(getNextKey(), type); } catch ( Exception ex ) { throw new GroupsException("Could not create new group: " + ex.getMessage()); } } /** * @return org.jasig.portal.groups.IEntityGroup */ private IEntityGroup newInstance (String newKey, Class newType, String newCreatorID, String newName, String newDescription) throws GroupsException { EntityGroupImpl egi = new EntityGroupImpl(newKey, newType); egi.setCreatorID(newCreatorID); egi.primSetName(newName); egi.setDescription(newDescription); return egi; } /** * @return org.jasig.portal.groups.ILockableEntityGroup */ private ILockableEntityGroup newLockableInstance (String newKey, Class newType, String newCreatorID, String newName, String newDescription) throws GroupsException { LockableEntityGroupImpl group = new LockableEntityGroupImpl(newKey, newType); group.setCreatorID(newCreatorID); group.primSetName(newName); group.setDescription(newDescription); return group; } /** * @return java.lang.String */ private static java.lang.String prependGroupTableAlias(String column) { return GROUP_TABLE_ALIAS + "." + column; } /** * @return java.lang.String */ private static java.lang.String prependMemberTableAlias(String column) { return MEMBER_TABLE_ALIAS + "." + column; } /** * Insert the entity into the database. * @param group org.jasig.portal.groups.IEntityGroup */ private void primAdd(IEntityGroup group, Connection conn) throws SQLException, GroupsException { try { RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, getInsertGroupSql()); try { Integer typeID = EntityTypes.getEntityTypeID(group.getLeafType()); ps.setString(1, group.getLocalKey()); ps.setString(2, group.getCreatorID()); ps.setInt (3, typeID.intValue()); ps.setString(4, group.getName()); ps.setString(5, group.getDescription()); LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primAdd(): " + ps + "(" + group.getLocalKey() + ", " + group.getCreatorID() + ", " + typeID + ", " + group.getName() + ", " + group.getDescription() + ")" ); int rc = ps.executeUpdate(); if ( rc != 1 ) { String errString = "Problem adding " + group; LogService.log (LogService.ERROR, errString); throw new GroupsException(errString); } } finally { ps.close(); } } catch (java.sql.SQLException sqle) { LogService.log (LogService.ERROR, sqle); throw sqle; } } /** * Delete this entity from the database after first deleting * its memberships. * Exception java.sql.SQLException - if we catch a SQLException, * we rollback and re-throw it. * @param group org.jasig.portal.groups.IEntityGroup */ private void primDelete(IEntityGroup group) throws SQLException { java.sql.Connection conn = null; String deleteGroupSql = getDeleteGroupSql(group); String deleteMembershipSql = getDeleteMembersInGroupSql(group); try { conn = RDBMServices.getConnection(); Statement stmnt = conn.createStatement(); setAutoCommit(conn, false); try { LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primDelete(): " + deleteMembershipSql); stmnt.executeUpdate(deleteMembershipSql); LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primDelete(): " + deleteGroupSql); stmnt.executeUpdate(deleteGroupSql); } finally { stmnt.close(); } commit(conn); } catch (SQLException sqle) { rollback(conn); throw sqle; } finally { setAutoCommit(conn, true); RDBMServices.releaseConnection(conn); } } /** * Find and return an instance of the group. * @return org.jasig.portal.groups.IEntityGroup * @param key java.lang.Object * @param lockable boolean */ private IEntityGroup primFind(String groupID, boolean lockable) throws GroupsException { IEntityGroup eg = null; java.sql.Connection conn = null; try { conn = RDBMServices.getConnection(); String sql = getFindGroupSql(); RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, sql); try { ps.setString(1, groupID); LogService.log (LogService.DEBUG, "RDBMEntityGroupStore.find(): " + ps + " (" + groupID + ")"); java.sql.ResultSet rs = ps.executeQuery(); try { while (rs.next()) { eg = (lockable) ? lockableInstanceFromResultSet(rs) : instanceFromResultSet(rs); } } finally { rs.close(); } } finally { ps.close(); } } catch (Exception e) { LogService.log (LogService.ERROR, "RDBMEntityGroupStore.find(): " + e); throw new GroupsException("Error retrieving " + groupID + ": " + e); } finally { RDBMServices.releaseConnection(conn); } return eg; } /** * Update the entity in the database. * @param group org.jasig.portal.groups.IEntityGroup */ private void primUpdate(IEntityGroup group, Connection conn) throws SQLException, GroupsException { try { RDBMServices.PreparedStatement ps = new RDBMServices.PreparedStatement(conn, getUpdateGroupSql()); try { Integer typeID = EntityTypes.getEntityTypeID(group.getLeafType()); ps.setString(1, group.getCreatorID()); ps.setInt(2, typeID.intValue()); ps.setString(3, group.getName()); ps.setString(4, group.getDescription()); ps.setString(5, group.getLocalKey()); LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primUpdate(): " + ps + "(" + group.getCreatorID() + ", " + typeID + ", " + group.getName() + ", " + group.getDescription() + ", " + group.getLocalKey() + ")" ); int rc = ps.executeUpdate(); if ( rc != 1 ) { String errString = "Problem updating " + group; LogService.log (LogService.ERROR, errString); throw new GroupsException(errString); } } finally { ps.close(); } } catch (java.sql.SQLException sqle) { LogService.log (LogService.ERROR, sqle); throw sqle; } } /** * Insert and delete group membership rows. The transaction is maintained by * the caller. * @param group org.jasig.portal.groups.EntityGroupImpl */ private void primUpdateMembers(EntityGroupImpl egi, Connection conn) throws java.sql.SQLException { String groupKey = egi.getLocalKey(); String memberKey, isGroup, serviceName = null; try { if ( egi.hasDeletes() ) { List deletedGroups = new ArrayList(); List deletedEntities = new ArrayList(); Iterator deletes = egi.getRemovedMembers().values().iterator(); while ( deletes.hasNext() ) { IGroupMember gm = (IGroupMember) deletes.next(); if ( gm.isGroup() ) { deletedGroups.add(gm);} else { deletedEntities.add(gm);} } if ( ! deletedGroups.isEmpty() ) { RDBMServices.PreparedStatement psDeleteMemberGroup = new RDBMServices.PreparedStatement(conn, getDeleteMemberGroupSql()); try { for ( Iterator groups = deletedGroups.iterator(); groups.hasNext(); ) { IEntityGroup removedGroup = (IEntityGroup) groups.next(); memberKey = removedGroup.getLocalKey(); isGroup = MEMBER_IS_GROUP; serviceName = removedGroup.getServiceName().toString(); psDeleteMemberGroup.setString(1, groupKey); psDeleteMemberGroup.setString(2, serviceName); psDeleteMemberGroup.setString(3, memberKey); psDeleteMemberGroup.setString(4, isGroup); LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primUpdateMembers(): " + psDeleteMemberGroup + "(" + groupKey + ", " + serviceName + ", " + memberKey + ", " + isGroup + ")" ); psDeleteMemberGroup.executeUpdate(); } // for } // try finally { psDeleteMemberGroup.close(); } } // if ( ! deletedGroups.isEmpty() ) if ( ! deletedEntities.isEmpty() ) { RDBMServices.PreparedStatement psDeleteMemberEntity = new RDBMServices.PreparedStatement(conn, getDeleteMemberEntitySql()); try { for ( Iterator entities = deletedEntities.iterator(); entities.hasNext(); ) { IGroupMember removedEntity = (IGroupMember) entities.next(); memberKey = removedEntity.getUnderlyingEntityIdentifier().getKey(); isGroup = MEMBER_IS_ENTITY; psDeleteMemberEntity.setString(1, groupKey); psDeleteMemberEntity.setString(2, memberKey); psDeleteMemberEntity.setString(3, isGroup); LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primUpdateMembers(): " + psDeleteMemberEntity + "(" + groupKey + ", " + memberKey + ", " + isGroup + ")" ); psDeleteMemberEntity.executeUpdate(); } // for } // try finally { psDeleteMemberEntity.close(); } } // if ( ! deletedEntities.isEmpty() ) } if ( egi.hasAdds() ) { RDBMServices.PreparedStatement psAdd = new RDBMServices.PreparedStatement(conn, getInsertMemberSql()); try { Iterator adds = egi.getAddedMembers().values().iterator(); while ( adds.hasNext() ) { IGroupMember addedGM = (IGroupMember) adds.next(); memberKey = addedGM.getKey(); if ( addedGM.isGroup() ) { IEntityGroup addedGroup = (IEntityGroup) addedGM; isGroup = MEMBER_IS_GROUP; serviceName = addedGroup.getServiceName().toString(); memberKey = addedGroup.getLocalKey(); } else { isGroup = MEMBER_IS_ENTITY; serviceName = egi.getServiceName().toString(); memberKey = addedGM.getUnderlyingEntityIdentifier().getKey(); } psAdd.setString(1, groupKey); psAdd.setString(2, serviceName); psAdd.setString(3, memberKey); psAdd.setString(4, isGroup); LogService.log(LogService.DEBUG, "RDBMEntityGroupStore.primUpdateMembers(): " + psAdd + "(" + groupKey + ", " + memberKey + ", " + isGroup + ")" ); psAdd.executeUpdate(); } } finally { psAdd.close(); } } } catch (SQLException sqle) { LogService.log (LogService.ERROR, sqle); throw sqle; } } /** * @param conn java.sql.Connection * @exception java.sql.SQLException */ protected static void rollback(Connection conn) throws java.sql.SQLException { SqlTransaction.rollback(conn); } public EntityIdentifier[] searchForGroups(String query, int method, Class leaftype) throws GroupsException { EntityIdentifier[] r = new EntityIdentifier[0]; ArrayList ar = new ArrayList(); Connection conn = null; RDBMServices.PreparedStatement ps = null; int type = EntityTypes.getEntityTypeID(leaftype).intValue(); //System.out.println("Checking out groups of leaftype "+leaftype.getName()+" or "+type); try { conn = RDBMServices.getConnection(); switch(method){ case IS: ps = new RDBMServices.PreparedStatement(conn,this.searchGroups); break; case STARTS_WITH: query = query+"%"; ps = new RDBMServices.PreparedStatement(conn,this.searchGroupsPartial); break; case ENDS_WITH: query = "%"+query; ps = new RDBMServices.PreparedStatement(conn,this.searchGroupsPartial); break; case CONTAINS: query = "%"+query+"%"; ps = new RDBMServices.PreparedStatement(conn,this.searchGroupsPartial); break; default: throw new GroupsException("Unknown search type"); } ps.clearParameters(); ps.setInt(1,type); ps.setString(2,query); ResultSet rs = ps.executeQuery(); //System.out.println(ps.toString()); while (rs.next()){ //System.out.println("result"); ar.add(new EntityIdentifier(rs.getString(1), org.jasig.portal.EntityTypes.GROUP_ENTITY_TYPE)); } ps.close(); } catch (Exception e) { LogService.instance().log(LogService.ERROR,"RDBMChannelDefSearcher.searchForEntities(): " + ps); LogService.instance().log(LogService.ERROR, e); } finally { RDBMServices.releaseConnection(conn); } return (EntityIdentifier[]) ar.toArray(r); } /** * @param conn java.sql.Connection * @param newValue boolean * @exception java.sql.SQLException The exception description. */ protected static void setAutoCommit(Connection conn, boolean newValue) throws java.sql.SQLException { SqlTransaction.setAutoCommit(conn, newValue); } /** * @param newGroupService org.jasig.portal.groups.IGroupService */ public void setGroupService(IGroupService newGroupService) { groupService = newGroupService; } /** * @return org.jasig.portal.groups.RDBMEntityGroupStore */ public static synchronized RDBMEntityGroupStore singleton() throws GroupsException { if ( singleton == null ) { singleton = new RDBMEntityGroupStore(); } return singleton; } /** * Commit this entity AND ITS MEMBERSHIPS to the underlying store. * @param group org.jasig.portal.groups.IEntityGroup */ public void update(IEntityGroup group) throws GroupsException { Connection conn = null; boolean exists = existsInDatabase(group); try { conn = RDBMServices.getConnection(); setAutoCommit(conn, false); try { if ( exists ) { primUpdate(group, conn); } else { primAdd(group, conn); } primUpdateMembers((EntityGroupImpl)group, conn); commit(conn); } catch (Exception ex) { rollback(conn); throw new GroupsException("Problem updating " + this + ex); } } catch ( SQLException sqlex ) { throw new GroupsException(sqlex.getMessage()); } finally { try { setAutoCommit(conn, true); } catch (SQLException sqle) { throw new GroupsException(sqle.getMessage()); } RDBMServices.releaseConnection(conn); } } /** * Insert and delete group membership rows inside a transaction. * @param group org.jasig.portal.groups.IEntityGroup */ public void updateMembers(IEntityGroup eg) throws GroupsException { Connection conn = null; EntityGroupImpl egi = (EntityGroupImpl) eg; if ( egi.isDirty() ) try { conn = RDBMServices.getConnection(); setAutoCommit(conn, false); try { primUpdateMembers(egi, conn); commit(conn); } catch ( SQLException sqle ) { rollback(conn); throw new GroupsException("Problem updating memberships for " + egi + " " + sqle.getMessage()); } } catch ( SQLException sqlex ) { throw new GroupsException(sqlex.getMessage()); } finally { try { setAutoCommit(conn, true); } catch (SQLException sqle) { throw new GroupsException(sqle.getMessage()); } RDBMServices.releaseConnection(conn); } } }
package de.longri.cachebox3.gui.activities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.EventListener; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.kotcrab.vis.ui.VisUI; import com.kotcrab.vis.ui.widget.VisLabel; import com.kotcrab.vis.ui.widget.VisTable; import com.kotcrab.vis.ui.widget.VisTextButton; import de.longri.cachebox3.CB; import de.longri.cachebox3.gui.ActivityBase; import de.longri.cachebox3.gui.menu.Menu; import de.longri.cachebox3.gui.menu.MenuID; import de.longri.cachebox3.gui.menu.MenuItem; import de.longri.cachebox3.gui.menu.OnItemClickListener; import de.longri.cachebox3.gui.views.ListView; import de.longri.cachebox3.settings.*; import de.longri.cachebox3.translation.Translation; import org.slf4j.LoggerFactory; public class Settings_Activity extends ActivityBase { final static org.slf4j.Logger log = LoggerFactory.getLogger(Settings_Activity.class); private VisTextButton btnOk, btnCancel, btnMenu; private final SettingsActivityStyle style; public Settings_Activity() { super("Settings_Activity"); this.style = VisUI.getSkin().get("default", SettingsActivityStyle.class); this.setStageBackground(style.background); createButtons(); } @Override public void onShow() { log.debug("Show Settings"); Config.SaveToLastValue(); fillContent(); } @Override public void layout() { super.layout(); float x = Gdx.graphics.getWidth() - (CB.scaledSizes.MARGIN + btnCancel.getWidth()); float y = CB.scaledSizes.MARGIN; btnCancel.setPosition(x, y); x -= CB.scaledSizes.MARGIN + btnMenu.getWidth(); btnMenu.setPosition(x, y); x -= CB.scaledSizes.MARGIN + btnOk.getWidth(); btnOk.setPosition(x, y); log.debug("Layout Settings"); } private void createButtons() { btnOk = new VisTextButton(Translation.Get("save")); btnMenu = new VisTextButton("..."); btnCancel = new VisTextButton(Translation.Get("cancel")); this.addActor(btnOk); this.addActor(btnMenu); this.addActor(btnCancel); btnMenu.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { Menu icm = new Menu(Translation.Get("changeSettingsVisibility")); icm.setOnItemClickListener(new OnItemClickListener() { @Override public boolean onItemClick(MenuItem item) { switch (item.getMenuItemId()) { case MenuID.MI_SHOW_EXPERT: Config.SettingsShowExpert.setValue(!Config.SettingsShowExpert.getValue()); Config.SettingsShowAll.setValue(false); layoutActListView(true); return true; case MenuID.MI_SHOW_ALL: Config.SettingsShowAll.setValue(!Config.SettingsShowAll.getValue()); Config.SettingsShowExpert.setValue(false); layoutActListView(true); return true; case MenuID.MI_SHOW_Normal: Config.SettingsShowAll.setValue(false); Config.SettingsShowExpert.setValue(false); layoutActListView(true); return true; } return false; } }); if (Config.SettingsShowAll.getValue()) Config.SettingsShowExpert.setValue(false); boolean normal = !Config.SettingsShowAll.getValue() && !Config.SettingsShowExpert.getValue(); icm.addCheckableItem(MenuID.MI_SHOW_Normal, "Settings_Normal", normal); icm.addCheckableItem(MenuID.MI_SHOW_EXPERT, "Settings_Expert", Config.SettingsShowExpert.getValue()); icm.addCheckableItem(MenuID.MI_SHOW_ALL, "Settings_All", Config.SettingsShowAll.getValue()); icm.show(); } }); btnOk.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { // String ActionsString = ""; // int counter = 0; // for (int i = 0, n = SettingsItem_QuickButton.tmpQuickList.size(); i < n; i++) { // QuickButtonItem tmp = SettingsItem_QuickButton.tmpQuickList.get(i); // ActionsString += String.valueOf(tmp.getAction().ordinal()); // if (counter < SettingsItem_QuickButton.tmpQuickList.size() - 1) { // ActionsString += ","; // counter++; // Config.quickButtonList.setValue(ActionsString); Config.SaveToLastValue(); Config.AcceptChanges(); finish(); } }); btnCancel.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { Config.LoadFromLastValue(); finish(); } }); } private Array<WidgetGroup> listViews = new Array<WidgetGroup>(); private Array<String> listViewsNames = new Array<String>(); Label.LabelStyle nameStyle, descStyle, defaultValuStyle, valueStyle; private void fillContent() { //set LabelStyles nameStyle = new Label.LabelStyle(); nameStyle.font = style.nameFont; nameStyle.fontColor = style.nameFontColor; descStyle = new Label.LabelStyle(); descStyle.font = style.descFont; descStyle.fontColor = style.descFontColor; defaultValuStyle = new Label.LabelStyle(); defaultValuStyle.font = style.defaultValueFont; defaultValuStyle.fontColor = style.defaultValueFontColor; valueStyle = new Label.LabelStyle(); valueStyle.font = style.valueFont; valueStyle.fontColor = style.valueFontColor; final Array<SettingCategory> settingCategories = new Array<SettingCategory>(); SettingCategory[] tmp = SettingCategory.values(); for (SettingCategory item : tmp) { if (item != SettingCategory.Button) { settingCategories.add(item); } } showListView(new ListView(settingCategories.size) { @Override public VisTable createView(Integer index) { final SettingCategory category = settingCategories.get(index); return getCategoryItem(category); } }, Translation.Get("setting"), true); } private void showListView(ListView listView, String name, boolean animate) { float y = btnOk.getY() + btnOk.getHeight() + CB.scaledSizes.MARGIN; WidgetGroup widgetGroup = new WidgetGroup(); widgetGroup.setBounds(CB.scaledSizes.MARGIN, y, Gdx.graphics.getWidth() - CB.scaledSizes.MARGINx2, Gdx.graphics.getHeight() - (y + CB.scaledSizes.MARGIN)); // title WidgetGroup titleGroup = new WidgetGroup(); float topY = widgetGroup.getHeight() - CB.scaledSizes.MARGIN_HALF; float xPos = 0; ClickListener backClickListener = new ClickListener() { public void clicked(InputEvent event, float x, float y) { backClick(); } }; // add the titleLabel on top if (style.backIcon != null && listViewsNames.size > 0) { Image backImage = new Image(style.backIcon); backImage.setPosition(xPos, 0); xPos += backImage.getWidth() + CB.scaledSizes.MARGIN; titleGroup.addActor(backImage); } VisLabel titleLabel = new VisLabel(name, "menu_title_act"); if (listViewsNames.size > 0) { VisLabel parentTitleLabel = new VisLabel(listViewsNames.get(listViewsNames.size - 1), "menu_title_parent"); parentTitleLabel.setPosition(xPos, 0); xPos += parentTitleLabel.getWidth() + CB.scaledSizes.MARGINx2; titleGroup.addActor(parentTitleLabel); } else { //center titleLabel xPos = (Gdx.graphics.getWidth() - titleLabel.getWidth()) / 2; } titleLabel.setPosition(xPos, 0); titleGroup.addActor(titleLabel); float titleHeight = titleLabel.getHeight() + CB.scaledSizes.MARGIN; titleGroup.setBounds(0, Gdx.graphics.getHeight() - (y + titleHeight), Gdx.graphics.getWidth(), titleHeight); titleGroup.addListener(backClickListener); widgetGroup.addActor(titleGroup); listView.setBounds(0, 0, widgetGroup.getWidth(), titleGroup.getY() - CB.scaledSizes.MARGIN); listView.layout(); listView.setBackground(null); // remove default background widgetGroup.addActor(listView); if (listViews.size > 0) { // animate float nextXPos = Gdx.graphics.getWidth() + CB.scaledSizes.MARGIN; if (animate) { listViews.get(listViews.size - 1).addAction(Actions.moveTo(0 - nextXPos, y, Menu.MORE_MENU_ANIMATION_TIME)); widgetGroup.setPosition(nextXPos, y); widgetGroup.addAction(Actions.moveTo(CB.scaledSizes.MARGIN, y, Menu.MORE_MENU_ANIMATION_TIME)); } else { widgetGroup.setPosition(CB.scaledSizes.MARGIN, y); } } listViews.add(widgetGroup); listViewsNames.add(name); this.addActor(widgetGroup); } private void backClick() { float nextXPos = Gdx.graphics.getWidth() + CB.scaledSizes.MARGIN; if (listViews.size == 1) return; listViewsNames.pop(); WidgetGroup actWidgetGroup = listViews.pop(); WidgetGroup showingWidgetGroup = listViews.get(listViews.size - 1); float y = actWidgetGroup.getY(); actWidgetGroup.addAction(Actions.sequence(Actions.moveTo(nextXPos, y, Menu.MORE_MENU_ANIMATION_TIME), Actions.removeActor())); showingWidgetGroup.addAction(Actions.moveTo(CB.scaledSizes.MARGIN, y, Menu.MORE_MENU_ANIMATION_TIME)); } private void layoutActListView(boolean itemCountChanged) { //get act listView WidgetGroup widgetGroup = listViews.get(listViews.size - 1); ListView actListView = null; for (Actor actor : widgetGroup.getChildren()) { if (actor instanceof ListView) { actListView = (ListView) actor; break; } } if (itemCountChanged) { Object object = actListView.getUserObject(); if (object instanceof SettingCategory) { WidgetGroup group = listViews.pop(); listViewsNames.pop(); //remove all Listener for (Actor actor : group.getChildren()) for (EventListener listener : actor.getListeners()) actor.removeListener(listener); this.removeActor(group); showCategory((SettingCategory) object, false); } } else { actListView.reLayout(); } } private VisTable getCategoryItem(final SettingCategory category) { VisTable table = new VisTable(); // add label with category name, align left table.left(); VisLabel label = new VisLabel(category.name()); label.setAlignment(Align.left); table.add(label).pad(CB.scaledSizes.MARGIN).expandX().fillX(); // add next icon Image next = new Image(style.nextIcon); table.add(next).width(next.getWidth()).pad(CB.scaledSizes.MARGIN / 2); // add clicklistener table.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { if (event.getType() == InputEvent.Type.touchUp) { showCategory(category, true); } } }); return table; } private void showCategory(SettingCategory category, boolean animate) { log.debug("Show settings categoriy: " + category.name()); //get all settings items of this category if the category mode correct final Array<SettingBase<?>> categorySettingsList = new Array<SettingBase<?>>(); boolean expert = Config.SettingsShowAll.getValue() || Config.SettingsShowExpert.getValue(); boolean developer = Config.SettingsShowAll.getValue(); for (SettingBase<?> setting : SettingsList.that) { if (setting.getCategory() == category) { boolean show = false; switch (setting.getMode()) { case DEVELOPER: show = developer; break; case Normal: show = true; break; case Expert: show = expert; break; case Never: show = developer; break; } if (show) { categorySettingsList.add(setting); log.debug(" with setting for: " + setting.getName()); } } } // show new ListView for this category ListView newListView = new ListView(categorySettingsList.size) { @Override public VisTable createView(Integer index) { final SettingBase<?> setting = categorySettingsList.get(index); return getSettingItem(setting); } }; newListView.setUserObject(category); showListView(newListView, category.name(), animate); } private VisTable getSettingItem(SettingBase<?> setting) { if (setting instanceof SettingBool) { return getBoolView((SettingBool) setting); } else if (setting instanceof SettingIntArray) { return getIntArrayView((SettingIntArray) setting); } else if (setting instanceof SettingStringArray) { return getStringArrayView((SettingStringArray) setting); } else if (setting instanceof SettingTime) { return getTimeView((SettingTime) setting); } else if (setting instanceof SettingInt) { return getIntView((SettingInt) setting); } else if (setting instanceof SettingDouble) { return getDblView((SettingDouble) setting); } else if (setting instanceof SettingFloat) { return getFloatView((SettingFloat) setting); } else if (setting instanceof SettingFolder) { return getFolderView((SettingFolder) setting); } else if (setting instanceof SettingFile) { return getFileView((SettingFile) setting); } else if (setting instanceof SettingEnum) { return getEnumView((SettingEnum<?>) setting); } else if (setting instanceof SettingString) { return getStringView((SettingString) setting); // } else if (setting instanceof SettingsListCategoryButton) { // return getButtonView((SettingsListCategoryButton<?>) setting); // } else if (setting instanceof SettingsListGetApiButton) { // return getApiKeyButtonView((SettingsListGetApiButton<?>) setting); // } else if (setting instanceof SettingsListButtonLangSpinner) { // return getLangSpinnerView((SettingsListButtonLangSpinner<?>) setting); // } else if (setting instanceof SettingsListButtonSkinSpinner) { // return getSkinSpinnerView((SettingsListButtonSkinSpinner<?>) setting); } else if (setting instanceof SettingsAudio) { return getAudioView((SettingsAudio) setting); } else if (setting instanceof SettingColor) { return getColorView((SettingColor) setting); } return null; } private VisTable getColorView(SettingColor setting) { return null; } private VisTable getAudioView(SettingsAudio setting) { return null; } private VisTable getStringView(SettingString setting) { return null; } private VisTable getEnumView(SettingEnum<?> setting) { return null; } private VisTable getFileView(SettingFile setting) { return null; } private VisTable getFolderView(SettingFolder setting) { return null; } private VisTable getFloatView(final SettingFloat setting) { final VisLabel valueLabel = new VisLabel(Float.toString(setting.getValue()), valueStyle); VisTable table = getNumericItemTable(valueLabel, setting); // add clickListener table.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { if (event.getType() == InputEvent.Type.touchUp) { new NumericInput_Activity<Float>(setting.getValue()) { public void returnValue(Float value) { setting.setValue(value); WidgetGroup group = listViews.peek(); for (Actor actor : group.getChildren()) { if (actor instanceof ListView) { final ListView listView = (ListView) actor; final float scrollPos = listView.getScrollPos(); listView.rebuildView(); Gdx.app.postRunnable(new Runnable() { @Override public void run() { listView.setScrollPos(scrollPos); } }); } } } }.show(); } } }); return table; } private VisTable getDblView(final SettingDouble setting) { final VisLabel valueLabel = new VisLabel(Double.toString(setting.getValue()), valueStyle); VisTable table = getNumericItemTable(valueLabel, setting); // add clickListener table.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { if (event.getType() == InputEvent.Type.touchUp) { new NumericInput_Activity<Double>(setting.getValue()) { public void returnValue(Double value) { setting.setValue(value); WidgetGroup group = listViews.peek(); for (Actor actor : group.getChildren()) { if (actor instanceof ListView) { final ListView listView = (ListView) actor; final float scrollPos = listView.getScrollPos(); listView.rebuildView(); Gdx.app.postRunnable(new Runnable() { @Override public void run() { listView.setScrollPos(scrollPos); } }); } } } }.show(); } } }); return table; } private VisTable getIntView(final SettingInt setting) { final VisLabel valueLabel = new VisLabel(Integer.toString(setting.getValue()), valueStyle); final VisTable table = getNumericItemTable(valueLabel, setting); // add clickListener table.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { if (event.getType() == InputEvent.Type.touchUp) { new NumericInput_Activity<Integer>(setting.getValue()) { public void returnValue(Integer value) { setting.setValue(value); WidgetGroup group = listViews.peek(); for (Actor actor : group.getChildren()) { if (actor instanceof ListView) { final ListView listView = (ListView) actor; final float scrollPos = listView.getScrollPos(); listView.rebuildView(); Gdx.app.postRunnable(new Runnable() { @Override public void run() { listView.setScrollPos(scrollPos); } }); } } } }.show(); } } }); return table; } private VisTable getTimeView(SettingTime setting) { return null; } private VisTable getStringArrayView(SettingStringArray setting) { return null; } private VisTable getIntArrayView(SettingIntArray setting) { return null; } private VisTable getBoolView(final SettingBool setting) { VisTable table = new VisTable(); // add label with category name, align left table.left(); VisLabel label = new VisLabel(Translation.Get(setting.getName()), nameStyle); label.setWrap(true); label.setAlignment(Align.left); table.add(label).pad(CB.scaledSizes.MARGIN).expandX().fillX(); // add check icon final Image[] checkImage = new Image[1]; if (setting.getValue()) { checkImage[0] = new Image(CB.getSprite("check_on")); } else { checkImage[0] = new Image(CB.getSprite("check_off")); } table.add(checkImage[0]).width(checkImage[0].getWidth()).pad(CB.scaledSizes.MARGIN / 2); // add clicklistener table.addListener(new ClickListener() { public void clicked(InputEvent event, float x, float y) { if (event.getType() == InputEvent.Type.touchUp) { setting.setValue(!setting.getValue()); if (setting.getValue()) { checkImage[0].setDrawable(new SpriteDrawable(CB.getSprite("check_on"))); } else { checkImage[0].setDrawable(new SpriteDrawable(CB.getSprite("check_off"))); } } } }); // add description line if description exist String description = Translation.Get("Desc_" + setting.getName()); if (!description.contains("$ID:")) { table.row(); VisLabel desclabel = new VisLabel(description, descStyle); desclabel.setWrap(true); desclabel.setAlignment(Align.left); table.add(desclabel).colspan(2).pad(CB.scaledSizes.MARGIN).expandX().fillX(); } // add defaultValue line table.row(); VisLabel desclabel = new VisLabel("default: " + String.valueOf(setting.getDefaultValue()), defaultValuStyle); desclabel.setWrap(true); desclabel.setAlignment(Align.left); table.add(desclabel).colspan(2).pad(CB.scaledSizes.MARGIN).expandX().fillX(); return table; } private VisTable getNumericItemTable(VisLabel valueLabel, SettingBase<?> setting) { VisTable table = new VisTable(); // add label with category name, align left table.left(); VisLabel label = new VisLabel(Translation.Get(setting.getName()), nameStyle); label.setWrap(true); label.setAlignment(Align.left); table.add(label).pad(CB.scaledSizes.MARGIN).expandX().fillX(); // add value lable table.add(valueLabel).width(valueLabel.getWidth()).pad(CB.scaledSizes.MARGIN / 2); // add description line if description exist String description = Translation.Get("Desc_" + setting.getName()); if (!description.contains("$ID:")) { table.row(); VisLabel desclabel = new VisLabel(description, descStyle); desclabel.setWrap(true); desclabel.setAlignment(Align.left); table.add(desclabel).colspan(2).pad(CB.scaledSizes.MARGIN).expandX().fillX(); } // add defaultValue line table.row(); VisLabel desclabel = new VisLabel("default: " + String.valueOf(setting.getDefaultValue()), defaultValuStyle); desclabel.setWrap(true); desclabel.setAlignment(Align.left); table.add(desclabel).colspan(2).pad(CB.scaledSizes.MARGIN).expandX().fillX(); return table; } public static class SettingsActivityStyle extends ActivityBaseStyle { public Drawable nextIcon, backIcon; public BitmapFont nameFont, descFont, defaultValueFont, valueFont; public Color nameFontColor, descFontColor, defaultValueFontColor, valueFontColor; } }
package csv; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import utils.Gensym; import utils.Out; import scala.collection.Seq; import scalautils.QuotMarks; public class CSVLexer { public static final String encoding = "UTF-8"; public static int seperator = ",".codePointAt(0); public static final String[] knownHeaders = {"QUESTION", "BLOCK", "OPTIONS", "RESOURCE", "EXCLUSIVE", "ORDERED", "PERTURB", "BRANCH"}; public static String[] headers = null; private static final PrintStream out = new Out(encoding).out; public static HashMap<String, String> xmlChars = new HashMap<String, String>(); static { xmlChars.put("<", "&lt;"); xmlChars.put(">", "&gt;"); xmlChars.put("&", "&amp;"); QuotMarks.addQuots(xmlChars); } private static String sep2string() { return Character.toString((char) seperator); } private static boolean inQuot(String line) { // searches for quotation marks // since there are multiple possibilities for the right qmark, // consider the first match the matching one // only care about the outer quotation. char[] c = line.toCharArray(); boolean inQ = false; String lqmark = ""; Seq<String> rqmarks = null; int i = 0; while (i < c.length) { String s = String.valueOf(c[i]); if (QuotMarks.isA(s)) { if (inQ) { assert (rqmarks!=null); if (rqmarks.contains(s)) { if (i+1 < c.length && c[i]==c[i+1]) // valid escape seq i++; else inQ = false; // else close quot } } else { // if I'm not already in a quote, check whether this is a 2-char quot. if (i + 1 < c.length && QuotMarks.isA(s + String.valueOf(c[i+1]))) { lqmark = s + String.valueOf(c[i+1]); i++; } else lqmark = s ; inQ=true ; rqmarks = QuotMarks.getMatch(lqmark); } } i++; // out.print(i+" "); } return inQ; } private static String[] getHeaders (String line) { Gensym gensym = new Gensym("GENCOLHEAD"); String[] headers = line.split(sep2string()); for (int i = 0; i < headers.length ; i++) { headers[i] = headers[i].trim().toUpperCase(); if (headers[i].equals("")) headers[i] = gensym.next(); else { // make sure it doesn't contain quotes for (int j = 0; j < headers[i].length() ; j++) { if (QuotMarks.isA(headers[i].substring(j, j+1)) || ((j+1 < headers[i].length()) && QuotMarks.isA(headers[i].substring(j, j+2)))) throw new RuntimeException("Headers cannot contain quotation marks : "+headers[i]); } } } for (int i = 0 ; i < headers.length ; i++ ) { boolean in = false; for (int j = 0 ; j < knownHeaders.length ; j++) if (headers[i].equals(knownHeaders[j])) { in = true; break; } if (!in) out.println(String.format("WARNING: Column header %s has no known semantics." , headers[i])); } return headers; } public static String xmlChars2HTML(String s) { for (Map.Entry<String, String> e : xmlChars.entrySet()) s = s.replaceAll(e.getKey(), e.getValue()); return s; } public static String htmlChars2XML(String s) { for (Map.Entry<String, String> e : xmlChars.entrySet()) s = s.replaceAll(e.getValue(), e.getKey()); return s; } private static void clean (HashMap<String, ArrayList<CSVEntry>> entries) { for (String key : entries.keySet()){ // all entries need to have the beginning/trailing seperator and whitespace removed for (CSVEntry entry : entries.get(key)) { if (entry.contents.endsWith(sep2string())) entry.contents = entry.contents.substring(0, entry.contents.length()-sep2string().length()); if (entry.contents.startsWith(sep2string())) entry.contents = entry.contents.substring(sep2string().length()); entry.contents = entry.contents.trim(); // remove beginning/trailing quotation marks String quot = QuotMarks.endingQuot(entry.contents); if (! quot.equals("")) entry.contents = entry.contents.substring(0, entry.contents.length() - quot.length()); quot = QuotMarks.startingQuot(entry.contents); if (! quot.equals("")) entry.contents = entry.contents.substring(quot.length()); // replace XML reserved characters entry.contents = xmlChars2HTML(entry.contents); } } } private static void resetHeaders() { headers = null; } public static HashMap<String, ArrayList<CSVEntry>> lex(String filename) throws FileNotFoundException, IOException, RuntimeException { // FileReader uses the system's default encoding. // BufferedReader makes 16-bit chars BufferedReader br = new BufferedReader(new FileReader(filename)); HashMap<String, ArrayList<CSVEntry>> entries = null; String line = ""; int lineno = 0; // in case this is called multiple times: resetHeaders(); while((line = br.readLine()) != null) { lineno+=1; if (headers==null) { headers = getHeaders(line); entries = new HashMap<String, ArrayList<CSVEntry>>(headers.length); for (int i = 0 ; i < headers.length ; i++) entries.put(headers[i], new ArrayList<CSVEntry>()); } else { // check to make sure this isn't a false alarm where we're in a quot // this is super inefficient, but whatever, we'll make it better later or maybe we won't notice. while (inQuot(line)) { String newLine = br.readLine(); lineno += 1; if (newLine != null) line = line + newLine; else throw new MalformedQuotationException(line); } // for each header, read an entry. String entry = null; String restOfLine = line; for (int i = 0 ; i < headers.length ; i ++) { if (i == headers.length - 1) { if (inQuot(restOfLine)) throw new MalformedQuotationException(restOfLine); entries.get(headers[i]).add(new CSVEntry(restOfLine, lineno, i)); } else { int a = restOfLine.indexOf(Character.toString((char) seperator)); int b = 1; if (a == -1) { out.println(String.format("WARNING: seperator '%s'(unicode:%s) not found in line %d:\n\t (%s)." , Character.toString((char) seperator) , String.format("\\u%04x", seperator) , lineno , line)); } entry = restOfLine.substring(0, a + b); restOfLine = restOfLine.substring(entry.length()); while (inQuot(entry)) { if (restOfLine.equals("")) throw new MalformedQuotationException(entry); a = restOfLine.indexOf(Character.toString((char) seperator)); entry = entry + restOfLine.substring(0, a + b); restOfLine = restOfLine.substring(a + b); } try{ entries.get(headers[i]).add(new CSVEntry(entry, lineno, i)); } catch (NullPointerException e) { System.out.println(entries); System.out.println(headers + " " + i); System.out.println(headers[i]); System.out.println(entry); System.out.println(lineno); } } } } } out.println(filename+": "+(lineno-1)+" "+Character.toString((char) seperator)+" "); clean(entries); if (! entries.keySet().contains("QUESTION")) throw new CSVColumnException("QUESTION"); if (! entries.keySet().contains("OPTIONS")) throw new CSVColumnException("OPTIONS"); return entries; } public static int specialChar(String stemp) { if (stemp.codePointAt(0)!=0x5C) throw new FieldSeperatorException(stemp); switch (stemp.charAt(1)) { case 't': return 0x9; case 'b' : return 0x8; case 'n' : return 0xA; case 'r' : return 0xD; case 'f' : return 0xC; case 'u' : return Integer.decode(stemp.substring(2, 5)); default: throw new FieldSeperatorException(stemp); } } public static void main(String[] args) throws FileNotFoundException, IOException, UnsupportedEncodingException, RuntimeException { //write test code here int i = 0 ; HashMap<String, ArrayList<CSVEntry>> entries; while(i < args.length) { if (i+1 < args.length && args[i+1].startsWith("--sep=")) { String stemp = args[i+1].substring("--sep=".length()); if (stemp.length() > 1) seperator = specialChar(stemp); else seperator = stemp.codePointAt(0); entries = lex(args[i]); i++; } else entries = lex(args[i]); out.println("headers: " + entries.keySet()); for (int j = 0 ; j < headers.length ; j++ ) { ArrayList<CSVEntry> thisCol = entries.get(headers[j]); int sps = 15 - headers[j].length(); String ssps = ""; while(sps>0) { ssps+=" "; sps out.println(headers[j]+ssps+thisCol.get(0)+"..."+thisCol.get(thisCol.size()-1)); } i++; headers = null; } } } class MalformedQuotationException extends RuntimeException { public MalformedQuotationException(String line) { super("Malformed quotation in :"+line); } } class FieldSeperatorException extends RuntimeException { public FieldSeperatorException(String seperator) { super(seperator.startsWith("\\")? "Illegal sep: " + seperator + " is " + seperator.length() + " chars and " + seperator.getBytes().length + " bytes." : "Illegal escape char (" + seperator.charAt(0) + ") in sep " + seperator ); } } class CSVColumnException extends RuntimeException { public CSVColumnException(String colName) { super(String.format("CSVs column headers must contain a %s column" , colName.toUpperCase())); } }
package org.apache.batik.ext.awt.image; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.awt.color.ColorSpace; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.DataBufferShort; import java.awt.image.DataBufferUShort; import java.awt.image.DirectColorModel; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.ComponentSampleModel; import java.awt.image.WritableRaster; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.RenderableImage; import org.apache.batik.ext.awt.RenderingHintsKeyExt; import org.apache.batik.ext.awt.image.PadMode; import org.apache.batik.ext.awt.image.renderable.Filter; import org.apache.batik.ext.awt.image.renderable.PaintRable; import org.apache.batik.ext.awt.image.rendered.AffineRed; import org.apache.batik.ext.awt.image.rendered.Any2LsRGBRed; import org.apache.batik.ext.awt.image.rendered.Any2sRGBRed; import org.apache.batik.ext.awt.image.rendered.BufferedImageCachableRed; import org.apache.batik.ext.awt.image.rendered.CachableRed; import org.apache.batik.ext.awt.image.rendered.FormatRed; import org.apache.batik.ext.awt.image.rendered.MultiplyAlphaRed; import org.apache.batik.ext.awt.image.rendered.PadRed; import org.apache.batik.ext.awt.image.rendered.RenderedImageCachableRed; import org.apache.batik.ext.awt.image.rendered.TranslateRed; import org.apache.batik.ext.awt.image.SVGComposite; /** * Set of utility methods for Graphics. * These generally bypass broken methods in Java2D or provide tweaked * implementations. * * @author <a href="mailto:Thomas.DeWeeese@Kodak.com">Thomas DeWeese</a> * @version $Id$ */ public class GraphicsUtil { public static AffineTransform IDENTITY = new AffineTransform(); /** * Draws <tt>ri</tt> into <tt>g2d</tt>. It does this be * requesting tiles from <tt>ri</tt> and drawing them individually * in <tt>g2d</tt> it also takes care of some colorspace and alpha * issues. * @param g2d The Graphics2D to draw into. * @param ri The image to be drawn. */ public static void drawImage(Graphics2D g2d, RenderedImage ri) { drawImage(g2d, wrap(ri)); } /** * Draws <tt>cr</tt> into <tt>g2d</tt>. It does this be * requesting tiles from <tt>ri</tt> and drawing them individually * in <tt>g2d</tt> it also takes care of some colorspace and alpha * issues. * @param g2d The Graphics2D to draw into. * @param cr The image to be drawn. */ public static void drawImage(Graphics2D g2d, CachableRed cr) { // System.out.println("DrawImage G: " + g2d); ColorModel srcCM = cr.getColorModel(); AffineTransform at = null; while (true) { if (cr instanceof AffineRed) { AffineRed ar = (AffineRed)cr; if (at == null) at = ar.getTransform(); else at.concatenate(ar.getTransform()); cr = ar.getSource(); continue; } else if (cr instanceof TranslateRed) { TranslateRed tr = (TranslateRed)cr; // System.out.println("testing Translate"); int dx = tr.getDeltaX(); int dy = tr.getDeltaY(); if (at == null) at = AffineTransform.getTranslateInstance(dx, dy); else at.translate(dx, dy); cr = tr.getSource(); continue; } break; } AffineTransform g2dAt = g2d.getTransform(); if ((at == null) || (at.isIdentity())) at = g2dAt; else at.preConcatenate(g2dAt); Composite g2dComposite = g2d.getComposite(); if (false) { System.out.println("CR: " + cr); System.out.println("CRR: " + cr.getBounds()); } // Scaling down so do it before color conversion. double determinant = at.getDeterminant(); if (!at.isIdentity() && (determinant <= 1.0)) { if (at.getType() != AffineTransform.TYPE_TRANSLATION) cr = new AffineRed(cr, at, g2d.getRenderingHints()); else { int xloc = cr.getMinX() + (int)at.getTranslateX(); int yloc = cr.getMinY() + (int)at.getTranslateY(); cr = new TranslateRed(cr, xloc, yloc); } } ColorSpace g2dCS = getDestinationColorSpace(g2d); if (g2dCS == null) // Assume device is sRGB g2dCS = ColorSpace.getInstance(ColorSpace.CS_sRGB); if (g2dCS != srcCM.getColorSpace()) { // System.out.println("srcCS: " + srcCM.getColorSpace()); // System.out.println("g2dCS: " + g2dCS); // System.out.println("sRGB: " + // ColorSpace.getInstance(ColorSpace.CS_sRGB)); // System.out.println("LsRGB: " + // ColorSpace.getInstance // (ColorSpace.CS_LINEAR_RGB)); if (g2dCS == ColorSpace.getInstance(ColorSpace.CS_sRGB)) cr = convertTosRGB(cr); else if (g2dCS == ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB)) cr = convertToLsRGB(cr); } srcCM = cr.getColorModel(); ColorModel g2dCM = getDestinationColorModel(g2d); ColorModel drawCM = g2dCM; if (g2dCM == null) { // If we can't find out about our device assume // it's SRGB unpremultiplied (Just because this // seems to work for us). drawCM = sRGB_Unpre; } else if (drawCM.hasAlpha() && g2dCM.hasAlpha() && (drawCM.isAlphaPremultiplied() != g2dCM .isAlphaPremultiplied())) { drawCM = coerceColorModel(drawCM, g2dCM.isAlphaPremultiplied()); } cr = FormatRed.construct(cr, drawCM); // Scaling up so do it after color conversion. if (!at.isIdentity() && (determinant > 1.0)) cr = new AffineRed(cr, at, g2d.getRenderingHints()); // Now CR is in device space, so clear the g2d transform. g2d.setTransform(IDENTITY); // Ugly Hack alert. This Makes it use our SrcOver implementation // Which doesn't seem to have as many bugs as the JDK one when // going between different src's and destinations (of course it's // also a lot slower). if (g2d.getRenderingHint(RenderingHintsKeyExt.KEY_TRANSCODING) == RenderingHintsKeyExt.VALUE_TRANSCODING_PRINTING) { if (SVGComposite.OVER.equals(g2dComposite)) { g2d.setComposite(SVGComposite.OVER); } } Rectangle crR = cr.getBounds(); Shape clip = g2d.getClip(); try { Rectangle clipR; if (clip == null) { clip = crR; clipR = crR; } else { clipR = clip.getBounds(); if (clipR.intersects(crR) == false) return; // Nothing to draw... clipR = clipR.intersection(crR); } Rectangle gcR = getDestinationBounds(g2d); // System.out.println("ClipRects: " + clipR + " -> " + gcR); if (gcR != null) { if (clipR.intersects(gcR) == false) return; // Nothing to draw... clipR = clipR.intersection(gcR); } if (false) { // There has been a problem where the render tries to // request a zero pixel high region (due to a bug in the // complex clip handling). I have at least temporarily // worked around this by changing the alpha state in // CompositeRable which changes code paths enough that the // renderer doesn't try to construct a zero height // SampleModel (which dies). // However I suspect that this fix is fragile (other code // paths may trigger the bug), eventually we may need to // reinstate this code, which handles the clipping for the // Graphics2D. if ((clip != null) && !(clip instanceof Rectangle2D)) { // This is now the clip in device space... clip = g2d.getClip(); if (clip instanceof Rectangle2D) // Simple clip rect... cr = new PadRed(cr, clipR, PadMode.ZERO_PAD, null); else { // Complex clip... // System.out.println("Clip:" + clip); // System.out.println("ClipR: " + clipR); // System.out.println("crR: " + cr.getBounds()); // System.out.println("at: " + at); if (clipR.intersects(cr.getBounds()) == false) return; // Nothing to draw... clipR = clipR.intersection(cr.getBounds()); BufferedImage bi = new BufferedImage (clipR.width, clipR.height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D big2d = createGraphics (bi, g2d.getRenderingHints()); big2d.translate(-clipR.x, -clipR.y); big2d.setPaint(Color.white); big2d.fill(clip); big2d.dispose(); CachableRed cCr; cCr = new BufferedImageCachableRed(bi, clipR.x, clipR.y); cr = new MultiplyAlphaRed (cr, cCr); } g2d.setClip(null); } } // System.out.println("Starting Draw: " + cr); // long startTime = System.currentTimeMillis(); boolean useDrawRenderedImage = false; SampleModel srcSM; srcCM = cr.getColorModel(); srcSM = cr.getSampleModel(); if ((srcSM.getWidth()*srcSM.getHeight()) >= (clipR.width*clipR.height)) // if srcSM tiles are larger than the clip size // then just draw the renderedImage useDrawRenderedImage = true; WritableRaster wr; if (useDrawRenderedImage) { // This can be significantly faster but can also // require much more memory, so we only use it when // the clip size is smaller than the tile size. wr = srcCM.createCompatibleWritableRaster (clipR.width, clipR.height); // If we push caching down the tree farther // Then this code path should probably try to // align with cr's tile grid to promote tile caching // (this of course will increase the memory required // in this path). cr.copyData(wr.createWritableTranslatedChild (clipR.x, clipR.y)); BufferedImage bi = new BufferedImage (srcCM, wr, srcCM.isAlphaPremultiplied(), null); // Any of the drawImage calls that take an // Affine are prone to the 'CGGStackRestore: gstack // underflow' bug on Mac OS X. This should work // around that problem. g2d.drawImage(bi, clipR.x, clipR.y, null); } else { // Use tiles to draw image... wr = Raster.createWritableRaster(srcSM, new Point(0,0)); BufferedImage bi = new BufferedImage (srcCM, wr, srcCM.isAlphaPremultiplied(), null); int xt0 = cr.getMinTileX(); int xt1 = xt0+cr.getNumXTiles(); int yt0 = cr.getMinTileY(); int yt1 = yt0+cr.getNumYTiles(); int tw = srcSM.getWidth(); int th = srcSM.getHeight(); Rectangle tR = new Rectangle(0,0,tw,th); Rectangle iR = new Rectangle(0,0,0,0); if (false) { System.out.println("CR: " + cr); System.out.println("CRR: " + crR + " TG: [" + xt0 +"," + yt0 +"," + xt1 +"," + yt1 +"] Off: " + cr.getTileGridXOffset() +"," + cr.getTileGridYOffset()); } DataBuffer db = wr.getDataBuffer(); int yloc = yt0*th+cr.getTileGridYOffset(); int skip = (clipR.y-yloc)/th; if (skip <0) skip = 0; yt0+=skip; int xloc = xt0*tw+cr.getTileGridXOffset(); skip = (clipR.x-xloc)/tw; if (skip <0) skip = 0; xt0+=skip; int endX = clipR.x+clipR.width-1; int endY = clipR.y+clipR.height-1; if (false) { System.out.println("clipR: " + clipR + " TG: [" + xt0 +"," + yt0 +"," + xt1 +"," + yt1 +"] Off: " + cr.getTileGridXOffset() +"," + cr.getTileGridYOffset()); } yloc = yt0*th+cr.getTileGridYOffset(); int minX = xt0*tw+cr.getTileGridXOffset(); int xStep = tw; xloc = minX; for (int y=yt0; y<yt1; y++, yloc += th) { if (yloc > endY) break; for (int x=xt0; x<xt1; x++, xloc+=xStep) { if ((xloc<minX) || (xloc > endX)) break; tR.x = xloc; tR.y = yloc; Rectangle2D.intersect(crR, tR, iR); WritableRaster twr; twr = wr.createWritableChild(0, 0, iR.width, iR.height, iR.x, iR.y, null); // System.out.println("Generating tile: " + twr); cr.copyData(twr); // Make sure we only draw the region that was written. BufferedImage subBI; subBI = bi.getSubimage(0, 0, iR.width, iR.height); if (false) { System.out.println("Drawing: " + tR); System.out.println("IR: " + iR); } // For some reason using the transform version // causes a gStackUnderflow error but if I just // use the drawImage with an x & y it works. g2d.drawImage(subBI, iR.x, iR.y, null); // AffineTransform trans // = AffineTransform.getTranslateInstance(iR.x, iR.y); // g2d.drawImage(subBI, trans, null); // String label = "sub [" + x + ", " + y + "]: "; // org.ImageDisplay.showImage // (label, subBI); } xStep = -xStep; // Reverse directions. xloc += xStep; // Get back in bounds. } } // long endTime = System.currentTimeMillis(); // System.out.println("Time: " + (endTime-startTime)); } finally { g2d.setTransform(g2dAt); g2d.setComposite(g2dComposite); } // System.out.println("Finished Draw"); } /** * Draws a <tt>Filter</tt> (<tt>RenderableImage</tt>) into a * Graphics 2D after taking into account a particular * <tt>RenderContext</tt>.<p> * * This method also attempts to unwind the rendering chain a bit. * So it knows about certain operations (like affine, pad, * composite), rather than applying each of these operations in * turn it accounts for there affects through modifications to the * Graphics2D. This avoids generating lots of intermediate images. * * @param g2d The Graphics to draw into. * @param filter The filter to draw * @param rc The render context that controls the drawing operation. */ public static void drawImage(Graphics2D g2d, RenderableImage filter, RenderContext rc) { AffineTransform origDev = g2d.getTransform(); Shape origClip = g2d.getClip(); RenderingHints origRH = g2d.getRenderingHints(); Shape clip = rc.getAreaOfInterest(); if (clip != null) g2d.clip(clip); g2d.transform(rc.getTransform()); g2d.setRenderingHints(rc.getRenderingHints()); drawImage(g2d, filter); g2d.setTransform(origDev); g2d.setClip(origClip); g2d.setRenderingHints(origRH); } /** * Draws a <tt>Filter</tt> (<tt>RenderableImage</tt>) into a * Graphics 2D.<p> * * This method also attempts to unwind the rendering chain a bit. * So it knows about certain operations (like affine, pad, * composite), rather than applying each of these operations in * turn it accounts for there affects through modifications to the * Graphics2D. This avoids generating lots of intermediate images. * * @param g2d The Graphics to draw into. * @param filter The filter to draw */ public static void drawImage(Graphics2D g2d, RenderableImage filter) { if (filter instanceof PaintRable) { PaintRable pr = (PaintRable)filter; if (pr.paintRable(g2d)) // paintRable succeeded so we are done... return; } // Get our sources image... // System.out.println("UnOpt: " + filter); AffineTransform at = g2d.getTransform(); RenderedImage ri = filter.createRendering (new RenderContext(at, g2d.getClip(), g2d.getRenderingHints())); if (ri == null) return; g2d.setTransform(IDENTITY); drawImage(g2d, GraphicsUtil.wrap(ri)); g2d.setTransform(at); } /** * This is a wrapper around the system's * BufferedImage.createGraphics that arranges for bi to be stored * in a Rendering hint in the returned Graphics2D. * This allows for accurate determination of the 'devices' size, * and colorspace. * @param bi The BufferedImage that the returned Graphics should * draw into. * @return A Graphics2D that draws into BufferedImage with <tt>bi</tt> * stored in a rendering hint. */ public static Graphics2D createGraphics(BufferedImage bi, RenderingHints hints) { Graphics2D g2d = bi.createGraphics(); if (hints != null) g2d.addRenderingHints(hints); g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference(bi)); g2d.clip(new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); return g2d; } public static Graphics2D createGraphics(BufferedImage bi) { Graphics2D g2d = bi.createGraphics(); g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference(bi)); g2d.clip(new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); return g2d; } public final static boolean WARN_DESTINATION = true; public static BufferedImage getDestination(Graphics2D g2d) { Object o = g2d.getRenderingHint (RenderingHintsKeyExt.KEY_BUFFERED_IMAGE); if (o != null) return (BufferedImage)(((Reference)o).get()); // Check if this is a BufferedImage G2d if so throw an error... GraphicsConfiguration gc = g2d.getDeviceConfiguration(); GraphicsDevice gd = gc.getDevice(); if (WARN_DESTINATION && (gd.getType() == GraphicsDevice.TYPE_IMAGE_BUFFER) && (g2d.getRenderingHint(RenderingHintsKeyExt.KEY_TRANSCODING) != RenderingHintsKeyExt.VALUE_TRANSCODING_PRINTING)) System.out.println ("Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint"); return null; } public static ColorModel getDestinationColorModel(Graphics2D g2d) { BufferedImage bi = getDestination(g2d); if (bi != null) return bi.getColorModel(); GraphicsConfiguration gc = g2d.getDeviceConfiguration(); // We are going to a BufferedImage but no hint was provided // so we can't determine the destination Color Model. if (gc.getDevice().getType() == GraphicsDevice.TYPE_IMAGE_BUFFER) { if (g2d.getRenderingHint(RenderingHintsKeyExt.KEY_TRANSCODING) == RenderingHintsKeyExt.VALUE_TRANSCODING_PRINTING) return sRGB_Unpre; // System.out.println("CM: " + gc.getColorModel()); // System.out.println("CS: " + gc.getColorModel().getColorSpace()); return null; } return gc.getColorModel(); } public static ColorSpace getDestinationColorSpace(Graphics2D g2d) { ColorModel cm = getDestinationColorModel(g2d); if (cm != null) return cm.getColorSpace(); return null; } public static Rectangle getDestinationBounds(Graphics2D g2d) { BufferedImage bi = getDestination(g2d); if (bi != null) return new Rectangle(0, 0, bi.getWidth(), bi.getHeight()); GraphicsConfiguration gc = g2d.getDeviceConfiguration(); // We are going to a BufferedImage but no hint was provided // so we can't determine the destination bounds. if (gc.getDevice().getType() == GraphicsDevice.TYPE_IMAGE_BUFFER) return null; // This is a JDK 1.3ism, so we will just return null... // return gc.getBounds(); return null; } /** * Standard prebuilt Linear_sRGB color model with no alpha */ public final static ColorModel Linear_sRGB = new DirectColorModel(ColorSpace.getInstance (ColorSpace.CS_LINEAR_RGB), 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x0, false, DataBuffer.TYPE_INT); /** * Standard prebuilt Linear_sRGB color model with premultiplied alpha. */ public final static ColorModel Linear_sRGB_Pre = new DirectColorModel(ColorSpace.getInstance (ColorSpace.CS_LINEAR_RGB), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, true, DataBuffer.TYPE_INT); /** * Standard prebuilt Linear_sRGB color model with unpremultiplied alpha. */ public final static ColorModel Linear_sRGB_Unpre = new DirectColorModel(ColorSpace.getInstance (ColorSpace.CS_LINEAR_RGB), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, false, DataBuffer.TYPE_INT); /** * Standard prebuilt sRGB color model with no alpha. */ public final static ColorModel sRGB = new DirectColorModel(ColorSpace.getInstance (ColorSpace.CS_sRGB), 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x0, false, DataBuffer.TYPE_INT); /** * Standard prebuilt sRGB color model with premultiplied alpha. */ public final static ColorModel sRGB_Pre = new DirectColorModel(ColorSpace.getInstance (ColorSpace.CS_sRGB), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, true, DataBuffer.TYPE_INT); /** * Standard prebuilt sRGB color model with unpremultiplied alpha. */ public final static ColorModel sRGB_Unpre = new DirectColorModel(ColorSpace.getInstance (ColorSpace.CS_sRGB), 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, false, DataBuffer.TYPE_INT); /** * Method that returns either Linear_sRGB_Pre or Linear_sRGB_UnPre * based on premult flag. * @param premult True if the ColorModel should have premultiplied alpha. * @return a ColorMdoel with Linear sRGB colorSpace and * the alpha channel set in accordance with * <tt>premult</tt> */ public static ColorModel makeLinear_sRGBCM(boolean premult) { if (premult) return Linear_sRGB_Pre; return Linear_sRGB_Unpre; } /** * Constructs a BufferedImage with a linear sRGB colorModel, and alpha. * @param width The desired width of the BufferedImage * @param height The desired height of the BufferedImage * @param premult The desired state of alpha premultiplied * @return The requested BufferedImage. */ public static BufferedImage makeLinearBufferedImage(int width, int height, boolean premult) { ColorModel cm = makeLinear_sRGBCM(premult); WritableRaster wr = cm.createCompatibleWritableRaster(width, height); return new BufferedImage(cm, wr, premult, null); } /** * This method will return a CacheableRed that has it's data in * the linear sRGB colorspace. If <tt>src</tt> is already in * linear sRGB then this method does nothing and returns <tt>src</tt>. * Otherwise it creates a transform that will convert * <tt>src</tt>'s output to linear sRGB and returns that CacheableRed. * * @param src The image to convert to linear sRGB. * @return An equivilant image to <tt>src</tt> who's data is in * linear sRGB. */ public static CachableRed convertToLsRGB(CachableRed src) { ColorModel cm = src.getColorModel(); ColorSpace cs = cm.getColorSpace(); if (cs == ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB)) return src; return new Any2LsRGBRed(src); } /** * This method will return a CacheableRed that has it's data in * the sRGB colorspace. If <tt>src</tt> is already in * sRGB then this method does nothing and returns <tt>src</tt>. * Otherwise it creates a transform that will convert * <tt>src</tt>'s output to sRGB and returns that CacheableRed. * * @param src The image to convert to sRGB. * @return An equivilant image to <tt>src</tt> who's data is in sRGB. */ public static CachableRed convertTosRGB(CachableRed src) { ColorModel cm = src.getColorModel(); ColorSpace cs = cm.getColorSpace(); if (cs == ColorSpace.getInstance(ColorSpace.CS_sRGB)) return src; return new Any2sRGBRed(src); } /** * Convertes any RenderedImage to a CacheableRed. <p> * If <tt>ri</tt> is already a CacheableRed it casts it down and * returns it.<p> * * In cases where <tt>ri</tt> is not already a CacheableRed it * wraps <tt>ri</tt> with a helper class. The wrapped * CacheableRed "Pretends" that it has no sources since it has no * way of inteligently handling the dependency/dirty region calls * if it exposed the source. * @param ri The RenderedImage to convert. * @return a CacheableRed that contains the same data as ri. */ public static CachableRed wrap(RenderedImage ri) { if (ri instanceof CachableRed) return (CachableRed) ri; if (ri instanceof BufferedImage) return new BufferedImageCachableRed((BufferedImage)ri); return new RenderedImageCachableRed(ri); } /** * An internal optimized version of copyData designed to work on * Integer packed data with a SinglePixelPackedSampleModel. Only * the region of overlap between src and dst is copied. * * Calls to this should be preflighted with is_INT_PACK_Data * on both src and dest (requireAlpha can be false). * * @param src The source of the data * @param dst The destination for the data. */ public static void copyData_INT_PACK(Raster src, WritableRaster dst) { // System.out.println("Fast copyData"); int x0 = dst.getMinX(); if (x0 < src.getMinX()) x0 = src.getMinX(); int y0 = dst.getMinY(); if (y0 < src.getMinY()) y0 = src.getMinY(); int x1 = dst.getMinX()+dst.getWidth()-1; if (x1 > src.getMinX()+src.getWidth()-1) x1 = src.getMinX()+src.getWidth()-1; int y1 = dst.getMinY()+dst.getHeight()-1; if (y1 > src.getMinY()+src.getHeight()-1) y1 = src.getMinY()+src.getHeight()-1; int width = x1-x0+1; int height = y1-y0+1; SinglePixelPackedSampleModel srcSPPSM; srcSPPSM = (SinglePixelPackedSampleModel)src.getSampleModel(); final int srcScanStride = srcSPPSM.getScanlineStride(); DataBufferInt srcDB = (DataBufferInt)src.getDataBuffer(); final int [] srcPixels = srcDB.getBankData()[0]; final int srcBase = (srcDB.getOffset() + srcSPPSM.getOffset(x0-src.getSampleModelTranslateX(), y0-src.getSampleModelTranslateY())); SinglePixelPackedSampleModel dstSPPSM; dstSPPSM = (SinglePixelPackedSampleModel)dst.getSampleModel(); final int dstScanStride = dstSPPSM.getScanlineStride(); DataBufferInt dstDB = (DataBufferInt)dst.getDataBuffer(); final int [] dstPixels = dstDB.getBankData()[0]; final int dstBase = (dstDB.getOffset() + dstSPPSM.getOffset(x0-dst.getSampleModelTranslateX(), y0-dst.getSampleModelTranslateY())); if ((srcScanStride == dstScanStride) && (srcScanStride == width)) { // System.out.println("VERY Fast copyData"); System.arraycopy(srcPixels, srcBase, dstPixels, dstBase, width*height); } else if (width > 128) { int srcSP = srcBase; int dstSP = dstBase; for (int y=0; y<height; y++) { System.arraycopy(srcPixels, srcSP, dstPixels, dstSP, width); srcSP += srcScanStride; dstSP += dstScanStride; } } else { for (int y=0; y<height; y++) { int srcSP = srcBase+y*srcScanStride; int dstSP = dstBase+y*dstScanStride; for (int x=0; x<width; x++) dstPixels[dstSP++] = srcPixels[srcSP++]; } } } public static void copyData_FALLBACK(Raster src, WritableRaster dst) { // System.out.println("Fallback copyData"); int x0 = dst.getMinX(); if (x0 < src.getMinX()) x0 = src.getMinX(); int y0 = dst.getMinY(); if (y0 < src.getMinY()) y0 = src.getMinY(); int x1 = dst.getMinX()+dst.getWidth()-1; if (x1 > src.getMinX()+src.getWidth()-1) x1 = src.getMinX()+src.getWidth()-1; int y1 = dst.getMinY()+dst.getHeight()-1; if (y1 > src.getMinY()+src.getHeight()-1) y1 = src.getMinY()+src.getHeight()-1; int width = x1-x0+1; int height = y1-y0+1; int [] data = null; for (int y = y0; y <= y1 ; y++) { data = src.getPixels(x0,y,width,1,data); dst.setPixels (x0,y,width,1,data); } } /** * Copies data from one raster to another. Only the region of * overlap between src and dst is copied. <tt>Src</tt> and * <tt>Dst</tt> must have compatible SampleModels. * * @param src The source of the data * @param dst The destination for the data. */ public static void copyData(Raster src, WritableRaster dst) { if (is_INT_PACK_Data(src.getSampleModel(), false) && is_INT_PACK_Data(dst.getSampleModel(), false)) { copyData_INT_PACK(src, dst); return; } copyData_FALLBACK(src, dst); } /** * Creates a new raster that has a <b>copy</b> of the data in * <tt>ras</tt>. This is highly optimized for speed. There is * no provision for changing any aspect of the SampleModel. * * This method should be used when you need to change the contents * of a Raster that you do not "own" (ie the result of a * <tt>getData</tt> call). * @param ras The Raster to copy. * @return A writable copy of <tt>ras</tt> */ public static WritableRaster copyRaster(Raster ras) { return copyRaster(ras, ras.getMinX(), ras.getMinY()); } /** * Creates a new raster that has a <b>copy</b> of the data in * <tt>ras</tt>. This is highly optimized for speed. There is * no provision for changing any aspect of the SampleModel. * However you can specify a new location for the returned raster. * * This method should be used when you need to change the contents * of a Raster that you do not "own" (ie the result of a * <tt>getData</tt> call). * * @param ras The Raster to copy. * * @param minX The x location for the upper left corner of the * returned WritableRaster. * * @param minY The y location for the upper left corner of the * returned WritableRaster. * * @return A writable copy of <tt>ras</tt> */ public static WritableRaster copyRaster(Raster ras, int minX, int minY) { WritableRaster newSrcWR; WritableRaster ret = Raster.createWritableRaster (ras.getSampleModel(), new Point(0,0)); ret = ret.createWritableChild (ras.getMinX()-ras.getSampleModelTranslateX(), ras.getMinY()-ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null); // Use System.arraycopy to copy the data between the two... DataBuffer srcDB = ras.getDataBuffer(); DataBuffer retDB = ret.getDataBuffer(); if (srcDB.getDataType() != retDB.getDataType()) { throw new IllegalArgumentException ("New DataBuffer doesn't match original"); } int len = srcDB.getSize(); int banks = srcDB.getNumBanks(); int [] offsets = srcDB.getOffsets(); for (int b=0; b< banks; b++) { switch (srcDB.getDataType()) { case DataBuffer.TYPE_BYTE: { DataBufferByte srcDBT = (DataBufferByte)srcDB; DataBufferByte retDBT = (DataBufferByte)retDB; System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len); } case DataBuffer.TYPE_INT: { DataBufferInt srcDBT = (DataBufferInt)srcDB; DataBufferInt retDBT = (DataBufferInt)retDB; System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len); } case DataBuffer.TYPE_SHORT: { DataBufferShort srcDBT = (DataBufferShort)srcDB; DataBufferShort retDBT = (DataBufferShort)retDB; System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len); } case DataBuffer.TYPE_USHORT: { DataBufferUShort srcDBT = (DataBufferUShort)srcDB; DataBufferUShort retDBT = (DataBufferUShort)retDB; System.arraycopy(srcDBT.getData(b), offsets[b], retDBT.getData(b), offsets[b], len); } } } return ret; } /** * Coerces <tt>ras</tt> to be writable. The returned Raster continues to * reference the DataBuffer from ras, so modifications to the returned * WritableRaster will be seen in ras.<p> * * This method should only be used if you need a WritableRaster due to * an interface (such as to construct a BufferedImage), but have no * intention of modifying the contents of the returned Raster. If * you have any doubt about other users of the data in <tt>ras</tt>, * use copyRaster (above). * @param ras The raster to make writable. * @return A Writable version of ras (shares DataBuffer with * <tt>ras</tt>). */ public static WritableRaster makeRasterWritable(Raster ras) { return makeRasterWritable(ras, ras.getMinX(), ras.getMinY()); } /** * Coerces <tt>ras</tt> to be writable. The returned Raster continues to * reference the DataBuffer from ras, so modifications to the returned * WritableRaster will be seen in ras.<p> * * You can specify a new location for the returned WritableRaster, this * is especially useful for constructing BufferedImages which require * the Raster to be at (0,0). * * This method should only be used if you need a WritableRaster due to * an interface (such as to construct a BufferedImage), but have no * intention of modifying the contents of the returned Raster. If * you have any doubt about other users of the data in <tt>ras</tt>, * use copyRaster (above). * * @param ras The raster to make writable. * * @param minX The x location for the upper left corner of the * returned WritableRaster. * * @param minY The y location for the upper left corner of the * returned WritableRaster. * * @return A Writable version of <tT>ras</tt> with it's upper left * hand coordinate set to minX, minY (shares it's DataBuffer * with <tt>ras</tt>). */ public static WritableRaster makeRasterWritable(Raster ras, int minX, int minY) { WritableRaster ret = Raster.createWritableRaster (ras.getSampleModel(), ras.getDataBuffer(), new Point(0,0)); ret = ret.createWritableChild (ras.getMinX()-ras.getSampleModelTranslateX(), ras.getMinY()-ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null); return ret; } /** * Create a new ColorModel with it's alpha premultiplied state matching * newAlphaPreMult. * @param cm The ColorModel to change the alpha premult state of. * @param newAlphaPreMult The new state of alpha premult. * @return A new colorModel that has isAlphaPremultiplied() * equal to newAlphaPreMult. */ public static ColorModel coerceColorModel(ColorModel cm, boolean newAlphaPreMult) { if (cm.isAlphaPremultiplied() == newAlphaPreMult) return cm; // Easiest way to build proper colormodel for new Alpha state... // Eventually this should switch on known ColorModel types and // only fall back on this hack when the CM type is unknown. WritableRaster wr = cm.createCompatibleWritableRaster(1,1); return cm.coerceData(wr, newAlphaPreMult); } /** * Coerces data within a bufferedImage to match newAlphaPreMult, * Note that this can not change the colormodel of bi so you * * @param wr The raster to change the state of. * @param cm The colormodel currently associated with data in wr. * @param newAlphaPreMult The desired state of alpha Premult for raster. * @return A new colormodel that matches newAlphaPreMult. */ public static ColorModel coerceData(WritableRaster wr, ColorModel cm, boolean newAlphaPreMult) { // System.out.println("CoerceData: " + cm.isAlphaPremultiplied() + // " Out: " + newAlphaPreMult); if (cm.hasAlpha()== false) // Nothing to do no alpha channel return cm; if (cm.isAlphaPremultiplied() == newAlphaPreMult) // nothing to do alpha state matches... return cm; // System.out.println("CoerceData: " + wr.getSampleModel()); int [] pixel = null; int bands = wr.getNumBands(); float norm; if (newAlphaPreMult) { if (is_BYTE_COMP_Data(wr.getSampleModel())) mult_BYTE_COMP_Data(wr); else if (is_INT_PACK_Data(wr.getSampleModel(), true)) mult_INT_PACK_Data(wr); else { norm = 1f/255f; int x0, x1, y0, y1, a, b; float alpha; x0 = wr.getMinX(); x1 = x0+wr.getWidth(); y0 = wr.getMinY(); y1 = y0+wr.getHeight(); for (int y=y0; y<y1; y++) for (int x=x0; x<x1; x++) { pixel = wr.getPixel(x,y,pixel); a = pixel[bands-1]; if ((a >= 0) && (a < 255)) { alpha = a*norm; for (b=0; b<bands-1; b++) pixel[b] = (int)(pixel[b]*alpha+0.5f); wr.setPixel(x,y,pixel); } } } } else { if (is_BYTE_COMP_Data(wr.getSampleModel())) divide_BYTE_COMP_Data(wr); else if (is_INT_PACK_Data(wr.getSampleModel(), true)) divide_INT_PACK_Data(wr); else { int x0, x1, y0, y1, a, b; float ialpha; x0 = wr.getMinX(); x1 = x0+wr.getWidth(); y0 = wr.getMinY(); y1 = y0+wr.getHeight(); for (int y=y0; y<y1; y++) for (int x=x0; x<x1; x++) { pixel = wr.getPixel(x,y,pixel); a = pixel[bands-1]; if ((a > 0) && (a < 255)) { ialpha = 255/(float)a; for (b=0; b<bands-1; b++) pixel[b] = (int)(pixel[b]*ialpha+0.5f); wr.setPixel(x,y,pixel); } } } } return coerceColorModel(cm, newAlphaPreMult); } /** * Copies data from one bufferedImage to another paying attention * to the state of AlphaPreMultiplied. * * @param src The source * @param dst The destination */ public static void copyData(BufferedImage src, BufferedImage dst) { Rectangle srcRect = new Rectangle(0, 0, src.getWidth(), src.getHeight()); copyData(src, srcRect, dst, new Point(0,0)); } /** * Copies data from one bufferedImage to another paying attention * to the state of AlphaPreMultiplied. * * @param src The source * @param srcRect The Rectangle of source data to be copied * @param dst The destination * @param dstP The Place for the upper left corner of srcRect in dst. */ public static void copyData(BufferedImage src, Rectangle srcRect, BufferedImage dst, Point destP) { ColorSpace srcCS = src.getColorModel().getColorSpace(); ColorSpace dstCS = dst.getColorModel().getColorSpace(); boolean srcAlpha = src.getColorModel().hasAlpha(); boolean dstAlpha = dst.getColorModel().hasAlpha(); // System.out.println("Src has: " + srcAlpha + // " is: " + src.isAlphaPremultiplied()); // System.out.println("Dst has: " + dstAlpha + // " is: " + dst.isAlphaPremultiplied()); if (srcAlpha == dstAlpha) if ((srcAlpha == false) || (src.isAlphaPremultiplied() == dst.isAlphaPremultiplied())) { // They match one another so just copy everything... copyData(src.getRaster(), dst.getRaster()); return; } // System.out.println("Using Slow CopyData"); int [] pixel = null; Raster srcR = src.getRaster(); WritableRaster dstR = dst.getRaster(); int bands = dstR.getNumBands(); float norm; int dx = destP.x-srcRect.x; int dy = destP.y-srcRect.y; int w = srcRect.width; int x0 = srcRect.x; int y0 = srcRect.y; int x1 = x0+srcRect.width-1; int y1 = y0+srcRect.height-1; if (!srcAlpha) { // Src has no alpha dest does so set alpha to 1.0 everywhere. // System.out.println("Add Alpha"); int [] oPix = new int[bands*w]; int out = (w*bands)-1; // The 2 skips alpha channel while(out >= 0) { // Fill alpha channel with 255's oPix[out] = 255; out -= bands; } int b, in; for (int y=y0; y<=y1; y++) { pixel = srcR.getPixels(x0,y,w,1,pixel); in = w*(bands-1)-1; out = (w*bands)-2; // The 2 skips alpha channel on last pix switch (bands) { case 4: while(in >= 0) { oPix[out--] = pixel[in--]; oPix[out--] = pixel[in--]; oPix[out--] = pixel[in--]; out } break; default: while(in >= 0) { for (b=0; b<bands-1; b++) oPix[out--] = pixel[in--]; out } } dstR.setPixels(x0+dx, y+dy, w, 1, oPix); } } else if (dstAlpha && dst.isAlphaPremultiplied()) { // Src and dest have Alpha but we need to multiply it for dst. // System.out.println("Mult Case"); int a, b, alpha, in, fpNorm = (1<<24)/255, pt5 = 1<<23; for (int y=y0; y<=y1; y++) { pixel = srcR.getPixels(x0,y,w,1,pixel); in=bands*w-1; switch (bands) { case 4: while(in >= 0) { a = pixel[in]; if (a == 255) in -= 4; else { in alpha = fpNorm*a; pixel[in] = (pixel[in]*alpha+pt5)>>>24; in pixel[in] = (pixel[in]*alpha+pt5)>>>24; in pixel[in] = (pixel[in]*alpha+pt5)>>>24; in } } break; default: while(in >= 0) { a = pixel[in]; if (a == 255) in -= bands; else { in alpha = fpNorm*a; for (b=0; b<bands-1; b++) { pixel[in] = (pixel[in]*alpha+pt5)>>>24; in } } } }; dstR.setPixels(x0+dx, y+dy, w, 1, pixel); } } else if (dstAlpha && !dst.isAlphaPremultiplied()) { // Src and dest have Alpha but we need to divide it out for dst. // System.out.println("Div Case"); int a, b, ialpha, in, fpNorm = 0x00FF0000, pt5 = 1<<15; for (int y=y0; y<=y1; y++) { pixel = srcR.getPixels(x0,y,w,1,pixel); in=(bands*w)-1; switch(bands) { case 4: while(in >= 0) { a = pixel[in]; if ((a <= 0) || (a >= 255)) in -= 4; else { in ialpha = fpNorm/a; pixel[in] = (pixel[in]*ialpha+pt5)>>>16; in pixel[in] = (pixel[in]*ialpha+pt5)>>>16; in pixel[in] = (pixel[in]*ialpha+pt5)>>>16; in } } break; default: while(in >= 0) { a = pixel[in]; if ((a <= 0) || (a >= 255)) in -= bands; else { in ialpha = fpNorm/a; for (b=0; b<bands-1; b++) { pixel[in] = (pixel[in]*ialpha+pt5)>>>16; in } } } } dstR.setPixels(x0+dx, y+dy, w, 1, pixel); } } else if (src.isAlphaPremultiplied()) { int [] oPix = new int[bands*w]; // Src has alpha dest does not so unpremult and store... // System.out.println("Remove Alpha, Div Case"); int a, b, ialpha, in, out, fpNorm = 0x00FF0000, pt5 = 1<<15; for (int y=y0; y<=y1; y++) { pixel = srcR.getPixels(x0,y,w,1,pixel); in = (bands+1)*w -1; out = (bands*w)-1; while(in >= 0) { a = pixel[in]; in if (a > 0) { if (a < 255) { ialpha = fpNorm/a; for (b=0; b<bands; b++) oPix[out--] = (pixel[in--]*ialpha+pt5)>>>16; } else for (b=0; b<bands; b++) oPix[out--] = pixel[in--]; } else { in -= bands; for (b=0; b<bands; b++) oPix[out--] = 255; } } dstR.setPixels(x0+dx, y+dy, w, 1, oPix); } } else { // Src has unpremult alpha, dest does not have alpha, // just copy the color channels over. Rectangle dstRect = new Rectangle(destP.x, destP.y, srcRect.width, srcRect.height); for (int b=0; b<bands; b++) copyBand(srcR, srcRect, b, dstR, dstRect, b); } } public static void copyBand(Raster src, int srcBand, WritableRaster dst, int dstBand) { Rectangle sR = src.getBounds(); Rectangle dR = dst.getBounds(); Rectangle cpR = sR.intersection(dR); copyBand(src, cpR, srcBand, dst, cpR, dstBand); } public static void copyBand(Raster src, Rectangle sR, int sBand, WritableRaster dst, Rectangle dR, int dBand) { int dy = dR.y -sR.y; int dx = dR.x -sR.x; sR = sR.intersection(src.getBounds()); dR = dR.intersection(dst.getBounds()); int width, height; if (dR.width < sR.width) width = dR.width; else width = sR.width; if (dR.height < sR.height) height = dR.height; else height = sR.height; int x = sR.x+dx; int [] samples = null; for (int y=sR.y; y< sR.y+height; y++) { samples = src.getSamples(sR.x, y, width, 1, sBand, samples); dst.setSamples(x, y+dy, width, 1, dBand, samples); } } public static boolean is_INT_PACK_Data(SampleModel sm, boolean requireAlpha) { // Check ColorModel is of type DirectColorModel if(!(sm instanceof SinglePixelPackedSampleModel)) return false; // Check transfer type if(sm.getDataType() != DataBuffer.TYPE_INT) return false; SinglePixelPackedSampleModel sppsm; sppsm = (SinglePixelPackedSampleModel)sm; int [] masks = sppsm.getBitMasks(); if (masks.length == 3) { if (requireAlpha) return false; } else if (masks.length != 4) return false; if(masks[0] != 0x00ff0000) return false; if(masks[1] != 0x0000ff00) return false; if(masks[2] != 0x000000ff) return false; if ((masks.length == 4) && (masks[3] != 0xff000000)) return false; return true; } public static boolean is_BYTE_COMP_Data(SampleModel sm) { // Check ColorModel is of type DirectColorModel if(!(sm instanceof ComponentSampleModel)) return false; // Check transfer type if(sm.getDataType() != DataBuffer.TYPE_BYTE) return false; return true; } protected static void divide_INT_PACK_Data(WritableRaster wr) { // System.out.println("Divide Int"); SinglePixelPackedSampleModel sppsm; sppsm = (SinglePixelPackedSampleModel)wr.getSampleModel(); final int width = wr.getWidth(); final int scanStride = sppsm.getScanlineStride(); DataBufferInt db = (DataBufferInt)wr.getDataBuffer(); final int base = (db.getOffset() + sppsm.getOffset(wr.getMinX()-wr.getSampleModelTranslateX(), wr.getMinY()-wr.getSampleModelTranslateY())); int pixel, a, aFP, n=0; // Access the pixel data array final int pixels[] = db.getBankData()[0]; for (int y=0; y<wr.getHeight(); y++) { int sp = base + y*scanStride; final int end = sp + width; while (sp < end) { pixel = pixels[sp]; a = pixel>>>24; if (a<=0) { pixels[sp] = 0x00FFFFFF; } else if (a<255) { aFP = (0x00FF0000/a); pixels[sp] = ((a << 24) | (((((pixel&0xFF0000)>>16)*aFP)&0xFF0000) ) | (((((pixel&0x00FF00)>>8) *aFP)&0xFF0000)>>8 ) | (((((pixel&0x0000FF)) *aFP)&0xFF0000)>>16)); } sp++; } } } protected static void mult_INT_PACK_Data(WritableRaster wr) { // System.out.println("Multiply Int: " + wr); SinglePixelPackedSampleModel sppsm; sppsm = (SinglePixelPackedSampleModel)wr.getSampleModel(); final int width = wr.getWidth(); final int scanStride = sppsm.getScanlineStride(); DataBufferInt db = (DataBufferInt)wr.getDataBuffer(); final int base = (db.getOffset() + sppsm.getOffset(wr.getMinX()-wr.getSampleModelTranslateX(), wr.getMinY()-wr.getSampleModelTranslateY())); int n=0; // Access the pixel data array final int pixels[] = db.getBankData()[0]; for (int y=0; y<wr.getHeight(); y++) { int sp = base + y*scanStride; final int end = sp + width; while (sp < end) { int pixel = pixels[sp]; int a = pixel>>>24; if ((a>=0) && (a<255)) { pixels[sp] = ((a << 24) | ((((pixel&0xFF0000)*a)>>8)&0xFF0000) | ((((pixel&0x00FF00)*a)>>8)&0x00FF00) | ((((pixel&0x0000FF)*a)>>8)&0x0000FF)); } sp++; } } } protected static void divide_BYTE_COMP_Data(WritableRaster wr) { // System.out.println("Multiply Int: " + wr); ComponentSampleModel csm; csm = (ComponentSampleModel)wr.getSampleModel(); final int width = wr.getWidth(); final int scanStride = csm.getScanlineStride(); final int pixStride = csm.getPixelStride(); final int [] bandOff = csm.getBandOffsets(); DataBufferByte db = (DataBufferByte)wr.getDataBuffer(); final int base = (db.getOffset() + csm.getOffset(wr.getMinX()-wr.getSampleModelTranslateX(), wr.getMinY()-wr.getSampleModelTranslateY())); int a=0; int aOff = bandOff[bandOff.length-1]; int bands = bandOff.length-1; int b, i; // Access the pixel data array final byte pixels[] = db.getBankData()[0]; for (int y=0; y<wr.getHeight(); y++) { int sp = base + y*scanStride; final int end = sp + width*pixStride; while (sp < end) { a = pixels[sp+aOff]&0xFF; if (a==0) { for (b=0; b<bands; b++) pixels[sp+bandOff[b]] = (byte)0xFF; } else if (a<255) { int aFP = (0x00FF0000/a); for (b=0; b<bands; b++) { i = sp+bandOff[b]; pixels[i] = (byte)(((pixels[i]&0xFF)*aFP)>>>16); } } sp+=pixStride; } } } protected static void mult_BYTE_COMP_Data(WritableRaster wr) { // System.out.println("Multiply Int: " + wr); ComponentSampleModel csm; csm = (ComponentSampleModel)wr.getSampleModel(); final int width = wr.getWidth(); final int scanStride = csm.getScanlineStride(); final int pixStride = csm.getPixelStride(); final int [] bandOff = csm.getBandOffsets(); DataBufferByte db = (DataBufferByte)wr.getDataBuffer(); final int base = (db.getOffset() + csm.getOffset(wr.getMinX()-wr.getSampleModelTranslateX(), wr.getMinY()-wr.getSampleModelTranslateY())); int a=0; int aOff = bandOff[bandOff.length-1]; int bands = bandOff.length-1; int b, i; // Access the pixel data array final byte pixels[] = db.getBankData()[0]; for (int y=0; y<wr.getHeight(); y++) { int sp = base + y*scanStride; final int end = sp + width*pixStride; while (sp < end) { a = pixels[sp+aOff]&0xFF; if (a!=0xFF) for (b=0; b<bands; b++) { i = sp+bandOff[b]; pixels[i] = (byte)(((pixels[i]&0xFF)*a)>>8); } sp+=pixStride; } } } /* This is skanky debugging code that might be useful in the future: if (count == 33) { String label = "sub [" + x + ", " + y + "]: "; org.ImageDisplay.showImage (label, subBI); org.ImageDisplay.printImage (label, subBI, new Rectangle(75-iR.x, 90-iR.y, 32, 32)); } // if ((count++ % 50) == 10) // org.ImageDisplay.showImage("foo: ", subBI); Graphics2D realG2D = g2d; while (realG2D instanceof sun.java2d.ProxyGraphics2D) { realG2D = ((sun.java2d.ProxyGraphics2D)realG2D).getDelegate(); } if (realG2D instanceof sun.awt.image.BufferedImageGraphics2D) { count++; if (count == 34) { RenderedImage ri; ri = ((sun.awt.image.BufferedImageGraphics2D)realG2D).bufImg; // g2d.setComposite(SVGComposite.OVER); // org.ImageDisplay.showImage("Bar: " + count, cr); org.ImageDisplay.printImage("Bar: " + count, cr, new Rectangle(75, 90, 32, 32)); org.ImageDisplay.showImage ("Foo: " + count, ri); org.ImageDisplay.printImage("Foo: " + count, ri, new Rectangle(75, 90, 32, 32)); System.out.println("BI: " + ri); System.out.println("BISM: " + ri.getSampleModel()); System.out.println("BICM: " + ri.getColorModel()); System.out.println("BICM class: " + ri.getColorModel().getClass()); System.out.println("BICS: " + ri.getColorModel().getColorSpace()); System.out.println ("sRGB CS: " + ColorSpace.getInstance(ColorSpace.CS_sRGB)); System.out.println("G2D info"); System.out.println("\tComposite: " + g2d.getComposite()); System.out.println("\tTransform" + g2d.getTransform()); java.awt.RenderingHints rh = g2d.getRenderingHints(); java.util.Set keys = rh.keySet(); java.util.Iterator iter = keys.iterator(); while (iter.hasNext()) { Object o = iter.next(); System.out.println("\t" + o.toString() + " -> " + rh.get(o).toString()); } ri = cr; System.out.println("RI: " + ri); System.out.println("RISM: " + ri.getSampleModel()); System.out.println("RICM: " + ri.getColorModel()); System.out.println("RICM class: " + ri.getColorModel().getClass()); System.out.println("RICS: " + ri.getColorModel().getColorSpace()); } } */ }
package com.parse; import com.facebook.stetho.inspector.network.DefaultResponseHandler; import com.facebook.stetho.inspector.network.NetworkEventReporter; import com.facebook.stetho.inspector.network.NetworkEventReporterImpl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * {@code ParseStethoInterceptor} is used to log the request and response through Stetho to chrome * browser debugger. */ /** package */ class ParseStethoInterceptor implements ParseNetworkInterceptor { private static final String CONTENT_LENGTH_HEADER = "Content-Length"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; // Implementation of Stetho request private static class ParseInterceptorHttpRequest implements NetworkEventReporter.InspectorRequest { private final String requestId; private final ParseHttpRequest request; private byte[] body; private boolean hasGeneratedBody; // Since Stetho use index to get header, we use a list to store them private List<String> headers; public ParseInterceptorHttpRequest(String requestId, ParseHttpRequest request) { this.requestId = requestId; this.request = request; // Add content-length and content-type header to the interceptor. These headers are added when // a real httpclient send the request. Since we still want users to see these headers, we // manually add them to Interceptor request if they are not in the header list headers = new ArrayList<>(); for (Map.Entry<String, String> headerEntry : request.getAllHeaders().entrySet()) { headers.add(headerEntry.getKey()); headers.add(headerEntry.getValue()); } if (request.getBody() != null) { if (!headers.contains(CONTENT_LENGTH_HEADER)) { headers.add(CONTENT_LENGTH_HEADER); headers.add(String.valueOf(request.getBody().getContentLength())); } // If user does not set contentType when create ParseFile, it may be null if (request.getBody().getContentType() != null && !headers.contains(CONTENT_TYPE_HEADER)) { headers.add(CONTENT_TYPE_HEADER); headers.add(request.getBody().getContentType()); } } } @Override public String id() { return requestId; } @Override public String friendlyName() { return null; } @Nullable @Override public Integer friendlyNameExtra() { return null; } @Override public String url() { return request.getUrl(); } @Override public String method() { return request.getMethod().toString(); } @Nullable @Override public byte[] body() throws IOException { if (!hasGeneratedBody) { hasGeneratedBody = true; body = generateBody(); } return body; } private byte[] generateBody() throws IOException { ParseHttpBody body = request.getBody(); if (body == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); body.writeTo(out); return out.toByteArray(); } @Override public int headerCount() { return headers.size() / 2; } @Override public String headerName(int index) { return headers.get(index * 2); } @Override public String headerValue(int index) { return headers.get(index * 2 + 1); } @Nullable @Override public String firstHeaderValue(String name) { int index = headers.indexOf(name); return index >= 0 ? headers.get(index + 1) : null; } } // Implementation of Stetho response private static class ParseInspectorHttpResponse implements NetworkEventReporter.InspectorResponse { private final String requestId; private final ParseHttpRequest request; private final ParseHttpResponse response; // Since stetho use index to get header, we use a list to store them private List<String> responseHeaders; public ParseInspectorHttpResponse( String requestId, ParseHttpRequest request, ParseHttpResponse response) { this.requestId = requestId; this.request = request; this.response = response; responseHeaders = new ArrayList<>(); for (Map.Entry<String, String> headerEntry : response.getAllHeaders().entrySet()) { responseHeaders.add(headerEntry.getKey()); responseHeaders.add(headerEntry.getValue()); } } @Override public String requestId() { return requestId; } @Override public String url() { return request.getUrl(); } @Override public int statusCode() { return response.getStatusCode(); } @Override public String reasonPhrase() { return response.getReasonPhrase(); } @Override public boolean connectionReused() { // Follow Stetho URLConnectionInspectorResponse return false; } @Override public int connectionId() { // Follow Stetho URLConnectionInspectorResponse return requestId.hashCode(); } @Override public boolean fromDiskCache() { // Follow Stetho URLConnectionInspectorResponse return false; } @Override public int headerCount() { return response.getAllHeaders().size(); } @Override public String headerName(int index) { return responseHeaders.get(index * 2); } @Override public String headerValue(int index) { return responseHeaders.get(index * 2 + 1); } @Nullable @Override public String firstHeaderValue(String name) { int index = responseHeaders.indexOf(name); return index >= 0 ? responseHeaders.get(index + 1) : null; } } // Stetho reporter private final NetworkEventReporter stethoEventReporter = NetworkEventReporterImpl.get(); // Request Id generator private final AtomicInteger nextRequestId = new AtomicInteger(0); @Override public ParseHttpResponse intercept(Chain chain) throws IOException { // Intercept request String requestId = String.valueOf(nextRequestId.getAndIncrement()); ParseHttpRequest request = chain.getRequest(); // If Stetho debugger is available (chrome debugger is open), intercept the request if (stethoEventReporter.isEnabled()) { ParseInterceptorHttpRequest inspectorRequest = new ParseInterceptorHttpRequest(requestId, chain.getRequest()); stethoEventReporter.requestWillBeSent(inspectorRequest); } ParseHttpResponse response; try { response = chain.proceed(request); } catch (IOException e) { // If Stetho debugger is available (chrome debugger is open), intercept the exception if (stethoEventReporter.isEnabled()) { stethoEventReporter.httpExchangeFailed(requestId, e.toString()); } throw e; } if (stethoEventReporter.isEnabled()) { // If Stetho debugger is available (chrome debugger is open), intercept the response body if (request.getBody() != null) { stethoEventReporter.dataSent(requestId, (int)(request.getBody().getContentLength()), (int)(request.getBody().getContentLength())); } // If Stetho debugger is available (chrome debugger is open), intercept the response headers stethoEventReporter.responseHeadersReceived( new ParseInspectorHttpResponse(requestId, request, response)); InputStream responseStream = null; if (response.getContent() != null) { responseStream = response.getContent(); } // Create the Stetho proxy inputStream, when Parse read this stream, it will proxy the // response body to Stetho reporter. responseStream = stethoEventReporter.interpretResponseStream( requestId, response.getContentType(), response.getAllHeaders().get("Content-Encoding"), responseStream, new DefaultResponseHandler(stethoEventReporter, requestId) ); if (responseStream != null) { response = response.newBuilder() .setContent(responseStream) .build(); } } return response; } }
package org.spine3.examples.todolist.client; import com.google.protobuf.Timestamp; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.spine3.examples.todolist.LabelId; import org.spine3.examples.todolist.TaskId; import org.spine3.examples.todolist.c.commands.AssignLabelToTask; import org.spine3.examples.todolist.c.commands.CreateBasicLabel; import org.spine3.examples.todolist.c.commands.CreateBasicTask; import org.spine3.examples.todolist.c.commands.CreateDraft; import org.spine3.examples.todolist.c.commands.UpdateTaskDueDate; import org.spine3.examples.todolist.q.projection.LabelledTasksView; import org.spine3.examples.todolist.q.projection.TaskView; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskDueDateInstance; import static org.spine3.examples.todolist.testdata.TestTaskLabelsCommandFactory.assignLabelToTaskInstance; import static org.spine3.protobuf.Timestamps2.getCurrentTime; /** * @author Illia Shepilov */ @DisplayName("After execution of UpdateTaskDueDate command") public class UpdateTaskDueDateTest extends CommandLineTodoClientTest { private TodoClient client; @BeforeEach @Override public void setUp() throws InterruptedException { super.setUp(); client = getClient(); } @Nested @DisplayName("LabelledTasksView should") class UpdateTaskDueDateInLabelledTasksView { @Test @DisplayName("contain the task view with updated due date") public void containUpdatedView() { final Timestamp newDueDate = getCurrentTime(); final TaskView view = obtainViewWhenHandledCommandUpdateTaskDueDate(newDueDate, true); assertEquals(newDueDate, view.getDueDate()); } @Test @DisplayName("contain the task view with not updated due date when command has wrong task ID") public void containNotUpdatedView() { final Timestamp newDueDate = getCurrentTime(); final TaskView view = obtainViewWhenHandledCommandUpdateTaskDueDate(newDueDate, false); assertNotEquals(newDueDate, view.getDueDate()); } } @Nested @DisplayName("DraftTasksView should") class UpdateTaskDueDateInDraftTasksView { @Test @DisplayName("contain the task view with updated due date") public void containUpdatedView() { final Timestamp newDueDate = getCurrentTime(); final TaskView view = obtainViewWhenHandledUpdateTaskDueDate(newDueDate, true); assertEquals(newDueDate, view.getDueDate()); } @Test @DisplayName("contain the task view with not updated due date when command has wrong task ID") public void containNotUpdatedView() { final Timestamp newDueDate = getCurrentTime(); final TaskView view = obtainViewWhenHandledUpdateTaskDueDate(newDueDate, false); assertNotEquals(newDueDate, view.getDueDate()); } } @Nested @DisplayName("MyListView should") class UpdateTaskDueDateInMyListView { @Test @DisplayName("contain the task view with updated due date") public void containUpdatedView() { final Timestamp newDueDate = getCurrentTime(); final TaskView view = obtainTaskViewWhenHandledUpdateTaskDueDate(newDueDate, true); assertEquals(newDueDate, view.getDueDate()); } @Test @DisplayName("contain task view with not updated due date when command has wrong task ID") public void containNotUpdatedView() { final Timestamp newDueDate = getCurrentTime(); final TaskView view = obtainTaskViewWhenHandledUpdateTaskDueDate(newDueDate, false); assertNotEquals(newDueDate, view.getDueDate()); } } private TaskView obtainTaskViewWhenHandledUpdateTaskDueDate(Timestamp newDueDate, boolean isCorrectId) { final CreateBasicTask createTask = createBasicTask(); client.create(createTask); final TaskId idOfCreatedTask = createTask.getId(); updateDueDate(newDueDate, isCorrectId, idOfCreatedTask); final List<TaskView> taskViews = client.getMyListView() .getMyList() .getItemsList(); assertEquals(1, taskViews.size()); final TaskView view = taskViews.get(0); assertEquals(idOfCreatedTask, view.getId()); return view; } private TaskView obtainViewWhenHandledUpdateTaskDueDate(Timestamp newDueDate, boolean isCorrectId) { final CreateDraft createDraft = createDraft(); client.create(createDraft); final TaskId createdTaskId = createDraft.getId(); updateDueDate(newDueDate, isCorrectId, createdTaskId); final List<TaskView> taskViews = client.getDraftTasksView() .getDraftTasks() .getItemsList(); assertEquals(1, taskViews.size()); final TaskView view = taskViews.get(0); assertEquals(createdTaskId, view.getId()); return view; } private TaskView obtainViewWhenHandledCommandUpdateTaskDueDate(Timestamp newDueDate, boolean isCorrectId) { final CreateBasicTask createTask = createBasicTask(); final TaskId createdTaskId = createTask.getId(); client.create(createTask); final CreateBasicLabel createLabel = createBasicLabel(); client.create(createLabel); final TaskId taskId = createTask.getId(); final LabelId labelId = createLabel.getLabelId(); final AssignLabelToTask assignLabelToTask = assignLabelToTaskInstance(taskId, labelId); client.assignLabel(assignLabelToTask); updateDueDate(newDueDate, isCorrectId, createdTaskId); final List<LabelledTasksView> tasksViewList = client.getLabelledTasksView(); final int expectedListSize = 1; assertEquals(expectedListSize, tasksViewList.size()); final List<TaskView> taskViews = tasksViewList.get(0) .getLabelledTasks() .getItemsList(); assertEquals(expectedListSize, taskViews.size()); final TaskView view = taskViews.get(0); assertEquals(labelId, view.getLabelId()); assertEquals(taskId, view.getId()); return view; } private void updateDueDate(Timestamp newDueDate, boolean isCorrectId, TaskId idOfCreatedTask) { final TaskId idOfUpdatedTask = isCorrectId ? idOfCreatedTask : createWrongTaskId(); final Timestamp previousDueDate = Timestamp.getDefaultInstance(); final UpdateTaskDueDate updateTaskDueDate = updateTaskDueDateInstance(idOfUpdatedTask, previousDueDate, newDueDate); client.update(updateTaskDueDate); } }
package com.stanfy.images; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.regex.Pattern; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.TextView; import com.stanfy.DebugFlags; import com.stanfy.images.model.CachedImage; import com.stanfy.views.ImagesLoadListenerProvider; import com.stanfy.views.LoadableImageView; import com.stanfy.views.LoadableTextView; import com.stanfy.views.RemoteImageDensityProvider; import com.stanfy.views.utils.AppUtils; public class ImagesManager<T extends CachedImage> { /** Logging tag. */ private static final String TAG = "ImagesManager"; /** Pattern to cut the images sources from HTML. */ protected static final Pattern IMG_URL_PATTERN = Pattern.compile("<img.*?src=\"(.*?)\".*?>"); /** Debug flag. */ private static final boolean DEBUG_IO = DebugFlags.DEBUG_IO; /** Debug flag. */ private static final boolean DEBUG = DebugFlags.DEBUG_IMAGES; /** Empty drawable. */ protected static final ColorDrawable EMPTY_DRAWABLE = new ColorDrawable(0xeeeeee); /** Memory cache. */ private ImageMemoryCache memCache; /** Buffers pool. */ private final BuffersPool buffersPool = new BuffersPool(new int[][] { {4, BuffersPool.DEFAULT_SIZE_FOR_IMAGES} }); /** Resources. */ private final Resources resources; /** Target density from source. */ private int sourceDensity = 0; /** Images format. */ private Bitmap.Config imagesFormat = Bitmap.Config.RGB_565; /** Current loads. */ private final ConcurrentHashMap<String, ImageLoader<T>> currentLoads = new ConcurrentHashMap<String, ImageLoader<T>>(Threading.imagesWorkersCount); /** Paused state. */ private boolean paused = false; /** Hidden constructor. */ public ImagesManager(final Resources resources) { this.resources = resources; } /** @param memCache the memCache to set */ public void setMemCache(final ImageMemoryCache memCache) { this.memCache = memCache; } /** @param imagesFormat the imagesFormat to set */ public void setImagesFormat(final Bitmap.Config imagesFormat) { this.imagesFormat = imagesFormat; } /** @param sourceDensity the sourceDensity to set */ public void setSourceDensity(final int sourceDensity) { this.sourceDensity = sourceDensity; } /** * Ensure that all the images are loaded. Not loaded images will be downloaded in this thread. * @param imagesDao images DAO * @param downloader downloader instance * @param context context instance * @param images images collection */ public void ensureImages(final ImagesDAO<T> imagesDao, final Downloader downloader, final Context context, final List<T> images) { final File imagesDir = getImageDir(context); for (final T image : images) { if (image.isLoaded() && new File(imagesDir, image.getPath()).exists()) { continue; } try { makeImageLocal(imagesDao, context, image, downloader); } catch (final IOException e) { if (DEBUG_IO) { Log.e(TAG, "IO error for " + image.getUrl() + ": " + e.getMessage()); } } } } /** * Clear the cached entities. * @param context context instance * @param path image file system path * @param url image URL * @return size of the deleted file */ public long clearCache(final Context context, final String path, final String url) { memCache.remove(url, false); long size = 0; if (path != null) { final File f = new File(getImageDir(context), path); size = f.length(); delete(f); } return size; } /** * Flush resources. */ public void flush() { memCache.clear(false); buffersPool.flush(); } /** * Populate the requested image to the specified view. Called from the GUI thread. * @param view view instance * @param url image URL * @param imagesDAO images DAO * @param downloader downloader instance */ public void populateImage(final View view, final String url, final ImagesManagerContext<T> imagesContext) { final Object tag = view.getTag(); ImageHolder imageHolder = null; if (tag == null) { imageHolder = createImageHolder(view); view.setTag(imageHolder); } else { if (!(tag instanceof ImageHolder)) { throw new IllegalStateException("View already has a tag " + tag); } imageHolder = (ImageHolder)tag; } populateImage(imageHolder, url, imagesContext); } /** * Cancel image loading for a view. * @param view view that hold an image */ public void cancelImageLoading(final View view) { final Object tag = view.getTag(); if (tag != null && tag instanceof ImageHolder) { cancelImageLoading((ImageHolder)tag); } } /** * Cancel image loading for a holder. * @param holder image holder instance */ public void cancelImageLoading(final ImageHolder holder) { holder.performCancellingLoader(); } protected ImageHolder createImageHolder(final View view) { if (view instanceof LoadableImageView) { return new LoadableImageViewHolder((LoadableImageView)view); } if (view instanceof ImageView) { return new ImageViewHolder((ImageView)view); } if (view instanceof CompoundButton) { return new CompoundButtonHolder((CompoundButton)view); } if (view instanceof TextView) { return new TextViewHolder((TextView)view); } return null; } /** * @param url image URL * @return true if image is cached in memory */ public boolean isMemCached(final String url) { return memCache.contains(url); } /** * @param url image URL * @param view that contains an image holder * @return image bitmap from memory cache */ public Drawable getMemCached(final String url, final View view) { final Object tag = view.getTag(); if (tag == null || !(tag instanceof ImageHolder)) { return null; } final Drawable res = getFromMemCache(url, (ImageHolder)tag); if (res == null) { return null; } return decorateDrawable((ImageHolder)tag, res); } public void populateImage(final ImageHolder imageHolder, final String url, final ImagesManagerContext<T> imagesContext) { if (DEBUG) { Log.d(TAG, "Process url" + url); } if (TextUtils.isEmpty(url)) { setLoadingImage(imageHolder); return; } imageHolder.performCancellingLoader(); final Drawable memCached = getFromMemCache(url, imageHolder); if (memCached != null) { imageHolder.onStart(null, url); setImage(imageHolder, memCached, false); imageHolder.onFinish(url, memCached); return; } if (DEBUG) { Log.d(TAG, "Set loading for " + url); } setLoadingImage(imageHolder); imageHolder.currentUrl = url; // we are in GUI thread startImageLoaderTask(imageHolder, imagesContext); } private void setLoadingImage(final ImageHolder holder) { if (!holder.skipLoadingImage()) { final Drawable d = !holder.isDynamicSize() ? getLoadingDrawable(holder) : null; setImage(holder, d, true); } } /** * @param image image to process * @return local file system path to that image */ public String setCachedImagePath(final T image) { if (image.getPath() != null) { return image.getPath(); } final long id = image.getId(); final String path = AppUtils.buildFilePathById(id, "image-" + id); image.setPath(path); return path; } /** * @return an executor for image tasks */ protected Executor getImageTaskExecutor() { return Threading.getImageTasksExecutor(); } /** * @param context context * @return a drawable to display while the image is loading */ protected Drawable getLoadingDrawable(final ImageHolder holder) { final Drawable d = holder.getLoadingImage(); return d != null ? d : EMPTY_DRAWABLE; } /** * @param context context instance * @param drawable resulting drawable * @return decorated drawable */ protected Drawable decorateDrawable(final ImageHolder holder, final Drawable drawable) { return drawable; } /** * @param imageView image view instance * @param drawable incoming drawable * @param preloader preloading image flag */ protected final void setImage(final ImageHolder imageHolder, final Drawable drawable, final boolean preloader) { final Drawable d = decorateDrawable(imageHolder, drawable); if (preloader) { imageHolder.setLoadingImage(d); } else { imageHolder.setImage(d); } synchronized (imageHolder) { imageHolder.reset(); } } /** * @param url image URL * @return cached drawable */ protected Drawable getFromMemCache(final String url, final ImageHolder holder) { synchronized (holder) { if (holder.currentUrl != null && !holder.currentUrl.equals(url)) { return null; } } final Bitmap map = memCache.getElement(url); if (map == null) { return null; } final BitmapDrawable result = new BitmapDrawable(holder.context.getResources(), map); final int gap = 5; return holder.isDynamicSize() || holder.skipScaleBeforeCache() || Math.abs(holder.getRequiredWidth() - result.getIntrinsicWidth()) < gap || Math.abs(holder.getRequiredHeight() - result.getIntrinsicHeight()) < gap ? result : null; } /** * @param imageHolder image holder to process * @param imagesDAO images DAO * @param downloader downloader instance * @return loader task instance */ protected void startImageLoaderTask(final ImageHolder imageHolder, final ImagesManagerContext<T> imagesContext) { final String key = imageHolder.getLoaderKey(); if (DEBUG) { Log.d(TAG, "Key " + key); } ImageLoader<T> loader = currentLoads.get(key); if (loader != null) { final boolean added = loader.addTarget(imageHolder); if (!added) { loader = null; } } if (loader == null) { if (DEBUG) { Log.d(TAG, "Start a new task"); } loader = new ImageLoader<T>(imageHolder.currentUrl, key, imagesContext); final boolean added = loader.addTarget(imageHolder); if (!added) { throw new IllegalStateException("Cannot add target to the new loader"); } currentLoads.put(key, loader); final Executor executor = getImageTaskExecutor(); executor.execute(loader.future); } else if (DEBUG) { Log.d(TAG, "Joined to the existing task"); } } /** * @param context context instance * @return base dir to save images */ public File getImageDir(final Context context) { final String eState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(eState)) { return AppUtils.getSdkDependentUtils().getExternalCacheDir(context); } return context.getCacheDir(); } private static void delete(final File file) { if (!file.exists()) { return; } final File parent = file.getParentFile(); if (file.delete()) { delete(parent); } } protected void makeImageLocal(final ImagesDAO<T> imagesDao, final Context context, final T image, final Downloader downloader) throws IOException { final String path = setCachedImagePath(image); final File f = new File(getImageDir(context), path); final File parent = f.getParentFile(); parent.mkdirs(); if (!parent.exists()) { Log.e(TAG, "Directories not created for " + f.getParent() + ". Local image won't be saved."); return; } final InputStream in = new PoolableBufferedInputStream(downloader.download(image.getUrl()), BuffersPool.DEFAULT_SIZE_FOR_IMAGES, buffersPool); final FileOutputStream out = new FileOutputStream(f); final byte[] buffer = buffersPool.get(BuffersPool.DEFAULT_SIZE_FOR_IMAGES); if (buffer == null) { return; } int cnt; try { do { cnt = in.read(buffer); if (cnt != -1) { out.write(buffer, 0, cnt); } } while (cnt != -1); } finally { in.close(); out.close(); buffersPool.release(buffer); } downloader.finish(image.getUrl()); image.setLoaded(true); final long time = System.currentTimeMillis(); image.setTimestamp(time); image.setUsageTimestamp(time); imagesDao.updateImage(image); } protected void memCacheImage(final String url, final Drawable d) { if (d instanceof BitmapDrawable) { if (DEBUG) { Log.d(TAG, "Memcache for " + url); } memCache.putElement(url, ((BitmapDrawable)d).getBitmap()); } } protected void setupDensityAndFormat(final BitmapFactory.Options options, final int sourceDensity) { options.inDensity = sourceDensity > 0 ? sourceDensity : this.sourceDensity; options.inPreferredConfig = imagesFormat; } protected Drawable readLocal(final T cachedImage, final Context context, final ImageHolder holder) throws IOException { final File file = new File(getImageDir(context), cachedImage.getPath()); if (!file.exists()) { if (DEBUG_IO) { Log.w(TAG, "Local file " + file.getAbsolutePath() + "does not exist."); } return null; } final BitmapFactory.Options options = new BitmapFactory.Options(); if (holder.useSampling() && !holder.isDynamicSize()) { options.inSampleSize = resolveSampleFactor(new FileInputStream(file), holder.getSourceDensity(), holder.getRequiredWidth(), holder.getRequiredHeight()); } final Drawable d = decodeStream(new FileInputStream(file), holder.getSourceDensity(), options); return d; } private InputStream prepareImageOptionsAndInput(final InputStream is, final int sourceDensity, final BitmapFactory.Options options) { final BuffersPool bp = buffersPool; final int bCapacity = BuffersPool.DEFAULT_SIZE_FOR_IMAGES; InputStream src = new FlushedInputStream(is); if (!src.markSupported()) { src = new PoolableBufferedInputStream(src, bCapacity, bp); } final BitmapFactory.Options opts = options != null ? options : new BitmapFactory.Options(); opts.inTempStorage = bp.get(bCapacity); setupDensityAndFormat(opts, sourceDensity); return src; } private void onImageDecodeFinish(final InputStream src, final BitmapFactory.Options opts) throws IOException { buffersPool.release(opts.inTempStorage); src.close(); } static int nearestPowerOf2(final int value) { if (value <= 0) { return -1; } int result = -1, x = value; while (x > 0) { ++result; x >>>= 1; } return 1 << result; } protected int resolveSampleFactor(final InputStream is, final int sourceDensity, final int width, final int height) throws IOException { final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; final InputStream src = prepareImageOptionsAndInput(is, sourceDensity, opts); int result = 1; try { BitmapFactory.decodeResourceStream(null, null, src, null, opts); final int inW = opts.outWidth, inH = opts.outHeight; if (inW > width || inH > height) { final int factor = inW > inH ? inW / width : inH / height; if (factor > 1) { result = factor; final int p = nearestPowerOf2(factor); final int maxDistance = 3; if (result - p < maxDistance) { result = p; } if (DEBUG) { Log.d(TAG, "Sampling: factor=" + factor + ", p=" + p + ", result=" + result); } } } } finally { // recycle onImageDecodeFinish(src, opts); } return result; } protected Drawable decodeStream(final InputStream is, final int sourceDensity, final BitmapFactory.Options options) throws IOException { final BitmapFactory.Options opts = options != null ? options : new BitmapFactory.Options(); final InputStream src = prepareImageOptionsAndInput(is, sourceDensity, opts); try { final Bitmap bm = BitmapFactory.decodeResourceStream(null, null, src, null, opts); final Drawable res = bm != null ? new BitmapDrawable(resources, bm) : null; if (DEBUG) { Log.d(TAG, "Image decoded: " + opts.outWidth + "x" + opts.outHeight + ", res=" + res); } return res; } catch (final OutOfMemoryError e) { // I know, it's bad to catch error but files can be VERY big! return null; } finally { // recycle onImageDecodeFinish(src, opts); } } /** * This our barrier for images loading tasks. * @return true if task can continue it's work and false if it's interrupted */ synchronized boolean waitForPause() { try { while (paused) { wait(); } return true; } catch (final InterruptedException e) { return false; } } /** * Pause all future loading tasks. */ public synchronized void pauseLoading() { this.paused = true; } /** * Resume all the loading tasks. */ public synchronized void resumeLoading() { this.paused = false; notifyAll(); } protected static class ImageLoader<T extends CachedImage> implements Callable<Void> { /** Image URL. */ private final String url; /** Loader key. */ private final String key; /** Images manager. */ private final ImagesManager<T> imagesManager; /** Images DAO. */ private final ImagesDAO<T> imagesDAO; /** Downloader. */ private final Downloader downloader; /** Future task instance. */ final FutureTask<Void> future; /** Targets. */ private final ArrayList<ImageHolder> targets = new ArrayList<ImageHolder>(); /** Main GUI view. */ private ImageHolder mainTarget; /** Result drawable. */ private Drawable resultDrawable; /** Resolved result flag. */ private boolean resultResolved = false, started = false; public ImageLoader(final String url, final String key, final ImagesManagerContext<T> imagesContext) { this.url = url; this.key = key; this.imagesManager = imagesContext.getImagesManager(); this.downloader = imagesContext.getDownloader(); this.imagesDAO = imagesContext.getImagesDAO(); this.future = new FutureTask<Void>(this); } /** Called from UI thread. */ public boolean addTarget(final ImageHolder imageHolder) { if (future.isCancelled()) { return false; } // we should start a new task if (!future.isDone()) { // normal case synchronized (this) { if (started) { imageHolder.onStart(this, url); } if (resultResolved) { imagesManager.setImage(imageHolder, resultDrawable, false); imageHolder.onFinish(url, resultDrawable); } else { imageHolder.currentLoader = this; targets.add(imageHolder); if (mainTarget == null) { mainTarget = imageHolder; } } } } else { // we finished imagesManager.setImage(imageHolder, resultDrawable, false); } return true; } public void removeTarget(final ImageHolder imageHolder) { imageHolder.onCancel(url); synchronized (this) { targets.remove(imageHolder); if (targets.isEmpty()) { future.cancel(true); } } } protected void safeImageSet(final T cachedImage, final Drawable source) { final Drawable d; synchronized (this) { resultResolved = true; if (source == null) { return; } d = memCacheImage(source); resultDrawable = d; } final String url = this.url; mainTarget.post(new Runnable() { @Override public void run() { final ArrayList<ImageHolder> targets = ImageLoader.this.targets; final int count = targets.size(); if (count > 0) { for (int i = 0; i < count; i++) { final ImageHolder imageHolder = targets.get(i); if (DEBUG) { Log.d(TAG, "Try to set " + imageHolder + " - " + url); } setImageToHolder(imageHolder, d); } } else if (DEBUG) { Log.w(TAG, "set drawable: have no targets in list"); } } }); } private void setImageToHolder(final ImageHolder imageHolder, final Drawable d) { synchronized (imageHolder) { final String currentUrl = imageHolder.currentUrl; if (currentUrl != null && currentUrl.equals(url)) { imagesManager.setImage(imageHolder, d, false); } else { if (DEBUG) { Log.d(TAG, "Skip set for " + imageHolder); } } } } protected Drawable setLocalImage(final T cachedImage) throws IOException { final Context x = mainTarget.context; if (x == null) { throw new IOException("Context is null"); } final Drawable d = imagesManager.readLocal(cachedImage, x, mainTarget); if (d != null) { imagesDAO.updateUsageTimestamp(cachedImage); } safeImageSet(cachedImage, d); return d; } protected Drawable setRemoteImage(final T cachedImage) throws IOException { if (!url.startsWith("http")) { return null; } final Context x = mainTarget.context; if (x == null) { throw new IOException("Context is null"); } cachedImage.setType(mainTarget.getImageType()); imagesManager.makeImageLocal(imagesDAO, x, cachedImage, downloader); return setLocalImage(cachedImage); } private BitmapDrawable prepare(final BitmapDrawable bd) { int dstW = mainTarget.getRequiredWidth(), dstH = mainTarget.getRequiredHeight(); if (dstW <= 0 || dstH <= 0 || mainTarget.skipScaleBeforeCache()) { if (DEBUG) { Log.d(TAG, "Skip scaling for " + mainTarget + " skip flag: " + mainTarget.skipScaleBeforeCache()); } return bd; } final Bitmap map = bd.getBitmap(); final int w = bd.getIntrinsicWidth(), h = bd.getIntrinsicHeight(); if (w <= dstW && h <= dstH) { return bd; } final double ratio = (double)w / h; if (w > h) { dstH = (int)(dstW / ratio); } else { dstW = (int)(dstH * ratio); } if (dstW <= 0 || dstH <= 0) { return bd; } final Bitmap scaled = Bitmap.createScaledBitmap(map, dstW, dstH, true); scaled.setDensity(imagesManager.resources.getDisplayMetrics().densityDpi); return new BitmapDrawable(imagesManager.resources, scaled); } private Drawable memCacheImage(final Drawable d) { Drawable result = d; if (d instanceof BitmapDrawable) { final BitmapDrawable bmd = (BitmapDrawable)d; result = prepare(bmd); if (result != bmd) { bmd.getBitmap().recycle(); } } imagesManager.memCacheImage(url, result); return result; } private void start() { synchronized (this) { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final String url = this.url; for (int i = 0; i < count; i++) { targets.get(i).onStart(this, url); } started = true; } } private void finish() { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final Drawable d = this.resultDrawable; for (int i = 0; i < count; i++) { targets.get(i).onFinish(url, d); } } private void cancel() { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final String url = this.url; for (int i = 0; i < count; i++) { targets.get(i).onCancel(url); } } private void error(final Throwable e) { final ArrayList<ImageHolder> targets = this.targets; final int count = targets.size(); final String url = this.url; for (int i = 0; i < count; i++) { targets.get(i).onError(url, e); } } @Override public Void call() { if (DEBUG) { Log.d(TAG, "Start image task"); } final String url = this.url; try { start(); if (!imagesManager.waitForPause()) { cancel(); return null; } T cachedImage = imagesDAO.getCachedImage(url); if (cachedImage == null) { cachedImage = imagesDAO.createCachedImage(url); if (cachedImage == null) { Log.w(TAG, "Cached image info was not created for " + url); return null; } } Drawable d = null; if (cachedImage.isLoaded()) { if (Thread.interrupted()) { cancel(); return null; } d = setLocalImage(cachedImage); if (DEBUG) { Log.d(TAG, "Image " + cachedImage.getId() + "-local"); } } if (d == null) { if (Thread.interrupted()) { cancel(); return null; } d = setRemoteImage(cachedImage); if (DEBUG) { Log.d(TAG, "Image " + cachedImage.getId() + "-remote"); } } if (d == null) { Log.w(TAG, "Image " + cachedImage.getUrl() + " is not resolved"); } finish(); } catch (final MalformedURLException e) { Log.e(TAG, "Bad URL: " + url + ". Loading canceled.", e); error(e); } catch (final IOException e) { if (DEBUG_IO) { Log.e(TAG, "IO error for " + url + ": " + e.getMessage()); } error(e); } catch (final Exception e) { Log.e(TAG, "Cannot load image " + url, e); error(e); } finally { final boolean removed = imagesManager.currentLoads.remove(key, this); if (!removed && DEBUG) { Log.w(TAG, "Incorrect loader in currents for " + key); } } return null; } } static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(final InputStream inputStream) { super(inputStream); } @Override public long skip(final long n) throws IOException { long totalBytesSkipped = 0L; final InputStream in = this.in; while (totalBytesSkipped < n) { long bytesSkipped = in.skip(n - totalBytesSkipped); if (bytesSkipped == 0L) { final int b = read(); if (b < 0) { break; // we reached EOF } else { bytesSkipped = 1; // we read one byte } } totalBytesSkipped += bytesSkipped; } return totalBytesSkipped; } } public abstract static class ImageHolder { /** Context instance. */ Context context; /** Current image URL. Set this field from the GUI thread only! */ String currentUrl; /** Listener. */ ImagesLoadListener listener; /** Current loader. */ ImageLoader<?> currentLoader; /** Loader key. */ private String loaderKey; /** @param context context instance */ public ImageHolder(final Context context) { this.context = context; reset(); } /* access */ /** @param listener the listener to set */ public final void setListener(final ImagesLoadListener listener) { this.listener = listener; } /** @return the context */ public Context getContext() { return context; } /* actions */ void reset() { currentUrl = null; loaderKey = null; } public void touch() { } public abstract void setImage(final Drawable d); public void setLoadingImage(final Drawable d) { setImage(d); } public abstract void post(final Runnable r); public void destroy() { context = null; } final void performCancellingLoader() { final String url = currentUrl; if (DEBUG) { Log.d(TAG, "Cancel " + url); } if (url != null) { final ImageLoader<?> loader = this.currentLoader; if (loader != null) { loader.removeTarget(this); } } } final void onStart(final ImageLoader<?> loader, final String url) { this.currentLoader = loader; if (listener != null) { listener.onLoadStart(this, url); } } final void onFinish(final String url, final Drawable drawable) { this.currentLoader = null; if (listener != null) { listener.onLoadFinished(this, url, drawable); } } final void onError(final String url, final Throwable exception) { this.currentLoader = null; if (listener != null) { listener.onLoadError(this, url, exception); } } final void onCancel(final String url) { this.currentLoader = null; if (listener != null) { listener.onLoadCancel(this, url); } this.currentUrl = null; } /* parameters */ public abstract int getRequiredWidth(); public abstract int getRequiredHeight(); public boolean isDynamicSize() { return getRequiredWidth() <= 0 || getRequiredHeight() <= 0; } public Drawable getLoadingImage() { return null; } public int getImageType() { return 0; } public int getSourceDensity() { return -1; } String getLoaderKey() { if (loaderKey == null) { loaderKey = currentUrl + "!" + getRequiredWidth() + "x" + getRequiredWidth(); } return loaderKey; } /* options */ public boolean skipScaleBeforeCache() { return false; } public boolean skipLoadingImage() { return false; } public boolean useSampling() { return false; } } public abstract static class ViewImageHolder<T extends View> extends ImageHolder { /** View instance. */ T view; public ViewImageHolder(final T view) { super(view.getContext()); this.view = view; touch(); } @Override public int getSourceDensity() { if (view instanceof RemoteImageDensityProvider) { return ((RemoteImageDensityProvider)view).getSourceDensity(); } return super.getSourceDensity(); } @Override public void touch() { final T view = this.view; if (view != null && view instanceof ImagesLoadListenerProvider) { this.listener = ((ImagesLoadListenerProvider)view).getImagesLoadListener(); } } @Override public void post(final Runnable r) { if (context instanceof Activity) { ((Activity)context).runOnUiThread(r); } else { view.post(r); } } @Override public int getRequiredHeight() { final View view = this.view; final LayoutParams params = view.getLayoutParams(); if (params == null || params.height == LayoutParams.WRAP_CONTENT) { return -1; } final int h = view.getHeight(); return h > 0 ? h : params.height; } @Override public int getRequiredWidth() { final View view = this.view; final LayoutParams params = view.getLayoutParams(); if (params == null || params.width == LayoutParams.WRAP_CONTENT) { return -1; } final int w = view.getWidth(); return w > 0 ? w : params.width; } @Override public void destroy() { super.destroy(); view = null; } } static class ImageViewHolder extends ViewImageHolder<ImageView> { public ImageViewHolder(final ImageView view) { super(view); } @Override public void setImage(final Drawable d) { view.setImageDrawable(d); } } static class LoadableImageViewHolder extends ImageViewHolder { public LoadableImageViewHolder(final LoadableImageView view) { super(view); } @Override public boolean skipScaleBeforeCache() { return ((LoadableImageView)view).isSkipScaleBeforeCache(); } @Override public boolean skipLoadingImage() { return ((LoadableImageView)view).isSkipLoadingImage(); } @Override public boolean useSampling() { return ((LoadableImageView)view).isUseSampling(); } @Override public Drawable getLoadingImage() { return ((LoadableImageView)view).getLoadingImage(); } @Override public void setLoadingImage(final Drawable d) { final LoadableImageView view = (LoadableImageView)this.view; setImage(d); view.setTemporaryScaleType(ScaleType.FIT_XY); } @Override public int getImageType() { return ((LoadableImageView)this.view).getImageType(); } } static class CompoundButtonHolder extends ViewImageHolder<CompoundButton> { public CompoundButtonHolder(final CompoundButton view) { super(view); } @Override public void setImage(final Drawable d) { view.setButtonDrawable(d); } } static class TextViewHolder extends ViewImageHolder<TextView> { public TextViewHolder(final TextView view) { super(view); } @Override public void setImage(final Drawable d) { if (view instanceof LoadableTextView) { ((LoadableTextView) view).setLoadedDrawable(d); } else { view.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null); } } @Override public int getRequiredHeight() { return -1; } @Override public int getRequiredWidth() { return -1; } } }
package data; import java.awt.Color; import java.text.DecimalFormat; import java.util.Arrays; import org.knowm.xchart.SwingWrapper; import org.knowm.xchart.XChartPanel; import org.knowm.xchart.XYChart; import org.knowm.xchart.XYChartBuilder; import org.knowm.xchart.XYSeries.XYSeriesRenderStyle; import org.knowm.xchart.style.Styler.ChartTheme; import stats.Statistics; import javax.swing.*; /** * A collection of numerical observations. This class is immutable and all subclasses must be immutable. * * @author Jacob Rachiele */ public class DataSet { private final double[] data; /** * Construct a new data set from the given data. * * @param data the collection of observations. */ public DataSet(final double... data) { if (data == null) { throw new IllegalArgumentException("Null array passed to constructor."); } this.data = data.clone(); } /** * The sum of the observations. * * @return the sum of the observations. */ public final double sum() { return Statistics.sumOf(this.data); } /** * The sum of the squared observations. * * @return the sum of the squared observations. */ public final double sumOfSquares() { return Statistics.sumOfSquared(this.data); } /** * The mean of the observations. * * @return the mean of the observations. */ public final double mean() { return Statistics.meanOf(this.data); } /** * The median value of the observations. * * @return the median value of the observations. */ public final double median() { return Statistics.medianOf(this.data); } /** * The size of the data set. * * @return the size of the data set. */ public final int n() { return this.data.length; } /** * Multiply every element of this data set with the corresponding element of the given data set. * * @param otherData The data to multiply by. * @return A new data set containing every element of this data set multiplied by * the corresponding element of the given data set. */ public final DataSet times(final DataSet otherData) { return new DataSet(Operators.productOf(this.data, otherData.data)); } /** * Add every element of this data set with the corresponding element of the given data set. * * @param otherData The data to add to. * @return A new data set containing every element of this data set added to * the corresponding element of the given data set. */ public final DataSet plus(final DataSet otherData) { return new DataSet(Operators.sumOf(this.data, otherData.data)); } /** * The unbiased sample variance of the observations. * * @return the unbiased sample variance of the observations. */ public final double variance() { return Statistics.varianceOf(this.data); } /** * The unbiased sample standard deviation of the observations. * * @return the unbiased sample standard deviation of the observations. */ public final double stdDeviation() { return Statistics.stdDeviationOf(this.data); } /** * The unbiased sample covariance of these observations with the observations * contained in the given data set. * * @param otherData the data to compute the covariance with. * @return the unbiased sample covariance of these observations with the observations * contained in the given data set. */ public final double covariance(final DataSet otherData) { return Statistics.covarianceOf(this.data, otherData.data); } /** * The unbiased sample correlation of these observations with the observations * contained in the given data set. * * @param otherData the data to compute the correlation coefficient with. * @return the unbiased sample correlation of these observations with the observations * contained in the given data set. */ public final double correlation(DataSet otherData) { return Statistics.correlationOf(this.data, otherData.data); } /** * The observations. * * @return the observations. */ public final double[] data() { return this.data.clone(); } /** * Plot this data set. This method will produce a scatter plot of the data values against the integers * from 0 to n - 1, where n is the size of the data set. */ public void plot() { new Thread(() -> { final double[] indices = new double[this.data.length]; for (int i = 0; i < indices.length; i++) { indices[i] = i; } XYChart chart = new XYChartBuilder().theme(ChartTheme.GGPlot2). title("Scatter Plot").xAxisTitle("Index").yAxisTitle("Values").build(); chart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Scatter). setChartFontColor(Color.BLACK).setSeriesColors(new Color[]{Color.BLUE}); chart.addSeries("data", indices, data); JPanel panel = new XChartPanel<>(chart); JFrame frame = new JFrame("Data Set"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.add(panel); frame.pack(); frame.setVisible(true); }).run(); } /** * Plot this data set against the given data set. The given data set will be plotted on the x-axis, while * this data set will be plotted on the y-axis. * * @param otherData the data set to plot this data set against. */ public void plotAgainst(final DataSet otherData) { new Thread(() -> { XYChart chart = new XYChartBuilder().theme(ChartTheme.GGPlot2).height(600).width(800) .title("Scatter Plot").xAxisTitle("X").yAxisTitle("Y").build(); chart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Scatter). setChartFontColor(Color.DARK_GRAY).setSeriesColors(new Color[]{Color.BLUE}); chart.addSeries("Y against X", otherData.data, this.data); JPanel panel = new XChartPanel<>(chart); JFrame frame = new JFrame("Scatter Plot"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.add(panel); frame.pack(); frame.setVisible(true); }).run(); } @Override public String toString() { DecimalFormat df = new DecimalFormat("0. return "\nValues: " + Arrays.toString(data) + "\nLength: " + data.length + "\nMean: " + mean() + "\nStandard deviation: " + df.format(stdDeviation()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(data); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } DataSet other = (DataSet) obj; return Arrays.equals(data, other.data); } }
package ninja; import sirius.kernel.cache.Cache; import sirius.kernel.cache.CacheManager; import sirius.kernel.health.Exceptions; import sirius.kernel.xml.Attribute; import sirius.kernel.xml.XMLStructuredOutput; import sirius.web.controller.Page; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Represents a bucket. * <p> * Internally a bucket is just a directory within the base directory. * </p> */ public class Bucket { private static final int PAGE_SIZE = 25; private File file; private static Cache<String, Boolean> publicAccessCache = CacheManager.createCache("public-bucket-access"); /** * Creates a new bucket based on the given directory. * * @param file the directory which stores the contents of the bucket. */ public Bucket(File file) { this.file = file; } /** * Returns the name of the bucket. * * @return the name of the bucket */ public String getName() { return file.getName(); } /** * Deletes the bucket and all of its contents. * * @return true if all files of the bucket and the bucket itself was deleted successfully, false otherwise. */ public boolean delete() { boolean deleted = false; for (File child : file.listFiles()) { deleted = child.delete() || deleted; } deleted = file.delete() || deleted; return deleted; } /** * Creates the bucket. * <p> * If the underlying directory already exists, nothing happens. * * @return true if the folder for the bucket was created successfully if it was missing before. */ public boolean create() { return !file.exists() && file.mkdirs(); } /** * Returns a list of at most the provided number of stored objects * * @param output the xml structured output the list of objects should be written to * @param limit controls the maximum number of objects returned * @param marker the key to start with when listing objects in a bucket * @param prefix limits the response to keys that begin with the specified prefix */ public void outputObjects(XMLStructuredOutput output, int limit, @Nullable String marker, @Nullable String prefix) { ListFileTreeVisitor visitor = new ListFileTreeVisitor(output, limit, marker, prefix); output.beginOutput("ListBucketResult", Attribute.set("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")); output.property("Name", getName()); output.property("MaxKeys", limit); output.property("Marker", marker); output.property("Prefix", prefix); try { Files.walkFileTree(file.toPath(), visitor); } catch (IOException e) { Exceptions.handle(e); } output.property("IsTruncated", limit > 0 && visitor.getCount() > limit); output.endOutput(); } /** * Determines if the bucket is private or public accessible * * @return <tt>true</tt> if the bucket is public accessible, <tt>false</tt> otherwise */ public boolean isPrivate() { return !publicAccessCache.get(getName(), key -> getPublicMarkerFile().exists()); } private File getPublicMarkerFile() { return new File(file, "__ninja_public"); } /** * Marks the bucket as private accessible. */ public void makePrivate() { if (getPublicMarkerFile().exists()) { if (getPublicMarkerFile().delete()) { publicAccessCache.put(getName(), false); } else { Storage.LOG.WARN("Failed to delete public marker for bucket %s - it remains public!", getName()); } } } /** * Marks the bucket as public accessible. */ public void makePublic() { if (!getPublicMarkerFile().exists()) { try { new FileOutputStream(getPublicMarkerFile()).close(); } catch (IOException e) { throw Exceptions.handle(Storage.LOG, e); } } publicAccessCache.put(getName(), true); } /** * Returns the underlying directory as File. * * @return a <tt>File</tt> representing the underlying directory */ public File getFile() { return file; } /** * Determines if the bucket exists. * * @return <tt>true</tt> if the bucket exists, <tt>false</tt> otherwise */ public boolean exists() { return file.exists(); } /** * Returns the child object with the given id. * * @param id the name of the requested child object. Must not contain .. / or \ * @return the object with the given id, might not exist, but is always non null */ public StoredObject getObject(String id) { if (id.contains("..") || id.contains("/") || id.contains("\\")) { throw Exceptions.createHandled() .withSystemErrorMessage( "Invalid object name: %s. A object name must not contain '..' '/' or '\\'", id) .handle(); } return new StoredObject(new File(file, id)); } /** * Get a {@link Page} of {@link StoredObject}s, starting at <tt>start</tt> with a page size of {@value PAGE_SIZE} * items. With the <tt>query</tt> parameter you can filter for files containing the query in the file name. * * @param start where to start the page * @param query a search query * @return the {@link Page} for the given parameters */ public Page<StoredObject> getPage(int start, String query) { List<StoredObject> files = getObjects(query); // because lists start at 0 and pages start at 1, the startIndex is start - 1. int startingIndex = start - 1; return new Page<StoredObject>().withStart(start) .withTotalItems(files.size()) .withQuery(query) .withHasMore(startingIndex + PAGE_SIZE < files.size()) .withItems(files.subList(startingIndex, Math.min(startingIndex + PAGE_SIZE, files.size()))); } /** * Get all files which file names contain the query. Leave the query empty to get all files. * * @param query The query to filter for * @return All files which contain the query */ public List<StoredObject> getObjects(@Nonnull String query) { if (file.listFiles() == null) { return new ArrayList<>(); } return Arrays.stream(file.listFiles()) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .map(StoredObject::new) .collect(Collectors.toList()); } }
package org.jimmutable.cloud.messaging; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.management.RuntimeErrorException; import javax.sql.rowset.serial.SerialException; import org.jimmutable.core.utils.Validator; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jimmutable.cloud.ApplicationId; import org.jimmutable.cloud.storage.StorageKeyExtension; import org.jimmutable.core.objects.StandardImmutableObject; import org.jimmutable.core.objects.StandardObject; import org.jimmutable.core.objects.common.ObjectId; import org.jimmutable.core.serialization.Format; import org.jimmutable.core.serialization.reader.ObjectParseTree; import org.jimmutable.core.serialization.writer.ObjectWriter; import com.amazonaws.util.IOUtils; public class MessagingDevLocalFileSystem extends Messaging { private File root; private ExecutorService executor_service = Executors.newSingleThreadExecutor(); private static final Logger logger = LogManager.getLogger(MessagingDevLocalFileSystem.class.getName()); public MessagingDevLocalFileSystem() { super(); if ( !ApplicationId.hasOptionalDevApplicationId() ) { System.err.println("Hey -- you are trying to instantiate a dev local file system. This should not be happening in production. If you are a developer and you are trying to run this through eclipse, you need to setup the environment configurations in your run configurations"); throw new RuntimeException(); } ObjectParseTree.registerTypeName(StandardMessageOnUpsert.class); root = new File(System.getProperty("user.home"), "/jimmutable_dev/messaging"); root.mkdirs(); } /** * @param topic * the topic that you want the message you want the message to go to * @param message * the message you want to send * @return true if the thread was created, false otherwise. */ @SuppressWarnings("rawtypes") @Override public boolean sendAsync( TopicDefinition topic, StandardImmutableObject message ) { if ( message == null ) { return false; } // need to ask about message size? executor_service.submit(new Thread(new SendMessageRunnable(topic, message))); return true; } /** * @param subscription * the subscription you want to listen to * @param listener * the listener you want to handle the message * @return true if the threads were created, false otherwise. */ @Override public boolean startListening( SubscriptionDefinition subscription, MessageListener listener ) { File subscription_path = new File(root.getAbsolutePath(), subscription.getSimpleValue()); if ( !subscription_path.exists() )// if subscription does not exist, make it. { subscription_path.mkdirs(); } new Thread(new ListenForMessageRunnable(subscription_path, listener)).start(); return true; } /** * Single thread executor finishes all current threads, then shuts down. Single * thread executor will not accept any new threads after this method is run. */ @Override public void sendAllAndShutdown() { executor_service.shutdown(); } private class SendMessageRunnable implements Runnable { @SuppressWarnings("rawtypes") private StandardObject message; private TopicDefinition topic; @SuppressWarnings("rawtypes") public SendMessageRunnable( TopicDefinition topic, StandardImmutableObject message ) { this.topic = topic; this.message = message; } @Override public void run() { Validator.notNull(topic); ObjectId objectId = new ObjectId(new Random().nextLong()); FileOutputStream fos; try { File pfile = new File(root.getAbsolutePath(), topic.getSimpleValue()); // CODE REIVEW: What is with the calls to isHidden()? Was there an issue with // hidden files/directories? // CODE ANSWER: We were having issues with Hidden directories (The one I found // was ./DStore) for ( File sub_file_header : listDirectoriesToPutMessagesInto(pfile) ) { writeFile(objectId, sub_file_header); } } catch ( Exception e ) { logger.log(Level.WARN, "Could not send message",e); } } private List<File> listDirectoriesToPutMessagesInto( File pfile ) { List<File> filesToReturn = new ArrayList<File>(); File[] listFiles = pfile.listFiles(); if ( listFiles != null ) { for ( File file_header : listFiles ) { listFiles = pfile.listFiles(); if ( !file_header.isHidden() && listFiles != null ) { for ( File sub_file_header : file_header.listFiles() ) { if ( !sub_file_header.isHidden() ) { filesToReturn.add(sub_file_header); } } } } } return filesToReturn; } private void writeFile( ObjectId objectId, File sub_file_header ) throws FileNotFoundException, IOException { FileOutputStream fos; File file = new File(sub_file_header.getAbsolutePath(), objectId.getSimpleValue() + "." + StorageKeyExtension.JSON); fos = new FileOutputStream(file.getAbsolutePath()); fos.write(ObjectWriter.serialize(Format.JSON_PRETTY_PRINT, message).getBytes()); fos.close(); } } private class ListenForMessageRunnable implements Runnable { private MessageListener listener; private Path my_dir; public ListenForMessageRunnable( File subscription_path, MessageListener listener ) { this.my_dir = subscription_path.toPath(); this.listener = listener; } @SuppressWarnings("rawtypes") @Override public void run() { WatchService watcher = setupListener(); WatchKey watchKey = null; while ( true ) { try { Thread.sleep(500); watchKey = watcher.take(); List<WatchEvent<?>> events = watchKey.pollEvents(); for ( WatchEvent event : events ) { if ( event.kind() == StandardWatchEventKinds.ENTRY_CREATE ) { handleEvent(event); } } } catch ( Exception e ) { logger.log(Level.ERROR, "Could not hear message",e); } watchKey.reset(); // need this so we can look again } } private void handleEvent( WatchEvent event ) throws SerialException { Path message_path = my_dir.resolve(((Path) event.context())); File f = new File(message_path.toString()); listener.onMessageReceived(StandardObject.deserialize(readFile(f))); f.delete(); } private WatchService setupListener() { WatchService watcher = null; try { watcher = my_dir.getFileSystem().newWatchService(); my_dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); } catch ( IOException e ) { logger.log(Level.ERROR, "Could not setup listener",e); } return watcher; } private String readFile( File f ) { FileInputStream fis = null; try { fis = new FileInputStream(f); byte[] byteArray = IOUtils.toByteArray(fis); fis.close(); return new String(byteArray); } catch ( Exception e ) { logger.log(Level.ERROR, "Something went wrong with reading the file", e); return null; } finally { try { fis.close(); } catch ( IOException e ) { logger.log(Level.ERROR, "Something went weird when trying to close the file stream", e); } } } } }
package com.campusdirection; import java.util.Arrays; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.TypedArray; import android.os.Bundle; import android.text.InputType; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Spinner; import android.widget.Toast; public class SearchFragment extends Fragment { // callback method implemented by MainActivity public interface SearchFragmentListener { // called after edit completed so movie can be redisplayed // public void onAddEditCompleted(long rowID); } private SearchFragmentListener listener; private Button searchButton; InstructionsFragment instructionsFragment; private EditText textRoom; private Spinner arrayBuilding; private RadioGroup directLocations; ///for the radio buttons that are exact locations user is looking for // set AddEditFragmentListener when Fragment attached @Override public void onAttach(Activity activity) { super.onAttach(activity); listener = (SearchFragmentListener) activity; } // remove AddEditFragmentListener when Fragment detached @Override public void onDetach() { super.onDetach(); listener = null; } // called after View is created @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); final View view = inflater.inflate(R.layout.activity_search_screen, container, false); //get user input building/room number textRoom = (EditText) view.findViewById(R.id.textRoom); // textRoom.setRawInputType(InputType.TYPE_CLASS_NUMBER); arrayBuilding = (Spinner) view.findViewById(R.id.arrayBuilding); searchButton = (Button) view.findViewById(R.id.searchButton); //adding section for Radio Buttons//////////////////////////////+++++++++++++ // directLocations = (RadioGroup) view.findViewById(R.id.radiogroup); // directLocations.setOnCheckedChangeListener(new OnCheckedChangeListener(){ // @Override // public void onCheckedChanged(RadioGroup group, int checkedId) { // // TODO Auto-generated method stub // RadioButton KodiacCorner = (RadioButton) view.findViewById(R.id.kodiacCornerButton); // RadioButton Library = (RadioButton) view.findViewById(R.id.LibraryButton); // RadioButton BookStore = (RadioButton) view.findViewById(R.id.bookstoreButton); // RadioButton Mobius = (RadioButton) view.findViewById(R.id.bookstoreButton); // if (KodiacCorner.isChecked()){ // arrayBuilding = "CC1"; // textRoom="121"; // if (Library.isChecked()){ // arrayBuilding = "CC1"; // textRoom="121"; // if (BookStore.isChecked()){ // arrayBuilding = "CC1"; // textRoom="121"; // if (Mobius.isChecked()){ // arrayBuilding = "CC1"; // textRoom="121"; searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.direction = ""; //reset direction string MainActivity.specialDirection = ""; //reset special room location MainActivity.searchClick = false; //reset /* when searchButton click, * do all the validation to make sure room number user enter is valid. * * If everything correct, then OPEN the "instruction_activity". * 1. when "instruction_activity" fragment is open. the scan will automatic open * 2. when scan complete, return back to "instruction_activity". * 3. User make rescan again anytime. * 4. user have option to Start Over, this will available on main menu selection. * this will return (pop) back to search_activity screen. */ // launch Instruction/Result fragment after validate user input if(validateRoom()){ splitInput(); //determine floor number base on user enter room number if(isRoom()) instructionFrag(); //launching instruction/result fragment else{ //display dialog message to ask user re-enter room number. showDialog(R.string.roomTitle, R.string.invalidRoom, MainActivity.lookFor.toString()); } }else{ //display dialog message to ask user enter room. Room number field can't be leave blank. showDialog(R.string.emptyInput, R.string.msgInput, ""); } } }); return view; } // check to see if the room user enter existed in that building/floor public boolean isRoom() { Resources res = getResources(); TypedArray tempBld; switch(MainActivity.inputBuild){ case "CC1": if(MainActivity.inputFloor >= 0 && MainActivity.inputFloor < 4){ tempBld = res.obtainTypedArray(R.array.CC1); return verifyRoom(res.getStringArray(tempBld.getResourceId(MainActivity.inputFloor, 0))); }else return false; case "CC2": if(MainActivity.inputFloor >= 0 && MainActivity.inputFloor < 4){ tempBld = res.obtainTypedArray(R.array.CC2); return verifyRoom(res.getStringArray(tempBld.getResourceId(MainActivity.inputFloor, 0))); }else return false; case "CC3": if(MainActivity.inputFloor > 0 && MainActivity.inputFloor < 3){ tempBld = res.obtainTypedArray(R.array.CC3); return verifyRoom(res.getStringArray(tempBld.getResourceId(MainActivity.inputFloor, 0))); }else return false; case "LBA": //Share building: Library Annex if(MainActivity.inputFloor == 1){ tempBld = res.obtainTypedArray(R.array.LBA); return verifyRoom(res.getStringArray(tempBld.getResourceId(MainActivity.inputFloor, 0))); }else return false; default: return false; //building is invalid } } // check existing room per floor plan public boolean verifyRoom(String[] arr) { // Toast.makeText(getActivity(), String.valueOf(Arrays.asList(arr).contains(MainActivity.inputRoom)), Toast.LENGTH_SHORT).show(); return Arrays.asList(arr).contains(MainActivity.inputRoom); } // check to see if user enter room number public boolean validateRoom() { String tempRm = textRoom.getText().toString().trim(); String tempRmRep = tempRm.replaceAll("[\\D]", ""); if(tempRm.equals("")) return false; else{ if(tempRmRep == "") return false; // Toast.makeText(getActivity(), String.valueOf(tempRmRep), Toast.LENGTH_SHORT).show(); else{ MainActivity.lookFor = String.valueOf(arrayBuilding.getSelectedItem())+"-"+textRoom.getText().toString().trim(); return true; } } } // split user input into piece (building, room, floor) public void splitInput() { String tempBd = String.valueOf(arrayBuilding.getSelectedItem()); String tempRm = textRoom.getText().toString(); int tempFlr = Integer.parseInt((tempRm.replaceAll("[\\D]", "")).substring(0, 1)); int tempLoc = Integer.parseInt((tempRm.replaceAll("[\\D]", "")).substring(1, 2)); //verify floor level base on user input room number int tempNum = Integer.parseInt(tempRm.replaceAll("[\\D]", "")); if(tempNum < 100) tempFlr = 0; MainActivity.setSplitInput(tempBd, tempRm, tempFlr, tempLoc); } // launch Result/Instruction fragment for direction public void instructionFrag() { instructionsFragment = new InstructionsFragment(); FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.fragmentContainer, instructionsFragment); ft.addToBackStack(null); ft.commit(); // causes CollectionListFragment to displa } // display this fragment's menu items @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.main, menu); } // handle choice from options menu @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // case R.id.action_add: // listener.onAddMovie(); // return true; } return super.onOptionsItemSelected(item); // call super's method } // display an AlertDialog when invalid room detect public void showDialog(final int msgTitle, final int msgFormat, final String str) { AlertDialog.Builder displayMsg = new AlertDialog.Builder(getActivity()); displayMsg.setTitle(msgTitle); displayMsg.setMessage(getResources().getString(msgFormat, str)); displayMsg.setPositiveButton(getResources().getText(R.string.okBut), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { //do something when OK button click //leave blank if just close window only. } }); /* displayMsg.setNegativeButton(getResources().getText(R.string.cancelBut), new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int arg1) { //do something when Cancel button click //leave blank if just close window only. } }); */ // display message to user displayMsg.show(); } }
package org.sibsutis.is.construction; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class Room { private String TypeOfRoom; private byte NumOfSubrooms; private String RoomSize; private List ListFurniture; private boolean WaterMain; private long PhoneLine; private boolean Line380v; private boolean Ethernet; private byte NumOfWindows; private List ListDevices; private long NumberOfRoom; public Room () {} public Room (String TypeOfRoom, long NumberOfRoom, byte NumOfSubrooms, String RoomSize, byte NumOfWindows, List ListFurniture, List ListDevices, boolean WaterMain, long PhoneLine, boolean Line380v, boolean Ethernet) { this.TypeOfRoom = TypeOfRoom; this.WaterMain = WaterMain; this.NumOfSubrooms = NumOfSubrooms; this.PhoneLine = PhoneLine; this.RoomSize = RoomSize; this.Ethernet = Ethernet; this.ListFurniture = ListFurniture; this.Line380v = Line380v; this.NumOfWindows = NumOfWindows; this.ListDevices = ListDevices; this.NumberOfRoom = NumberOfRoom; log.log(Level.INFO,"[Room] Экземпляр объекта Room с заполненными полями " + "успешно создан" );} public String getRoomInfo(boolean ByCategory) { String str; if (ByCategory==true) { str = "Type: " + TypeOfRoom +"\nNumber: " + NumberOfRoom + "\nSubrooms: " + NumOfSubrooms + "\nSize: " + RoomSize + "\nWindows: " + NumOfWindows + "\nFurniture: " + ListFurniture + "\nDevices: " + ListDevices + "\nWaterMain: " + WaterMain + "\nNumber: " + PhoneLine + "Power 380V: " + Line380v + "\nEthernet: " + Ethernet; } else { str = "" + TypeOfRoom +"," + NumberOfRoom + "," + NumOfSubrooms + "," + RoomSize + "," + NumOfWindows + "," + ListFurniture + "," + ListDevices + "," + WaterMain + "," + PhoneLine + "," + Line380v + "," + Ethernet; } log.log(Level.INFO,"[Room] Функция возврата всех параметров отработала успешно" ); return str;} public String getTypeOfRoom () {return TypeOfRoom; } public byte getNumOfRooms () {return NumOfSubrooms; } public String getRoomSize () {return RoomSize; } public List getListFurniture () {return ListFurniture; } public boolean getWaterMain () {return WaterMain; } public long getPhoneLine () {return PhoneLine;} public boolean getLine380v () {return Line380v;} public boolean getEthernet () {return Ethernet;} public byte getNumOfWindows () {return NumOfWindows;} public List getListDevices () {return ListDevices;} public long getNumberOfRoom() {return NumberOfRoom;} public void setTypeOfRoom (String TypeOfRoom) { this.TypeOfRoom = TypeOfRoom; } public void setNumOfRooms (byte NumOfSubrooms) { this.NumOfSubrooms = NumOfSubrooms; } public void setRoomSize (String RoomSize) { this.RoomSize = RoomSize; } public void setListFurniture (List ListFurniture) { this.ListFurniture = ListFurniture; } public void setWaterMain (boolean WaterMain) { this.WaterMain = WaterMain; } public void setPhoneLine (long PhoneLine) { this.PhoneLine = PhoneLine; } public void setLine380v (boolean Line380v) { this.Line380v = Line380v; } public void setEthernet (boolean Ethernet) { this.Ethernet = Ethernet; } public void setNumOfWindows (byte NumOfWindows) { this.NumOfWindows = NumOfWindows; } public void setListDevices (List ListDevices) { this.ListDevices = ListDevices; } public void setNumberOfRoom (long NumberOfRoom) { this.NumberOfRoom = NumberOfRoom; } private static final Logger log = Logger.getLogger(Room.class.getName()); }
package io.undertow.client.http; import io.undertow.UndertowMessages; import io.undertow.client.ClientCallback; import io.undertow.client.ClientConnection; import io.undertow.client.ClientProvider; import org.xnio.ChannelListener; import org.xnio.IoFuture; import org.xnio.OptionMap; import org.xnio.Pool; import org.xnio.StreamConnection; import org.xnio.XnioIoThread; import org.xnio.XnioWorker; import org.xnio.ssl.XnioSsl; import java.net.InetSocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author Stuart Douglas */ public class HttpClientProvider implements ClientProvider { @Override public Set<String> handlesSchemes() { return new HashSet<String>(Arrays.asList(new String[]{"http", "https"})); } @Override public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioWorker worker, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) { if (uri.getScheme().equals("https")) { if (ssl == null) { throw UndertowMessages.MESSAGES.sslWasNull(); } ssl.openSslConnection(worker, new InetSocketAddress(uri.getHost(), uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null); } else { worker.openStreamConnection(new InetSocketAddress(uri.getHost(), uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null); } } @Override public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) { if (uri.getScheme().equals("https")) { if (ssl == null) { throw UndertowMessages.MESSAGES.sslWasNull(); } ssl.openSslConnection(ioThread, new InetSocketAddress(uri.getHost(), uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null); } else { ioThread.openStreamConnection(new InetSocketAddress(uri.getHost(), uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null); } } private IoFuture.Notifier<StreamConnection, Object> createNotifier(final ClientCallback<ClientConnection> listener) { return new IoFuture.Notifier<StreamConnection, Object>() { @Override public void notify(IoFuture<? extends StreamConnection> ioFuture, Object o) { if (ioFuture.getStatus() == IoFuture.Status.FAILED) { listener.failed(ioFuture.getException()); } } }; } private ChannelListener<StreamConnection> createOpenListener(final ClientCallback<ClientConnection> listener, final URI uri, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) { return new ChannelListener<StreamConnection>() { @Override public void handleEvent(StreamConnection connection) { handleConnected(connection, listener, uri, ssl, bufferPool, options); } }; } private void handleConnected(StreamConnection connection, ClientCallback<ClientConnection> listener, URI uri, XnioSsl ssl, Pool<ByteBuffer> bufferPool, OptionMap options) { listener.completed(new HttpClientConnection(connection, options, bufferPool)); } }
package htm.core; import htm.Input; import htm.InputProvider; import htm.InputSet; import java.util.ArrayList; import java.util.Collection; /** * * @author david.charubini */ public class HTM extends Thread { private final InputProvider inputProvider; private final Pooler spatialPooler; private final Pooler temporalPooler; private final Region[][] regionsByLevel; private volatile boolean running = false; public HTM(InputProvider inputProvider, Region[][] regionsByLevel, Pooler spatialPooler, Pooler temporalPooler) { super(); this.inputProvider = inputProvider; this.regionsByLevel = regionsByLevel; this.spatialPooler = spatialPooler; this.temporalPooler = temporalPooler; } public void initialize() { this.running = true; this.start(); } @Override public void run() { while (this.running) { InputSet inputSet = null; try { inputSet = this.inputProvider.take(); } catch (InterruptedException ie) { if (this.running) { ie.printStackTrace(); } } this.process(inputSet); // TODO: process output - via queue? } } public Collection<Input<?>> getConnectedInputs() { // TBD: take the connected synapses from the upper levels // and feed downward? Collection<Input<?>> connectedInputs = new ArrayList<Input<?>>(); for (Region region : this.regionsByLevel[0]) { region.getConnectedInputs(connectedInputs); } return connectedInputs; } // TODO: return output, feed region output into higher levels private void process (InputSet input) { System.out.println("Processing input"); InputSet inputSet = input; for (Region[] regions : this.regionsByLevel) { Collection<Input<?>> connectedInputs = new ArrayList<Input<?>>(); for (Region region : regions) { Collection<Input<?>> spatialInputs = new ArrayList<Input<?>>(); // perform spatial pooling this.spatialPooler.process(region, inputSet); // pull out the connections region.getConnectedInputs(spatialInputs); // feed the connections into the temporal pooler this.temporalPooler.process(region, new InputSet(spatialInputs)); // the remaining connections become input into the next level region.getConnectedInputs(connectedInputs); } inputSet = new InputSet(connectedInputs); } } public void uninitialize() { this.running = false; } }
package edu.duke.cabig.c3pr.web; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Logger; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import edu.duke.cabig.c3pr.domain.EligibilityCriteria; import edu.duke.cabig.c3pr.domain.StudyParticipantAssignment; import edu.duke.cabig.c3pr.domain.SubjectEligibilityAnswer; import edu.duke.cabig.c3pr.service.ParticipantService; import edu.duke.cabig.c3pr.utils.Lov; import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.Flow; import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.Tab; /** * @author Ramakrishna * */ public class CreateRegistrationController extends RegistrationController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(CreateRegistrationController.class); private static Log log = LogFactory.getLog(CreateRegistrationController.class); private ParticipantService participantService; public void setParticipantService(ParticipantService participantService) { this.participantService = participantService; } public CreateRegistrationController() { super("Create Registration"); } protected void intializeFlows(Flow<StudyParticipantAssignment> flow) { flow.addTab(new Tab<StudyParticipantAssignment>("Search Subject or Study", "SearchSubjectStudy","registration/home","false"){ public Map<String, Object> referenceData() { Map<String, List<Lov>> configMap = configurationProperty.getMap(); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("searchTypeRefDataStudy", configMap.get("studySearchType")); refdata.put("searchTypeRefDataPrt", configMap.get("participantSearchType")); return refdata; } }); flow.addTab(new Tab<StudyParticipantAssignment>("Select Study", "Select Study")); flow.addTab(new Tab<StudyParticipantAssignment>("Select Subject", "Select Subject")); flow.addTab(new Tab<StudyParticipantAssignment>("Enrollment Details", "Enrollment Details","registration/reg_registration_details")); flow.addTab(new Tab<StudyParticipantAssignment>("Check Eligibility", "Check Eligibility","registration/reg_check_eligibility")); flow.addTab(new Tab<StudyParticipantAssignment>("Stratify", "Stratify","registration/reg_stratify")); flow.addTab(new Tab<StudyParticipantAssignment>("Review & Submit", "Review & Submit","registration/reg_submit")); flow.getTab(0).setShowSummary("false"); flow.getTab(1).setShowSummary("false"); flow.getTab(2).setShowSummary("false"); flow.getTab(6).setShowSummary("false"); flow.getTab(0).setShowLink("false"); flow.getTab(1).setShowLink("false"); flow.getTab(2).setShowLink("false"); flow.getTab(0).setSubFlow("true"); flow.getTab(1).setSubFlow("true"); flow.getTab(2).setSubFlow("true"); setFlow(flow); } @Override protected boolean isFormSubmission(HttpServletRequest request) { return super.isFormSubmission(request) || isResumeFlow(request); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { // TODO Auto-generated method stub StudyParticipantAssignment studyParticipantAssignment=new StudyParticipantAssignment(); studyParticipantAssignment.setStartDate(new Date()); studyParticipantAssignment.setEligibilityWaiverReasonText("Type Eligibility Waiver Reason."); removeAlternateDisplayFlow(request); request.getSession().setAttribute("registrationFlow", getFlow()); request.getSession().setAttribute("studyParticipantAssignments", studyParticipantAssignment); return studyParticipantAssignment; } @Override protected Map<String, Object> referenceData(HttpServletRequest httpServletRequest, int page) throws Exception { // TODO Auto-generated method stub Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("registrationTab", getFlow().getTab(page)); return refdata; } @Override protected void postProcessPage(HttpServletRequest request, Object command, Errors errors, String tabShortTitle) throws Exception { // TODO Auto-generated method stub StudyParticipantAssignment studyParticipantAssignment=(StudyParticipantAssignment)command; if(isResumeFlow(request)){ if (logger.isDebugEnabled()) { logger.debug("postProcessPage(HttpServletRequest, Object, Errors, String) - ResumeFlow"); //$NON-NLS-1$ } if (logger.isDebugEnabled()) { logger.debug("postProcessPage(HttpServletRequest, Object, Errors, String) - extracting eligibility criteria from study..."); //$NON-NLS-1$ } List criterias=studyParticipantAssignment.getStudySite().getStudy().getIncCriterias(); for(int i=0 ; i<criterias.size() ; i++){ SubjectEligibilityAnswer subjectEligibilityAnswer=new SubjectEligibilityAnswer(); subjectEligibilityAnswer.setEligibilityCriteria((EligibilityCriteria)criterias.get(i)); studyParticipantAssignment.addSubjectEligibilityAnswers(subjectEligibilityAnswer); } criterias=studyParticipantAssignment.getStudySite().getStudy().getExcCriterias(); for(int i=0 ; i<criterias.size() ; i++){ SubjectEligibilityAnswer subjectEligibilityAnswer=new SubjectEligibilityAnswer(); subjectEligibilityAnswer.setEligibilityCriteria((EligibilityCriteria)criterias.get(i)); studyParticipantAssignment.addSubjectEligibilityAnswers(subjectEligibilityAnswer); } studyParticipantAssignment.setStartDate(new Date()); studyParticipantAssignment.setStudyParticipantIdentifier("SYS_GEN1"); if (logger.isDebugEnabled()) { logger.debug("postProcessPage(HttpServletRequest, Object, Errors, String) - studyParticipantAssignment.getParticipant().getPrimaryIdentifier()" + studyParticipantAssignment.getParticipant().getPrimaryIdentifier()); //$NON-NLS-1$ } } if(tabShortTitle.equalsIgnoreCase("Check Eligibility")){ boolean flag=true; List<SubjectEligibilityAnswer> answers=studyParticipantAssignment.getInclusionEligibilityAnswers(); for(SubjectEligibilityAnswer subjectEligibilityAnswer:answers){ if(!subjectEligibilityAnswer.getAnswerText().equalsIgnoreCase("Yes")&&!subjectEligibilityAnswer.getAnswerText().equalsIgnoreCase("NA")){ flag=false; break; } } if(flag){ answers=studyParticipantAssignment.getExclusionEligibilityAnswers(); for(SubjectEligibilityAnswer subjectEligibilityAnswer:answers){ if(!subjectEligibilityAnswer.getAnswerText().equalsIgnoreCase("No")&&!subjectEligibilityAnswer.getAnswerText().equalsIgnoreCase("NA")){ flag=false; break; } } } studyParticipantAssignment.setEligibilityIndicator(flag); } } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest) */ @Override protected ModelAndView processFinish(HttpServletRequest request, HttpServletResponse response, Object command, BindException arg3) throws Exception { // TODO Auto-generated method stub StudyParticipantAssignment studyParticipantAssignment = (StudyParticipantAssignment) command; if (logger.isDebugEnabled()) { logger.debug("processFinish(HttpServletRequest, HttpServletResponse, Object, BindException) - in process finish"); //$NON-NLS-1$ } studyParticipantAssignment.getParticipant().getStudyParticipantAssignments().size(); studyParticipantAssignment.getParticipant().addStudyParticipantAssignment(studyParticipantAssignment); studyParticipantAssignment.setRegistrationStatus(evaluateStatus(studyParticipantAssignment)); System.out.println("Calling participant service"); participantService.createRegistration(studyParticipantAssignment); System.out.println("participant service call over"); removeAlternateDisplayFlow(request); request.getSession().removeAttribute("registrationFlow"); request.setAttribute("command", command); RequestDispatcher rd = request.getRequestDispatcher("confirm?type=confirm"); rd.forward(request, response); return null; } private String evaluateStatus(StudyParticipantAssignment studyParticipantAssignment){ String status="Complete"; if(studyParticipantAssignment.getInformedConsentSignedDateStr().equals("")){ return "Incomplete"; }else if(studyParticipantAssignment.getTreatingPhysician()==null){ return "Incomplete"; }else if(studyParticipantAssignment.getTreatingPhysician().equals("")){ return "Incomplete"; }else if(studyParticipantAssignment.getEligibilityIndicator()){ List<SubjectEligibilityAnswer> criterias=studyParticipantAssignment.getSubjectEligibilityAnswers(); if (logger.isDebugEnabled()) { logger.debug("evaluateStatus(StudyParticipantAssignment) - studyParticipantAssignment.getEligibilityIndicator():" + studyParticipantAssignment.getEligibilityIndicator()); //$NON-NLS-1$ } studyParticipantAssignment.setEligibilityWaiverReasonText(""); if (logger.isDebugEnabled()) { logger.debug("evaluateStatus(StudyParticipantAssignment) - printing answers....."); //$NON-NLS-1$ } for(int i=0 ; i<criterias.size() ; i++){ if (logger.isDebugEnabled()) { logger.debug("evaluateStatus(StudyParticipantAssignment) - question : " + criterias.get(i).getEligibilityCriteria().getQuestionText()); //$NON-NLS-1$ } if (logger.isDebugEnabled()) { logger.debug("evaluateStatus(StudyParticipantAssignment) - ----- answer : " + criterias.get(i).getAnswerText()); //$NON-NLS-1$ } if(criterias.get(i).getAnswerText()==null){ if(criterias.get(i).getAnswerText().equals("")){ return "Incomplete"; } } } }else if(!studyParticipantAssignment.getEligibilityIndicator()&&studyParticipantAssignment.getEligibilityWaiverReasonText()!=null){ if(studyParticipantAssignment.getEligibilityWaiverReasonText().equals("")) return "Incomplete"; } return status; } private void setAlternateDisplayOrder(HttpServletRequest request, List order){ request.getSession().setAttribute("registrationAltOrder", order); } private void removeAlternateDisplayFlow(HttpServletRequest request){ request.getSession().removeAttribute("registrationAltFlow"); } private boolean isResumeFlow(HttpServletRequest request){ if(request.getParameter("resumeFlow")!=null) return true; return false; } }
package org.elasticsearch.action.search; import com.bazaarvoice.elasticsearch.client.core.HttpExecutor; import com.bazaarvoice.elasticsearch.client.core.HttpResponse; import com.bazaarvoice.elasticsearch.client.core.util.InputStreams; import com.bazaarvoice.elasticsearch.client.core.util.UrlBuilder; import org.apache.lucene.search.Explanation; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.IgnoreIndices; import org.elasticsearch.common.base.Function; import org.elasticsearch.common.base.Joiner; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableList; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.text.StringText; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.util.concurrent.FutureCallback; import org.elasticsearch.common.util.concurrent.Futures; import org.elasticsearch.common.util.concurrent.ListenableFuture; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.facet.Facet; import org.elasticsearch.search.facet.InternalFacets; import org.elasticsearch.search.facet.datehistogram.DateHistogramFacet; import org.elasticsearch.search.facet.datehistogram.InternalCountDateHistogramFacet; import org.elasticsearch.search.facet.datehistogram.InternalFullDateHistogramFacet; import org.elasticsearch.search.facet.histogram.HistogramFacet; import org.elasticsearch.search.facet.histogram.InternalCountHistogramFacet; import org.elasticsearch.search.facet.histogram.InternalFullHistogramFacet; import org.elasticsearch.search.highlight.HighlightField; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import org.elasticsearch.search.internal.InternalSearchHits; import org.elasticsearch.search.internal.InternalSearchResponse; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import static com.bazaarvoice.elasticsearch.client.core.util.MapFunctions.readBytesReference; import static com.bazaarvoice.elasticsearch.client.core.util.MapFunctions.requireList; import static com.bazaarvoice.elasticsearch.client.core.util.MapFunctions.requireMap; import static com.bazaarvoice.elasticsearch.client.core.util.MapFunctions.requireString; import static com.bazaarvoice.elasticsearch.client.core.util.Rest.findRestStatus; import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.ignoreIndicesToString; import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.scrollToString; import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.searchTypeToString; import static org.elasticsearch.common.Preconditions.checkState; import static org.elasticsearch.common.base.Optional.fromNullable; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeDoubleValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeFloatValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeIntegerValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeLongValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringValue; public class SearchRest { public static ListenableFuture<SearchResponse> act(HttpExecutor executor, SearchRequest request) { UrlBuilder url = UrlBuilder.create(); if (request.indices() == null || request.indices().length == 0) { url = url.path("_search"); } else { String indices = Joiner.on(',').skipNulls().join(request.indices()); if (request.types() == null || request.types().length == 0) { url = url.path(indices, "_search"); } else if (request.types() == null || request.types().length == 0) { String types = Joiner.on(',').skipNulls().join(request.types()); url = url.path(indices, types, "_search"); } } if (request.extraSource() != null) { throw new NotImplementedException();// TODO: implement. not bothering with this for now... } url = url .paramIfPresent("search_type", fromNullable(request.searchType()).transform(searchTypeToString)) .paramIfPresent("scroll", fromNullable(request.scroll()).transform(scrollToString)) .paramIfPresent("routing", fromNullable(request.routing())) .paramIfPresent("preference", fromNullable(request.preference())) .paramIfPresent("ignore_indices", fromNullable(toNullIfDefault(request.ignoreIndices())).transform(ignoreIndicesToString)) ; return Futures.transform(executor.post(url.url(), InputStreams.of(request.source())), searchResponseFunction); } private static IgnoreIndices toNullIfDefault(final IgnoreIndices ignoreIndices) { // TODO add a string serialization for DEFAULT with a PR, then get rid of this method if (IgnoreIndices.DEFAULT.equals(ignoreIndices)) { return null; } else { return ignoreIndices; } } public static FutureCallback<SearchResponse> searchResponseCallback(final ActionListener<SearchResponse> listener) { return new SearchCallback(listener); } private static Function<HttpResponse, SearchResponse> searchResponseFunction = new Function<HttpResponse, SearchResponse>() { @Override public SearchResponse apply(final HttpResponse httpResponse) { try { //TODO check REST status and "ok" field and handle failure Map<String, Object> map = JsonXContent.jsonXContent.createParser(httpResponse.response()).mapAndClose(); Map<String, Object> shards = requireMap(map.get("_shards"), String.class, Object.class); int totalShards = nodeIntegerValue(shards.get("total")); int successfulShards = nodeIntegerValue(shards.get("successful")); int failedShards = totalShards - successfulShards; InternalFacets facets = null; if (map.containsKey("facets")) { final Map<String, Object> facetsMap = requireMap(map.get("facets"), String.class, Object.class); final List<Facet> facetsList = new ArrayList<Facet>(facetsMap.size()); for (Map.Entry<String, Object> facetEntry : facetsMap.entrySet()) { final String facetName = facetEntry.getKey(); final Map<String, Object> facetMap = requireMap(facetEntry.getValue(), String.class, Object.class); final String type = requireString(facetMap.get("_type")); if (type.equals(DateHistogramFacet.TYPE)) { final List<Object> entries = requireList(facetMap.get("entries"), Object.class); InternalCountDateHistogramFacet.CountEntry[] countEntries = null; InternalFullDateHistogramFacet.FullEntry[] fullEntries = null; for (int i = 0; i < entries.size(); i++) { final Map<String, Object> entryMap = requireMap(entries.get(i), String.class, Object.class); final long time = nodeLongValue(entryMap.get("time")); final long count = nodeLongValue(entryMap.get("count")); final double min = nodeDoubleValue(entryMap.get("min"), Double.NaN); final double max = nodeDoubleValue(entryMap.get("max"), Double.NaN); final double total = nodeDoubleValue(entryMap.get("total"), Double.NaN); final long totalCount = nodeLongValue(entryMap.get("total_count"), 0); final double mean = nodeDoubleValue(entryMap.get("mean"), Double.NaN); if (Double.isNaN(min) && Double.isNaN(max) && Double.isNaN(total) && Double.isNaN(mean) && totalCount == 0) { checkState(fullEntries == null); if (countEntries == null) { countEntries = new InternalCountDateHistogramFacet.CountEntry[entries.size()]; } countEntries[i] = new InternalCountDateHistogramFacet.CountEntry(time, count); } else { checkState(countEntries == null); if (fullEntries == null) { fullEntries = new InternalFullDateHistogramFacet.FullEntry[entries.size()]; } fullEntries[i] = new InternalFullDateHistogramFacet.FullEntry(time, count, min, max, totalCount, total); } } final DateHistogramFacet.ComparatorType comparatorType = null; // FIXME not serialized, so there's nothing we can pick here. Not sure of the impact of choosing null. if (countEntries != null) { facetsList.add(new InternalCountDateHistogramFacet(facetName, comparatorType, countEntries)); } else { checkState(fullEntries != null); assert fullEntries != null; facetsList.add(new InternalFullDateHistogramFacet(facetName, comparatorType, Arrays.asList(fullEntries))); } } else if (type.equals(HistogramFacet.TYPE)) { final List<Object> entries = requireList(facetMap.get("entries"), Object.class); InternalCountHistogramFacet.CountEntry[] countEntries = null; InternalFullHistogramFacet.FullEntry[] fullEntries = null; for (int i = 0; i < entries.size(); i++) { final Map<String, Object> entryMap = requireMap(entries.get(i), String.class, Object.class); final long key = nodeLongValue(entryMap.get("key")); final long count = nodeLongValue(entryMap.get("count")); final double min = nodeDoubleValue(entryMap.get("min"), Double.NaN); final double max = nodeDoubleValue(entryMap.get("max"), Double.NaN); final double total = nodeDoubleValue(entryMap.get("total"), Double.NaN); final long totalCount = nodeLongValue(entryMap.get("total_count"), 0); final double mean = nodeDoubleValue(entryMap.get("mean"), Double.NaN); if (Double.isNaN(min) && Double.isNaN(max) && Double.isNaN(total) && Double.isNaN(mean) && totalCount == 0) { checkState(fullEntries == null); if (countEntries == null) { countEntries = new InternalCountHistogramFacet.CountEntry[entries.size()]; } countEntries[i] = new InternalCountHistogramFacet.CountEntry(key, count); } else { checkState(countEntries == null); if (fullEntries == null) { fullEntries = new InternalFullHistogramFacet.FullEntry[entries.size()]; } fullEntries[i] = new InternalFullHistogramFacet.FullEntry(key, count, min, max, totalCount, total); } } final HistogramFacet.ComparatorType comparatorType = null; // FIXME not serialized, so there's nothing we can pick here. Not sure of the impact of choosing null. if (countEntries != null) { facetsList.add(new InternalCountHistogramFacet(facetName, comparatorType, countEntries)); } else { checkState(fullEntries != null); assert fullEntries != null; facetsList.add(new InternalFullHistogramFacet(facetName, comparatorType, Arrays.asList(fullEntries))); } } facets = new InternalFacets(facetsList); } SearchResponse searchResponse = new SearchResponse( new InternalSearchResponse( getSearchHits(map), facets, suggest, nodeBooleanValue(map.get("timed_out")) ), nodeStringValue(map.get("_scroll_id"), null), totalShards, successfulShards, nodeLongValue(map.get("took")), getShardSearchFailures(shards, failedShards)); // SearchResponse indexResponse = new SearchResponse( // requireString(map.get("_index")), // requireString(map.get("_type")), // requireString(map.get("_id")), // requireLong(map.get("_version"))); // if (map.containsKey("matches")) { // List<String> matches = requireList(map.get("matches"), String.class); // indexResponse.setMatches(matches); // return indexResponse; }catch(IOException e){ // FIXME: which exception to use? It should match ES clients if possible. throw new RuntimeException(e); } } } ; private static ShardSearchFailure[] getShardSearchFailures(final Map<String, Object> shards, final int failedShards) { final ShardSearchFailure[] shardSearchFailures = new ShardSearchFailure[failedShards]; Object[] failures = requireList(shards.get("failures"), Object.class).toArray(); for (int i = 0; i < failedShards; i++) { Map<String, Object> failure = requireMap(failures[i], String.class, Object.class); SearchShardTarget shard = null; if (failure.containsKey("index") && failure.containsKey("shard")) { String index = nodeStringValue(failure.get("index"), null); Integer shardId = nodeIntegerValue(failure.get("shard")); shard = new SearchShardTarget(null, index, shardId); } shardSearchFailures[i] = new ShardSearchFailure( nodeStringValue(failure.get("reason"), null), shard, findRestStatus(nodeIntegerValue(failure.get("status"))) ); } return shardSearchFailures; } private static InternalSearchHits getSearchHits(final Map<String, Object> map) { InternalSearchHits hits = null; if (map.containsKey("hits")) { Map<String, Object> hitsMap = requireMap(map.get("hits"), String.class, Object.class); final long totalHits = nodeLongValue(hitsMap.get("total")); final float maxScore = hitsMap.get("max_score") != null ? nodeFloatValue(hitsMap.get("max_score")) : Float.NaN; List<InternalSearchHit> internalSearchHits = Lists.newArrayList(); if (hitsMap.containsKey("hits")) { List<Object> hitsList = requireList(hitsMap.get("hits"), Object.class); for (Object hit : hitsList) { Map<String, Object> hitMap = requireMap(hit, String.class, Object.class); Object explanation = hitMap.get("_explanation"); String nodeid = null; int shardid = -1; // FIXME not quite right, but the es serialization node is confusing // it only serializes _shard and _node if explanation != null, but it always serializes _index, // and the only way _index could be set is at the same time as the other fields, // (unless it comes from the read(instream) method, in which case shardid and index get set, but nodeid may be unset. // which suggests that at least index and shardid are set on the ES side, but they are deliberately // leaving shardid off from the serialization when explanation() is null. // If so, there is no way I can recover that information, so I'll just set shardId to an impossible value // TODO send a PR to elasticsearch to fix this on the server side if (explanation != null) { shardid = nodeIntegerValue(hitMap.get("_shard")); nodeid = nodeStringValue(hitMap.get("_node"), null); } String index = nodeStringValue(hitMap.get("_index"), null); SearchShardTarget searchShardTarget = new SearchShardTarget(nodeid, index, shardid); Text type = new StringText(nodeStringValue(hitMap.get("_type"), null)); String id = nodeStringValue(hitMap.get("_id"), null); long version = nodeLongValue(hitMap.get("_version"), -1); float score = nodeFloatValue(hitMap.get("_score"), Float.NaN); BytesReference source = readBytesReference(hitMap.get("_source")); final int docId = -1; // this field isn't serialized ImmutableMap.Builder<String, SearchHitField> fields = ImmutableMap.builder(); if (hitMap.containsKey("fields")) { Map<String, Object> fieldsMap = requireMap(hitMap.get("fields"), String.class, Object.class); for (Map.Entry<String, Object> fieldEntry : fieldsMap.entrySet()) { final ImmutableList.Builder<Object> valuesBuilder = ImmutableList.builder(); if (fieldEntry.getValue() instanceof List) { for (Object value : requireList(fieldEntry.getValue(), Object.class)) { valuesBuilder.add(value); } } else { valuesBuilder.add(fieldEntry.getValue()); } SearchHitField field = new InternalSearchHitField(fieldEntry.getKey(), valuesBuilder.build()); fields.put(field.getName(), field); } } InternalSearchHit internalSearchHit = new InternalSearchHit(docId, id, type, source, fields.build()); internalSearchHit.shardTarget(searchShardTarget); if (hitMap.containsKey("highlight")) { ImmutableMap.Builder<String, HighlightField> highlights = ImmutableMap.builder(); final Map<String, Object> highlightMap = requireMap(hitMap.get("highlight"), String.class, Object.class); for (Map.Entry<String, Object> entry : highlightMap.entrySet()) { final String name = entry.getKey(); final Text[] fragments; if (entry.getValue() == null) { fragments = null; } else { final List<String> strings = requireList(entry.getValue(), String.class); fragments = new Text[strings.size()]; for (int i = 0; i < strings.size(); i++) { fragments[i] = new StringText(strings.get(i)); } } final HighlightField highlightField = new HighlightField(name, fragments); highlights.put(highlightField.getName(), highlightField); } internalSearchHit.highlightFields(highlights.build()); } if (hitMap.containsKey("sort")) { // TODO: can't really tell if this is the right thing to do. final List<Object> sorts = requireList(hitMap.get("sort"), Object.class); internalSearchHit.sortValues(sorts.toArray()); } if (hitMap.containsKey("matched_filters")) { final List<String> matched_filters = requireList(hitMap.get("matched_filters"), String.class); internalSearchHit.matchedQueries(matched_filters.toArray(new String[matched_filters.size()])); } if (explanation != null) { internalSearchHit.explanation(getExplanation(explanation)); } internalSearchHits.add(internalSearchHit); } } hits = new InternalSearchHits(internalSearchHits.toArray(new InternalSearchHit[internalSearchHits.size()]), totalHits, maxScore); } return hits; } private static Explanation getExplanation(final Object explanationObj) { final Map<String, Object> explainMap = requireMap(explanationObj, String.class, Object.class); final float value = nodeFloatValue(explainMap.get("value")); final String description = nodeStringValue(explainMap.get("description"), null); final Explanation explanation = new Explanation(value, description); if (explainMap.containsKey("details")) { for (Object detail : requireList(explainMap.get("details"), Object.class)) { explanation.addDetail(getExplanation(detail)); } } return explanation; } private static class SearchCallback implements FutureCallback<SearchResponse> { private final ActionListener<SearchResponse> listener; private SearchCallback(ActionListener<SearchResponse> listener) { this.listener = listener; } @Override public void onSuccess(final SearchResponse indexResponse) { listener.onResponse(indexResponse); } @Override public void onFailure(final Throwable throwable) { // TODO transform failure listener.onFailure(throwable); } } }
package water; import java.lang.reflect.InvocationTargetException; import java.util.*; import javassist.*; import water.api.Request.API; import water.util.Log; import water.util.Log.Tag.Sys; public class Weaver { private final ClassPool _pool; private final CtClass _dtask, _iced, _enum; private final CtClass[] _serBases; private final CtClass _fielddoc; private final CtClass _arg; public static Class _typeMap; public static java.lang.reflect.Method _onLoad; public static volatile String[] _packages = new String[] { "water", "hex", "org.junit" }; Weaver() { try { _pool = ClassPool.getDefault(); _iced = _pool.get("water.Iced"); // Needs serialization _dtask= _pool.get("water.DTask");// Needs serialization and remote execution _enum = _pool.get("java.lang.Enum"); // Needs serialization _serBases = new CtClass[] { _iced, _dtask, _enum, }; for( CtClass c : _serBases ) c.freeze(); _fielddoc = _pool.get("water.api.DocGen$FieldDoc");// Is auto-documentation result _arg = _pool.get("water.api.RequestArguments$Argument"); // Needs auto-documentation } catch( NotFoundException e ) { throw new RuntimeException(e); } } public static void registerPackage(String name) { synchronized( Weaver.class ) { String[] a = _packages; if(Arrays.asList(a).indexOf(name) < 0) { String[] t = Arrays.copyOf(a, a.length + 1); t[t.length-1] = name; _packages = t; } } } public Class weaveAndLoad(String name, ClassLoader cl) { try { CtClass w = javassistLoadClass(name); if( w == null ) return null; return w.toClass(cl, null); } catch( CannotCompileException e ) { throw new RuntimeException(e); } } // See if javaassist can find this class; if so then check to see if it is a // subclass of water.DTask, and if so - alter the class before returning it. private synchronized CtClass javassistLoadClass(String name) { try { if( name.equals("water.Boot") ) return null; CtClass cc = _pool.get(name); // Full Name Lookup if( cc == null ) return null; // Oops? Try the system loader, but expected to work if( !inPackages(cc.getPackageName()) ) return null; for( CtClass base : _serBases ) if( cc.subclassOf(base) ) return javassistLoadClass(cc); return cc; } catch( NotFoundException nfe ) { return null; // Not found? Use the normal loader then } catch( CannotCompileException e ) { // Expected to compile throw new RuntimeException(e); } } private static boolean inPackages(String pack) { if( pack==null ) return false; String[] p = _packages; for( int i = 0; i < p.length; i++ ) if( pack.startsWith(p[i]) ) return true; return false; } private synchronized CtClass javassistLoadClass( CtClass cc ) throws NotFoundException, CannotCompileException { if( cc.isFrozen() ) return cc; // serialize parent javassistLoadClass(cc.getSuperclass()); // Serialize enums first, since we need the raw_enum function for this class for( CtField ctf : cc.getDeclaredFields() ) { CtClass base = ctf.getType(); while( base.isArray() ) base = base.getComponentType(); if( base.subclassOf(_enum) && base != cc ) javassistLoadClass(base); } return addSerializationMethods(cc); } // Returns true if this method pre-exists *in the local class*. // Returns false otherwise, which requires a local method to be injected private static boolean hasExisting( String methname, String methsig, CtBehavior ccms[] ) throws NotFoundException { for( CtBehavior cm : ccms ) if( cm.getName ().equals(methname) && cm.getSignature().equals(methsig ) ) return true; return false; } // This method is handed a CtClass which is known to be a subclass of // water.DTask. Add any missing serialization methods. CtClass addSerializationMethods( CtClass cc ) throws CannotCompileException, NotFoundException { if( cc.subclassOf(_enum) ) exposeRawEnumArray(cc); if( cc.subclassOf(_iced) ) ensureAPImethods(cc); if( cc.subclassOf(_iced) || cc.subclassOf(_dtask) ) { cc.setModifiers(javassist.Modifier.setPublic(cc.getModifiers())); ensureSerMethods(cc); ensureNullaryCtor(cc); ensureNewInstance(cc); ensureType(cc); } cc.freeze(); return cc; } // Expose the raw enum array that all Enums have, so we can directly convert // ordinal values to enum instances. private void exposeRawEnumArray(CtClass cc) throws NotFoundException, CannotCompileException { CtField field; try { field = cc.getField("$VALUES"); } catch( NotFoundException nfe ) { // Eclipse apparently stores this in a different place. field = cc.getField("ENUM$VALUES"); } String body = "public static "+cc.getName()+" raw_enum(int i) { return i==255?null:"+field.getName()+"[i]; } "; try { cc.addMethod(CtNewMethod.make(body,cc)); } catch( CannotCompileException ce ) { Log.warn(Sys.WATER," throw ce; } } // Create a newInstance call which will rapidly make a new object of a // particular type *without* Reflection's overheads. private void ensureNewInstance(CtClass cc) throws NotFoundException, CannotCompileException { CtMethod ccms[] = cc.getDeclaredMethods(); if( !javassist.Modifier.isAbstract(cc.getModifiers()) && !hasExisting("newInstance", "()Lwater/Freezable;", ccms) ) { cc.addMethod(CtNewMethod.make( "public water.Freezable newInstance() {\n" + " return new " +cc.getName()+"();\n" + "}", cc)); } } // The Weaver is called from the SystemLoader, and if it directly calls // TypeMap we end up calling a version of TypeMap loaded through the // SystemLoader - this is a separate version of TypeMap loaded *through* the // weaver... and may have different type mappings. So we avoid the issue by // forcing a call to the pre-woven TypeMap. public Weaver initTypeMap( ClassLoader boot ) { _typeMap = weaveAndLoad("water.TypeMap",boot); try { _onLoad = _typeMap.getMethod("onLoad",String.class); } catch( NoSuchMethodException nsme ) { throw new RuntimeException(nsme); } return this; } // Serialized types support a unique dense integer per-class, so we can do // simple array lookups to get class info. The integer is cluster-wide // unique and determined lazily. private void ensureType(CtClass cc) throws NotFoundException, CannotCompileException { CtMethod ccms[] = cc.getDeclaredMethods(); if( !javassist.Modifier.isAbstract(cc.getModifiers()) && !hasExisting("frozenType", "()I", ccms) ) { // Horrible Reflective Call // Make a horrible reflective call to TypeMap.onLoad because.... // The Weaver is called from the SystemLoader, and if it directly calls // TypeMap we end up calling a version of TypeMap loaded through the // SystemLoader - this is a separate version of TypeMap loaded *through* // the weaver... and may have different type mappings. So we avoid the // issue by forcing a call to the pre-woven TypeMap. if( _onLoad == null ) throw new RuntimeException("Weaver not booted, loading class "+cc.getName()+", add to the BOOTSTRAP_CLASSES list"); Integer I; try { I = (Integer)_onLoad.invoke(null,cc.getName()); } catch( IllegalAccessException iae ) { throw new RuntimeException( iae); } catch( InvocationTargetException ite) { throw new RuntimeException(ite.getTargetException()); } // Build a simple method returning the type token cc.addMethod(CtNewMethod.make("public int frozenType() {" + " return " + I + ";" + "}", cc)); } } private static abstract class FieldFilter { abstract boolean filter( CtField ctf ) throws NotFoundException; } private void ensureAPImethods(CtClass cc) throws NotFoundException, CannotCompileException { CtField ctfs[] = cc.getDeclaredFields(); boolean api = false; for( CtField ctf : ctfs ) if( ctf.getName().equals("API_WEAVER") ) api = true; if( api == false ) return; CtField fielddoc=null; CtField getdoc=null; boolean callsuper = true; for( CtClass base : _serBases ) if( cc.getSuperclass() == base ) callsuper = false; // Auto-gen JSON output to AutoBuffers make_body(cc,ctfs,callsuper, "public water.AutoBuffer writeJSONFields(water.AutoBuffer ab) {\n", " super.writeJSONFields(ab)", " ab.putJSON%z(\"%s\",%s)", " ab.putEnumJSON(\"%s\",%s)", " ab.putJSON%z(\"%s\",%s)", ".put1(',');\n", ";\n return ab;\n}", new FieldFilter() { @Override boolean filter(CtField ctf) throws NotFoundException { Object[] as; try { as = ctf.getAnnotations(); } catch( ClassNotFoundException ex) { throw new NotFoundException("getAnnotations throws ", ex); } API api = null; for(Object o : as) if(o instanceof API) { api = (API) o; break; } return api != null && (api.json() || !isInput(ctf.getType(), api)); } }); // Auto-gen JSON & Args doc method. Requires a structured java object. // Every @API annotated field is either a JSON field, an Argument, or both. // field, and has some associated fields. // H2OHexKey someField2; // Anything derived from RequestArguments$Argument // static final String someField2Help = "some help text"; // static final int someField2MinVar = 1, someField2MaxVar = 1; // String[] someField; // Anything NOT derived from Argument is a JSON field // static final String someFieldHelp = "some help text"; // static final int someFieldMinVar = 1, someFieldMaxVar = 1; // xxxMinVar and xxxMaxVar are optional; if xxxMinVar is missing it // defaults to 1, and if xxxMaxVar is missing it defaults "till now". StringBuilder sb = new StringBuilder(); sb.append("new water.api.DocGen$FieldDoc[] {"); // Get classes in the hierarchy with marker field ArrayList<CtClass> classes = new ArrayList<CtClass>(); CtClass current = cc; while( true ) { // For all self & superclasses classes.add(current); current = current.getSuperclass(); api = false; for( CtField ctf : current.getDeclaredFields() ) if( ctf.getName().equals("API_WEAVER") ) api = true; if( api == false ) break; } // Start with parent classes to get fields in order Collections.reverse(classes); boolean first = true; for(CtClass c : classes) { for( CtField ctf : c.getDeclaredFields() ) { int mods = ctf.getModifiers(); if( javassist.Modifier.isStatic(mods) ) { if( c == cc ) { // Capture the DOC_* fields for self only if( ctf.getName().equals("DOC_FIELDS") ) fielddoc = ctf; if( ctf.getName().equals("DOC_GET") ) getdoc = ctf; } continue; // Only auto-doc instance fields (not static) } first = addDocIfAPI(sb,ctf,cc,first); } } sb.append("}"); if( fielddoc == null ) throw new CannotCompileException("Did not find static final DocGen.FieldDoc[] DOC_FIELDS field;"); if( !fielddoc.getType().isArray() || fielddoc.getType().getComponentType() != _fielddoc ) throw new CannotCompileException("DOC_FIELDS not declared static final DocGen.FieldDoc[];"); cc.removeField(fielddoc); // Remove the old one cc.addField(fielddoc,CtField.Initializer.byExpr(sb.toString())); cc.addMethod(CtNewMethod.make(" public water.api.DocGen$FieldDoc[] toDocField() { return DOC_FIELDS; }",cc)); if( getdoc != null ) cc.addMethod(CtNewMethod.make(" public String toDocGET() { return DOC_GET; }",cc)); } private boolean addDocIfAPI( StringBuilder sb, CtField ctf, CtClass cc, boolean first ) throws NotFoundException, CannotCompileException { String name = ctf.getName(); Object[] as; try { as = ctf.getAnnotations(); } catch( ClassNotFoundException ex) { throw new NotFoundException("getAnnotations throws ", ex); } API api = null; for(Object o : as) if(o instanceof API) api = (API) o; if( api != null ) { String help = api.help(); int min = api.since(); int max = api.until(); if( min < 1 || min > 1000000 ) throw new CannotCompileException("Found field '"+name+"' but 'since' < 1 or 'since' > 1000000"); if( max < min || (max > 1000000 && max != Integer.MAX_VALUE) ) throw new CannotCompileException("Found field '"+name+"' but 'until' < "+min+" or 'until' > 1000000"); if( first ) first = false; else sb.append(","); boolean input = isInput(ctf.getType(), api); sb.append("new water.api.DocGen$FieldDoc(\""+name+"\",\""+help+"\","+min+","+max+","+ctf.getType().getName()+".class,"+input+","+api.required()+")"); } return first; } private final boolean isInput(CtClass fieldType, API api) { return Request2.Helper.isInput(api) || // Legacy fieldType.subclassOf(_arg); } // Support for a nullary constructor, for deserialization. private void ensureNullaryCtor(CtClass cc) throws NotFoundException, CannotCompileException { // Build a null-ary constructor if needed String clzname = cc.getSimpleName(); if( !hasExisting(clzname,"()V",cc.getDeclaredConstructors()) ) { String body = "public "+clzname+"() { }"; cc.addConstructor(CtNewConstructor.make(body,cc)); } else { CtConstructor ctor = cc.getConstructor("()V"); ctor.setModifiers(javassist.Modifier.setPublic(ctor.getModifiers())); } } // Serialization methods: read, write & copyOver. private void ensureSerMethods(CtClass cc) throws NotFoundException, CannotCompileException { // Check for having "read" and "write". Either All or None of read & write // must be defined. Note that I use getDeclaredMethods which returns only // the local methods. The singular getDeclaredMethod searches for a // specific method *up into superclasses*, which will trigger premature // loading of those superclasses. CtMethod ccms[] = cc.getDeclaredMethods(); boolean w = hasExisting("write", "(Lwater/AutoBuffer;)Lwater/AutoBuffer;", ccms); boolean r = hasExisting("read" , "(Lwater/AutoBuffer;)Lwater/Freezable;" , ccms); boolean d = cc.subclassOf(_dtask); // Subclass of DTask? boolean c = hasExisting("copyOver" , "(Lwater/DTask;)V" , ccms); if( w && r && (!d || c) ) return; if( w || r || c ) throw new RuntimeException(cc.getName() +" must implement all of " + "read(AutoBuffer) and write(AutoBuffer) and copyOver(DTask) or none"); // Add the serialization methods: read, write. CtField ctfs[] = cc.getDeclaredFields(); // We cannot call Iced.xxx, as these methods always throw a // RuntimeException (to make sure we noisily fail instead of silently // fail). But we DO need to call the super-chain of serialization methods // - stopping at DTask. boolean callsuper = true; // for( CtClass base : _serBases ) // if( cc.getSuperclass() == base ) callsuper = false; // Running example is: // class Crunk extends DTask { // int _x; int _xs[]; double _d; // Build a write method that looks something like this: // public AutoBuffer write( AutoBuffer s ) { // s.put4(_x); // s.putA4(_xs); // s.put8d(_d); // TODO use Freezable.write instead of AutoBuffer.put for final classes make_body(cc,ctfs,callsuper, "public water.AutoBuffer write(water.AutoBuffer ab) {\n", " super.write(ab);\n", " ab.put%z(%s);\n", " ab.putEnum(%s);\n", " ab.put%z(%s);\n", "", " return ab;\n" + "}", null); // Build a read method that looks something like this: // public T read( AutoBuffer s ) { // _x = s.get4(); // _xs = s.getA4(); // _d = s.get8d(); make_body(cc,ctfs,callsuper, "public water.Freezable read(water.AutoBuffer s) {\n", " super.read(s);\n", " %s = s.get%z();\n", " %s = %c.raw_enum(s.get1());\n", " %s = (%C)s.get%z(%c.class);\n", "", " return this;\n" + "}", null); // Build a copyOver method that looks something like this: // public void copyOver( T s ) { // _x = s._x; // _xs = s._xs; // _d = s._d; if( d ) make_body(cc,ctfs,callsuper, "public void copyOver(water.DTask i) {\n"+ " "+cc.getName()+" s = ("+cc.getName()+")i;\n", " super.copyOver(s);\n", " %s = s.%s;\n", " %s = s.%s;\n", " %s = s.%s;\n", "", "}", null); } // Produce a code body with all these fill-ins. private final void make_body(CtClass cc, CtField[] ctfs, boolean callsuper, String header, String supers, String prims, String enums, String freezables, String field_sep, String trailer, FieldFilter ff ) throws CannotCompileException, NotFoundException { StringBuilder sb = new StringBuilder(); sb.append(header); if( callsuper ) sb.append(supers); boolean debug_print = false; boolean first = !callsuper; for( CtField ctf : ctfs ) { int mods = ctf.getModifiers(); if( javassist.Modifier.isTransient(mods) || javassist.Modifier.isStatic(mods) ) { debug_print |= ctf.getName().equals("DEBUG_WEAVER"); continue; // Only serialize not-transient instance fields (not static) } if( ff != null && !ff.filter(ctf) ) continue; // Fails the filter if( first ) first = false; else sb.append(field_sep); CtClass base = ctf.getType(); while( base.isArray() ) base = base.getComponentType(); int ftype = ftype(cc, ctf.getSignature() ); // Field type encoding if( ftype%20 == 9 ) { sb.append(freezables); } else if( ftype%20 == 10 ) { // Enums sb.append(enums); } else { sb.append(prims); } String z = FLDSZ1[ftype % 20]; for(int i = 0; i < ftype / 20; ++i ) z = 'A'+z; subsub(sb, "%z", z); // %z ==> short type name subsub(sb, "%s", ctf.getName()); // %s ==> field name subsub(sb, "%c", base.getName().replace('$', '.')); // %c ==> base class name subsub(sb, "%C", ctf.getType().getName().replace('$', '.')); // %C ==> full class name } sb.append(trailer); String body = sb.toString(); if( debug_print ) { System.err.println(cc.getName()+" "+body); } try { cc.addMethod(CtNewMethod.make(body,cc)); } catch( CannotCompileException e ) { throw Log.err(" } } static private final String[] FLDSZ1 = { "Z","1","2","2","4","4f","8","8d","Str","","Enum" // prims, String, Freezable, Enum }; // Field types: // 0-7: primitives // 8,9, 10: String, Freezable, Enum // 20-27: array-of-prim // 28,29, 30: array-of-String, Freezable, Enum // Barfs on all others (eg Values or array-of-Frob, etc) private int ftype( CtClass ct, String sig ) throws NotFoundException { switch( sig.charAt(0) ) { case 'Z': return 0; // Booleans: I could compress these more case 'B': return 1; // Primitives case 'C': return 2; case 'S': return 3; case 'I': return 4; case 'F': return 5; case 'J': return 6; case 'D': return 7; case 'L': // Handled classes if( sig.equals("Ljava/lang/String;") ) return 8; String clz = sig.substring(1,sig.length()-1).replace('/', '.'); CtClass argClass = _pool.get(clz); if( argClass.subtypeOf(_pool.get("water.Freezable")) ) return 9; if( argClass.subtypeOf(_pool.get("java.lang.Enum")) ) return 10; break; case '[': // Arrays return ftype(ct, sig.substring(1))+20; // Same as prims, plus 20 } throw barf(ct, sig); } // Replace 2-byte strings like "%s" with s2. static private void subsub( StringBuilder sb, String s1, String s2 ) { int idx; while( (idx=sb.indexOf(s1)) != -1 ) sb.replace(idx,idx+2,s2); } private static RuntimeException barf( CtClass ct, String sig ) { return new RuntimeException(ct.getSimpleName()+"."+sig+": Serialization not implemented"); } }
package wumpus; import java.util.HashSet; import wumpus.Environment.Items; /** * Describes a single board block, that holds information on what have in. */ public class Block { private int x, y, w, h; private HashSet<Items> items = new HashSet<Items>(); /** * The Block constructor. * @param position The linear position in the board * @param width The width of the board * @param height The height of the board */ public Block(int position, int width, int height) { x = position % width; y = position / width; w = width; h = height; reset(); } /** * Returns this block linear position at the board. * @return The linear index */ public int getPosition() { return x + y * w; } /** * Returns some block linear position from a 2D position. * @return The linear index */ public int getPosition(int x, int y) { return x + y * w; } /** * Returns the horizontal position of this block at the board. * @return The X position */ public int getX() { return x; } /** * Returns the vertical position of this block at the board. * @return The Y position */ public int getY() { return y; } /** * Returns the blocks linear position that share the same borders * @return The neighbors array */ public int[] getNeighbors() { int[] neighbors = {-1, -1, -1, 1}; int north = y - 1; int south = y + 1; int west = x - 1; int east = x + 1; if (north >= 0) neighbors[0] = getPosition(x, north); if (south < h) neighbors[1] = getPosition(x, south); if (west >= 0) neighbors[2] = getPosition(west, y); if (east < w) neighbors[2] = getPosition(east, y); return neighbors; } /** * Resets all items on this block. */ public void reset() { items.clear(); } /** * Resets some type of item on this block if has on it. * @param item The item to reset */ public void reset(Items item) { if (items.contains(item)) { items.remove(item); } } /** * Returns weather this block is empty or not. * @return <tt>true</tt> if contains no items */ public boolean isEmpty() { return items.isEmpty(); } /** * Returns weather this block contains the item or not. * @param item The item to find * @return <tt>true</tt> if not contains the given item */ public boolean contains(Items item) { return items.contains(item); } /** * Adds an item to this block. * @param item The item */ public void setItem(Items item) { items.add(item); } }
package org.openforis.collect.relational.util; import static org.openforis.collect.relational.util.Constants.CODE_TABLE_PK_FORMAT; import static org.openforis.collect.relational.util.Constants.TABLE_NAME_QNAME; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.openforis.collect.relational.model.RelationalSchemaConfig; import org.openforis.idm.metamodel.CodeList; import org.openforis.idm.metamodel.CodeListLevel; /** * * @author S. Ricci * */ public class CodeListTables { public static String getTableName(CodeList codeList, Integer levelIdx) { return getTableName(RelationalSchemaConfig.createDefault(), codeList, levelIdx); } public static String getTableName(RelationalSchemaConfig config, CodeList codeList, Integer levelIdx) { String baseTableName = CodeListTables.getBaseTableName(codeList, levelIdx); return baseTableName + config.getCodeListTableSuffix(); } public static String getIdColumnName(String tableName) { return getIdColumnName(RelationalSchemaConfig.createDefault(), tableName); } public static String getIdColumnName(RelationalSchemaConfig config, String tableName) { String result = String.format(CODE_TABLE_PK_FORMAT, tableName, config.getIdColumnSuffix()); return result; } public static String getCodeColumnName(CodeList codeList, Integer hierarchyIdx) { return getBaseTableName(codeList, hierarchyIdx); } public static String getCodeColumnName(String tableName) { return getCodeColumnName(RelationalSchemaConfig.createDefault(), tableName); } public static String getCodeColumnName(RelationalSchemaConfig config, String tableName) { return StringUtils.removeEnd(tableName, config.getCodeListTableSuffix()); } public static String getLabelColumnName(CodeList codeList, Integer levelIdx) { return getLabelColumnName(RelationalSchemaConfig.createDefault(), codeList, levelIdx); } public static String getLabelColumnName(RelationalSchemaConfig config, CodeList codeList, Integer levelIdx) { return getLabelColumnName(config, codeList, levelIdx, null); } public static String getLabelColumnName(String tableName) { return getLabelColumnName(RelationalSchemaConfig.createDefault(), tableName); } public static String getLabelColumnName(RelationalSchemaConfig config, String tableName) { String baseName = extractBaseTableName(config, tableName); return getLabelColumnName(config, baseName, null); } public static String getLabelColumnName(CodeList codeList, Integer levelIdx, String langCode) { return getLabelColumnName(RelationalSchemaConfig.createDefault(), codeList, levelIdx, langCode); } public static String getLabelColumnName(RelationalSchemaConfig config, CodeList codeList, Integer levelIdx, String langCode) { String baseTableName = getBaseTableName(codeList, levelIdx); return getLabelColumnName(config, baseTableName, langCode); } private static String getLabelColumnName(RelationalSchemaConfig config, String baseTableName, String langCode) { StringBuilder sb = new StringBuilder(64); sb.append(baseTableName); sb.append(config.getLabelColumnSuffix()); if ( StringUtils.isNotBlank(langCode) ) { sb.append("_"); sb.append(langCode); } return sb.toString(); } public static String getDescriptionColumnName(String tableName) { return getDescriptionColumnName(RelationalSchemaConfig.createDefault(), tableName); } public static String getDescriptionColumnName(RelationalSchemaConfig config, String tableName) { String baseName = extractBaseTableName(config, tableName); return getDescriptionColumnName(config, baseName, null); } public static String getDescriptionColumnName(CodeList codeList, Integer levelIdx) { return getDescriptionColumnName(RelationalSchemaConfig.createDefault(), codeList, levelIdx); } public static String getDescriptionColumnName(RelationalSchemaConfig config, CodeList codeList, Integer levelIdx) { return getDescriptionColumnName(config, codeList, levelIdx, null); } public static String getDescriptionColumnName(CodeList codeList, Integer levelIdx, String langCode) { return getDescriptionColumnName(RelationalSchemaConfig.createDefault(), codeList, levelIdx, langCode); } public static String getDescriptionColumnName(RelationalSchemaConfig config, CodeList codeList, Integer levelIdx, String langCode) { String baseTableName = getBaseTableName(codeList, levelIdx); return getDescriptionColumnName(config, baseTableName, langCode); } protected static String getDescriptionColumnName(RelationalSchemaConfig config, String baseTableName, String langCode) { StringBuilder sb = new StringBuilder(64); sb.append(baseTableName); sb.append(config.getDescriptionColumnSuffix()); if ( StringUtils.isNotBlank(langCode) ) { sb.append("_"); sb.append(langCode); } return sb.toString(); } private static String getBaseTableName(CodeList codeList, Integer levelIdx) { StringBuilder sb = new StringBuilder(); String tableNameAnnotation = codeList.getAnnotation(TABLE_NAME_QNAME); if ( tableNameAnnotation == null ) { sb.append(codeList.getName()); } else { sb.append(tableNameAnnotation); } if ( levelIdx != null ) { List<CodeListLevel> hierarchy = codeList.getHierarchy(); CodeListLevel currentLevel = hierarchy.get(levelIdx); sb.append("_"); sb.append(currentLevel.getName()); } return sb.toString(); } private static String extractBaseTableName(RelationalSchemaConfig config, String tableName) { String baseName = StringUtils.removeEnd(tableName, config.getCodeListTableSuffix()); return baseName; } }
// P a n e l // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.ui.util; import omr.constant.Constant; import omr.constant.ConstantSet; import omr.ui.PixelCount; import omr.util.Logger; import com.jgoodies.forms.layout.FormLayout; import java.awt.Graphics; import java.awt.Insets; import javax.swing.JPanel; /** * Class <code>Panel</code> is a JPanel with specific features to define * and position label and text fields. * * <P><B>note</B> : To actually display the cell limits as a debugging aid * to refine the panel layout, you have to edit this class and make it * extend FormDebugPanel, instead of JPanel. There is also a line to * uncomment in both methods : the constructor and the paintComponent * method. * * * @author Herv&eacute; Bitteur * @version $Id$ */ public class Panel extends JPanel { /** Specific application parameters */ private static final Constants constants = new Constants(); /** Usual logger utility */ private static final Logger logger = Logger.getLogger(Panel.class); /** Default Insets */ private static Insets DEFAULT_INSETS; /** Room for potential specific insets */ private Insets insets; /** * Creates a new Panel object. */ public Panel () { // XXX Uncomment following line for FormDebugPanel XXX //setPaintInBackground(true); } /** * Selector to the default button width * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getButtonWidth () { return constants.buttonWidth.getValue(); } /** * Selector to the default vertical interval between two rows * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getFieldInterline () { return constants.fieldInterline.getValue(); } /** * Selector to the default interval between two label/field * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getFieldInterval () { return constants.fieldInterval.getValue(); } /** * Selector to the default label width * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getFieldWidth () { return constants.fieldWidth.getValue(); } // setInsets // /** * Set the panel insets (in number of pixels) on the four directions * * @param top inset on top side * @param left inset on the left side * @param bottom inset on the bottom side * @param right inset on the right side */ public void setInsets (int top, int left, int bottom, int right) { insets = new Insets(top, left, bottom, right); } // getInsets // /** * By this way, Swing will paint the component with its specific inset * values * * @return the panel insets */ @Override public Insets getInsets () { if (insets != null) { return insets; } else { return getDefaultInsets(); } } /** * Selector to the default label - field interval * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getLabelInterval () { return constants.labelInterval.getValue(); } /** * Selector to the default label width * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getLabelWidth () { return constants.labelWidth.getValue(); } // setNoInsets // /** * A convenient method to set all 4 insets values to zero */ public void setNoInsets () { insets = new Insets(0, 0, 0, 0); } /** * Selector to the default vertical interval between two Panels * * @return default distance in JGoodies/Forms units (such as DLUs) */ public static String getPanelInterline () { return constants.panelInterline.getValue(); } // makeFormLayout // /** * Build a JGoodies Forms layout, based on the provided number of rows * and number of columns, using default values for label alignment, and * for widths of labels and fields * * @param rows number of logical rows (not counting the interlines) * @param cols number of logical columns (counting the combination of a * label and its related field as just one column) * @return the FormLayout ready to use */ public static FormLayout makeFormLayout (int rows, int cols) { return makeFormLayout( rows, cols, "right:", Panel.getLabelWidth(), Panel.getFieldWidth()); } // makeFormLayout // /** * A more versatile way to prepare a JGoodies FormLayout * * @param rows number of rows * @param cols number of columns * @param labelAlignment horizontal alignment for labels * @param labelWidth width for labels * @param fieldWidth width for text fields * @return the FormLayout ready to use */ public static FormLayout makeFormLayout (int rows, int cols, String labelAlignment, String labelWidth, String fieldWidth) { final String labelInterval = Panel.getLabelInterval(); final String fieldInterval = Panel.getFieldInterval(); final String fieldInterline = Panel.getFieldInterline(); // Columns StringBuffer sbc = new StringBuffer(); for (int i = cols - 1; i >= 0; i sbc.append(labelAlignment) .append(labelWidth) .append(",") .append(labelInterval) .append(",") .append(fieldWidth); if (i != 0) { sbc.append(",") .append(fieldInterval) .append(","); } } // Rows StringBuffer sbr = new StringBuffer(); for (int i = rows - 1; i >= 0; i sbr.append("pref"); if (i != 0) { sbr.append(",") .append(fieldInterline) .append(","); } } if (logger.isFineEnabled()) { logger.fine("sbc=" + sbc); logger.fine("sbr=" + sbr); } return new FormLayout(sbc.toString(), sbr.toString()); } // paintComponent // /** * This method is redefined to give a chance to draw the cell * boundaries if so desired * * @param g the graphic context */ @Override protected void paintComponent (Graphics g) { // XXX Uncomment following line for FormDebugPanel XXX //setPaintInBackground(true); super.paintComponent(g); } // getDefaultInsets // private Insets getDefaultInsets () { if (DEFAULT_INSETS == null) { DEFAULT_INSETS = new Insets( constants.insetTop.getValue(), constants.insetLeft.getValue(), constants.insetBottom.getValue(), constants.insetRight.getValue()); } return DEFAULT_INSETS; } // Constants // private static final class Constants extends ConstantSet { Constant.String buttonWidth = new Constant.String( "45dlu", "Width of a standard button"); Constant.String fieldInterline = new Constant.String( "1dlu", "Vertical Gap between two lines"); Constant.String fieldInterval = new Constant.String( "3dlu", "Horizontal gap between two fields"); Constant.String fieldWidth = new Constant.String( "35dlu", "Width of a field value"); PixelCount insetBottom = new PixelCount( 6, "Value of Bottom inset"); PixelCount insetLeft = new PixelCount(6, "Value of Left inset"); PixelCount insetRight = new PixelCount(6, "Value of Right inset"); PixelCount insetTop = new PixelCount(6, "Value of Top inset"); Constant.String labelInterval = new Constant.String( "1dlu", "Gap between a field label and its field value"); Constant.String labelWidth = new Constant.String( "25dlu", "Width of the label of a field"); Constant.String panelInterline = new Constant.String( "6dlu", "Vertical Gap between two panels"); } }
package org.openforis.collect.designer.viewmodel; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.openforis.collect.designer.component.SchemaTreeModel; import org.openforis.collect.designer.component.SchemaTreeModel.SchemaNodeData; import org.openforis.collect.designer.component.SchemaTreeModel.SchemaTreeNode; import org.openforis.collect.designer.component.SchemaTreeModelCreator; import org.openforis.collect.designer.component.SurveyObjectTreeModelCreator; import org.openforis.collect.designer.component.UITreeModelCreator; import org.openforis.collect.designer.model.AttributeType; import org.openforis.collect.designer.model.LabelKeys; import org.openforis.collect.designer.model.NodeType; import org.openforis.collect.designer.util.MessageUtil; import org.openforis.collect.designer.util.Predicate; import org.openforis.collect.designer.util.Resources; import org.openforis.collect.metamodel.ui.UIOptions; import org.openforis.collect.metamodel.ui.UIOptions.Layout; import org.openforis.collect.metamodel.ui.UITab; import org.openforis.collect.metamodel.ui.UITabSet; import org.openforis.collect.model.CollectSurvey; import org.openforis.idm.metamodel.AttributeDefinition; import org.openforis.idm.metamodel.EntityDefinition; import org.openforis.idm.metamodel.ModelVersion; import org.openforis.idm.metamodel.NodeDefinition; import org.openforis.idm.metamodel.NodeLabel.Type; import org.openforis.idm.metamodel.Schema; import org.openforis.idm.metamodel.SurveyObject; import org.zkoss.bind.BindUtils; import org.zkoss.bind.Binder; import org.zkoss.bind.annotation.AfterCompose; import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.ContextParam; import org.zkoss.bind.annotation.ContextType; import org.zkoss.bind.annotation.DependsOn; import org.zkoss.bind.annotation.GlobalCommand; import org.zkoss.bind.annotation.Init; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.util.resource.Labels; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.IdSpace; import org.zkoss.zk.ui.Path; import org.zkoss.zk.ui.select.Selectors; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zul.Include; import org.zkoss.zul.Menupopup; import org.zkoss.zul.Tree; import org.zkoss.zul.TreeNode; import org.zkoss.zul.Treeitem; import org.zkoss.zul.Window; /** * * @author S. Ricci * */ @VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class) public class SchemaVM extends SurveyBaseVM { public static final String DEFAULT_ROOT_ENTITY_NAME = "change_it_to_your_record_type"; public static final String DEFAULT_MAIN_TAB_LABEL = "Change it to your main tab label"; private static final String PATH_NULL_VALUES_REPLACE = "..."; private static final String NODE_TYPES_IMAGES_PATH = "/assets/images/node_types/"; private static final String SCHEMA_CHANGED_GLOBAL_COMMAND = "schemaChanged"; private static final String VALIDATE_COMMAND = "validate"; private static final String APPLY_CHANGES_COMMAND = "applyChanges"; private static final String CONFIRM_REMOVE_NODE_MESSAGE_KEY = "survey.schema.confirm_remove_node"; private static final String CONFIRM_REMOVE_NON_EMPTY_ENTITY_MESSAGE_KEY = "survey.schema.confirm_remove_non_empty_entity"; private static final String CONFIRM_REMOVE_NODE_WITH_DEPENDENCIES_MESSAGE_KEY = "survey.schema.confirm_remove_node_with_dependencies"; private static final String CONFIRM_REMOVE_NODE_TITLE_KEY = "survey.schema.confirm_remove_node_title"; private SchemaNodeData selectedTreeNode; private SurveyObject editedNode; private boolean newNode; private EntityDefinition selectedRootEntity; private UITabSet rootTabSet; private ModelVersion selectedVersion; private String selectedTreeViewType; private EntityDefinition editedNodeParentEntity; @Wire private Include nodeFormInclude; @Wire private Tree nodesTree; @Wire private Menupopup mainTabPopup; @Wire private Menupopup tabPopup; @Wire private Menupopup singleEntityPopup; @Wire private Menupopup tableEntityPopup; @Wire private Menupopup formEntityPopup; @Wire private Menupopup attributePopup; @Wire private Menupopup detachedNodePopup; //transient private Window rootEntityEditPopUp; private Window nodeMovePopUp; private SchemaTreeModel treeModel; public enum TreeViewType { ENTRY, DATA } @Override @Init(superclass=false) public void init() { super.init(); } @AfterCompose public void doAfterCompose(@ContextParam(ContextType.VIEW) Component view){ Selectors.wireComponents(view, this, false); Selectors.wireEventListeners(view, this); selectedTreeViewType = TreeViewType.ENTRY.name().toLowerCase(); //select first root entity List<EntityDefinition> rootEntities = getRootEntities(); if (rootEntities.size() > 0) { EntityDefinition mainRootEntity = rootEntities.get(0); performNodeTreeFilterChange(mainRootEntity, null); } } @Command public void nodeSelected(@ContextParam(ContextType.BINDER) final Binder binder, @ContextParam(ContextType.VIEW) final Component view, @BindingParam("data") final SchemaNodeData data) { if ( data != null ) { checkCanLeaveForm(new CanLeaveFormCompleteConfirmHandler() { @Override public void onOk(boolean confirmed) { if ( confirmed ) { undoLastChanges(view); } performSelectNode(binder, data); } @Override public void onCancel() { treeModel.select(selectedTreeNode); } }); } else { resetEditingStatus(); } } @Command public void rootEntitySelected(@BindingParam("rootEntity") final EntityDefinition rootEntity) { nodesTreeFilterChanged(rootEntity, selectedVersion); } @Command public void versionSelected(@BindingParam("version") ModelVersion version) { nodesTreeFilterChanged(selectedRootEntity, version); } protected void nodesTreeFilterChanged(final EntityDefinition rootEntity, final ModelVersion version) { checkCanLeaveForm(new CanLeaveFormCompleteConfirmHandler() { @Override public void onOk(boolean confirmed) { performNodeTreeFilterChange(rootEntity, version); } @Override public void onCancel() { notifyChange("selectedRootEntity","selectedVersion"); } }); } private void performNodeTreeFilterChange(EntityDefinition rootEntity, ModelVersion version) { selectedRootEntity = rootEntity; rootTabSet = survey.getUIOptions().getAssignedRootTabSet(rootEntity); selectedVersion = version; resetEditingStatus(); refreshTreeModel(); dispatchCurrentFormValidatedCommand(true, isCurrentFormBlocking()); notifyChange("selectedTreeNode","selectedRootEntity","selectedVersion","treeModel"); } protected void performSelectNode(Binder binder, SchemaNodeData data) { selectedTreeNode = data; treeModel.select(data); SurveyObject surveyObject = data.getSurveyObject(); EntityDefinition parentDefn = treeModel.getNearestParentEntityDefinition(surveyObject); editNode(binder, false, parentDefn, surveyObject); } @Command public void addRootEntity() { checkCanLeaveForm(new CanLeaveFormConfirmHandler() { @Override public void onOk(boolean confirmed) { resetNodeSelection(); resetEditingStatus(); EntityDefinition rootEntity = createRootEntityDefinition(); selectedRootEntity = rootEntity; selectedVersion = null; refreshTreeModel(); selectTreeNode(null); notifyChange("selectedRootEntity","selectedVersion"); editRootEntity(); } }); } @Command public void addEntity(@ContextParam(ContextType.BINDER) final Binder binder, @BindingParam("multiple") boolean multiple, @BindingParam("layout") String layout) { resetNodeSelection(); addChildEntity(binder, multiple, layout); } @Command public void addChildEntity(@ContextParam(ContextType.BINDER) final Binder binder, @BindingParam("multiple") final boolean multiple, @BindingParam("layout") final String layout) { checkCanLeaveForm(new CanLeaveFormConfirmHandler() { @Override public void onOk(boolean confirmed) { EntityDefinition parentEntity = getSelectedNodeParentEntity(); EntityDefinition newNode = createEntityDefinition(); newNode.setMultiple(multiple); UIOptions uiOptions = survey.getUIOptions(); Layout layoutEnum = Layout.valueOf(layout); SurveyObject selectedSurveyObject = selectedTreeNode.getSurveyObject(); UITab parentTab = null; if ( selectedSurveyObject instanceof UITab ) { parentTab = (UITab) selectedSurveyObject; } if ( uiOptions.isLayoutSupported(parentEntity, newNode.getId(), parentTab, multiple, layoutEnum) ) { uiOptions.setLayout(newNode, layoutEnum); if ( parentTab != null ) { uiOptions.assignToTab(newNode, parentTab); } editNode(binder, true, parentEntity, newNode); afterNewNodeCreated(newNode, true); } else { MessageUtil.showWarning(LabelKeys.LAYOUT_NOT_SUPPORTED_MESSAGE_KEY); } } }); } private EntityDefinition getSelectedNodeParentEntity() { if ( selectedTreeNode == null ) { return selectedRootEntity; } else { SurveyObject surveyObject = selectedTreeNode.getSurveyObject(); if ( surveyObject instanceof EntityDefinition ) { return (EntityDefinition) surveyObject; } else { EntityDefinition parentEntity = treeModel.getNearestParentEntityDefinition(surveyObject); return parentEntity; } } } @Command public void addAttribute(@ContextParam(ContextType.BINDER) final Binder binder, @BindingParam("attributeType") final String attributeType) throws Exception { resetNodeSelection(); addChildAttribute(binder, attributeType); } @Command public void addChildAttribute(@ContextParam(ContextType.BINDER) final Binder binder, @BindingParam("attributeType") final String attributeType) throws Exception { checkCanLeaveForm(new CanLeaveFormConfirmHandler() { @Override public void onOk(boolean confirmed) { AttributeType attributeTypeEnum = AttributeType.valueOf(attributeType); AttributeDefinition newNode = (AttributeDefinition) NodeType.createNodeDefinition(survey, NodeType.ATTRIBUTE, attributeTypeEnum); EntityDefinition parentEntity = getSelectedNodeParentEntity(); SurveyObject selectedSurveyObject = selectedTreeNode.getSurveyObject(); if ( selectedSurveyObject instanceof UITab ) { UIOptions uiOptions = survey.getUIOptions(); uiOptions.assignToTab(newNode, (UITab) selectedSurveyObject); } editNode(binder, true, parentEntity, newNode); afterNewNodeCreated(newNode, true); } }); } private void afterNewNodeCreated(SurveyObject surveyObject, boolean detached) { treeModel.appendNodeToSelected(surveyObject, detached); selectTreeNode(surveyObject); //workaround: tree nodes not refreshed when adding child to "leaf" nodes (i.e. empty entity) notifyChange("treeModel"); } @Command public void expandTree() { treeModel.openAllItems(); notifyChange("treeModel"); } @Command public void collapseTree() { treeModel.clearOpen(); notifyChange("treeModel"); } @Override @GlobalCommand public void undoLastChanges(@ContextParam(ContextType.VIEW) Component view) { if ( editedNode != null ) { if ( newNode ) { treeModel.select(editedNode); treeModel.removeSelectedNode(); } else { //restore committed label into tree node String committedLabel = editedNode instanceof NodeDefinition ? ((NodeDefinition) editedNode).getName(): ((UITab) editedNode).getLabel(currentLanguageCode); updateTreeNodeLabel(view, editedNode, committedLabel); } resetEditingStatus(false); } } @GlobalCommand public void editedNodeNameChanging( @ContextParam(ContextType.VIEW) Component view, @BindingParam("item") SurveyObject item, @BindingParam("name") String name) { if ( editedNode != null && editedNode == item ) { updateTreeNodeLabel(view, editedNode, name); } } private void updateTreeNodeLabel(Component view, SurveyObject item, String label) { treeModel.updateNodeLabel(item, label); for (Treeitem treeItem : nodesTree.getItems()) { SchemaTreeNode node = treeItem.getValue(); SchemaNodeData data = node.getData(); SurveyObject itemSO = data.getSurveyObject(); if ( itemSO == item ) { treeItem.setLabel(label); } } } @Override @GlobalCommand public void currentLanguageChanged() { super.currentLanguageChanged(); refreshTreeModel(); } protected void resetEditingStatus() { resetEditingStatus(true); } protected void resetEditingStatus(boolean notifyChange) { resetNodeSelection(); editedNode = null; editedNodeParentEntity = null; refreshNodeForm(); if ( notifyChange ) { notifyChange("editedNodeParentEntity","editedNode"); } } protected void resetNodeSelection() { selectedTreeNode = null; notifyChange("selectedTreeNode"); resetTreeSelection(); } protected void resetTreeSelection() { if ( treeModel != null ) { treeModel.deselect(); } } protected void selectTreeNode(SurveyObject surveyObject) { treeModel.select(surveyObject); selectedTreeNode = treeModel.getNodeData(surveyObject); notifyChange("selectedTreeNode"); //BindUtils.postNotifyChange(null, null, selectedTreeNode, "*"); } @Override @GlobalCommand public void versionsUpdated() { super.versionsUpdated(); if ( selectedVersion != null && ! survey.getVersions().contains(selectedVersion) ) { resetEditingStatus(); selectedVersion = null; refreshTreeModel(); notifyChange("selectedVersion"); } } protected void editNode(Binder binder, boolean newNode, EntityDefinition parentEntity, SurveyObject node) { this.newNode = newNode; editedNodeParentEntity = parentEntity; editedNode = node; if ( ! newNode ) { selectedTreeNode = treeModel.getNodeData(node); } refreshNodeForm(); validateForm(binder); notifyChange("selectedTreeNode","editedNode"); } protected void refreshNodeForm() { nodeFormInclude.setSrc(null); if ( editedNode != null ) { nodeFormInclude.setDynamicProperty("parentEntity", editedNodeParentEntity); nodeFormInclude.setDynamicProperty("item", editedNode); nodeFormInclude.setDynamicProperty("newItem", newNode); String location; if ( editedNode instanceof UITab ) { location = Resources.Component.TAB.getLocation(); } else if ( editedNode instanceof EntityDefinition ) { location = Resources.Component.ENTITY.getLocation(); } else { AttributeType attributeType = AttributeType.valueOf((AttributeDefinition) editedNode); location = Resources.Component.ATTRIBUTE.getLocation(); String attributeTypeShort = attributeType.name().toLowerCase(); location = MessageFormat.format(location, attributeTypeShort); } nodeFormInclude.setSrc(location); } } protected void validateForm() { if ( editedNode != null ) { Binder binder = (Binder) nodeFormInclude.getAttribute("$BINDER$"); validateForm(binder); } else { dispatchCurrentFormValidatedCommand(true); } } protected void validateForm(@ContextParam(ContextType.BINDER) Binder binder) { Component view = binder.getView(); IdSpace idSpace = view.getSpaceOwner(); Binder formComponentBinder = getNodeFormBinder(idSpace); formComponentBinder.postCommand(VALIDATE_COMMAND, null); } protected Binder getNodeFormBinder(IdSpace idSpace) { Component formComponent = getNodeFormComponent(idSpace); Binder formComponentBinder = (Binder) formComponent.getAttribute("binder"); return formComponentBinder; } protected Component getNodeFormComponent(IdSpace idSpace) { Component component = Path.getComponent(idSpace, "nodeFormInclude/nodeFormContainer"); return component; } protected void applyChangesToForm(IdSpace idSpace) { Binder binder = getNodeFormBinder(idSpace); binder.postCommand(APPLY_CHANGES_COMMAND, null); } @Command public void removeNode() { removeTreeNode(selectedTreeNode); } private void removeTreeNode(final SchemaNodeData data) { if ( data.isDetached() ) { performRemoveDetachedNode(); } else { SurveyObject surveyObject = data.getSurveyObject(); if ( surveyObject instanceof NodeDefinition ) { removeNodeDefinition((NodeDefinition) surveyObject); } else { removeTab((UITab) surveyObject); } } } protected void removeNodeDefinition(final NodeDefinition nodeDefn) { String confirmMessageKey; if (nodeDefn instanceof EntityDefinition && !((EntityDefinition) nodeDefn).getChildDefinitions().isEmpty() ) { confirmMessageKey = CONFIRM_REMOVE_NON_EMPTY_ENTITY_MESSAGE_KEY; } else if ( nodeDefn.hasDependencies() ) { confirmMessageKey = CONFIRM_REMOVE_NODE_WITH_DEPENDENCIES_MESSAGE_KEY; } else { confirmMessageKey = CONFIRM_REMOVE_NODE_MESSAGE_KEY; } NodeType type = NodeType.valueOf(nodeDefn); String typeLabel = type.getLabel().toLowerCase(); boolean isRootEntity = nodeDefn.getParentDefinition() == null; if ( isRootEntity ) { typeLabel = Labels.getLabel("survey.schema.root_entity"); } Object[] messageArgs = new String[] {typeLabel, nodeDefn.getName()}; Object[] titleArgs = new String[] {typeLabel}; MessageUtil.showConfirm(new MessageUtil.ConfirmHandler() { @Override public void onOk() { performRemoveNode(nodeDefn); } }, confirmMessageKey, messageArgs, CONFIRM_REMOVE_NODE_TITLE_KEY, titleArgs, "global.remove_item", "global.cancel"); } @Command public void removeRootEntity() { removeNodeDefinition(selectedRootEntity); } @Command public void editRootEntity() { Map<String, Object> args = new HashMap<String, Object>(); args.put("formLocation", Resources.Component.ENTITY.getLocation()); args.put("title", Labels.getLabel("survey.layout.root_entity")); args.put("parentEntity", null); args.put("item", selectedRootEntity); args.put("newItem", false); rootEntityEditPopUp = openPopUp(Resources.Component.NODE_EDIT_POPUP.getLocation(), true, args); } @Command public void closeNodeEditPopUp() { checkCanLeaveForm(new CanLeaveFormConfirmHandler() { @Override public void onOk(boolean confirmed) { closePopUp(rootEntityEditPopUp); rootEntityEditPopUp = null; } }); } @Command public void moveNodeUp() { moveNode(true); } @Command public void moveNodeDown() { moveNode(false); } protected void moveNode(boolean up) { SurveyObject surveyObject = selectedTreeNode.getSurveyObject(); List<SurveyObject> siblings = getSiblingsInTree(surveyObject); int oldIndex = siblings.indexOf(surveyObject); int newIndexInTree = up ? oldIndex - 1: oldIndex + 1; moveNode(newIndexInTree); } protected void moveNode(int newIndexInTree) { SurveyObject surveyObject = selectedTreeNode.getSurveyObject(); List<SurveyObject> siblings = getSiblingsInTree(surveyObject); SurveyObject newIndexItem = siblings.get(newIndexInTree); SchemaTreeNode newIndexNode = treeModel.getTreeNode(newIndexItem); int newIndexInModel = newIndexNode.getIndexInModel(); if ( surveyObject instanceof NodeDefinition ) { NodeDefinition nodeDefn = (NodeDefinition) surveyObject; EntityDefinition parentEntity = nodeDefn.getParentEntityDefinition(); if ( parentEntity != null ) { parentEntity.moveChildDefinition(nodeDefn, newIndexInModel); } else { EntityDefinition rootEntity = nodeDefn.getRootEntity(); Schema schema = rootEntity.getSchema(); schema.moveRootEntityDefinition(rootEntity, newIndexInModel); } } else { UITab tab = (UITab) surveyObject; UITabSet parent = tab.getParent(); parent.moveTab(tab, newIndexInModel); } treeModel.moveSelectedNode(newIndexInTree); notifyChange("treeModel","moveNodeUpDisabled","moveNodeDownDisabled"); dispatchSchemaChangedCommand(); } protected void performRemoveDetachedNode() { treeModel.removeSelectedNode(); notifyChange("treeModel"); resetEditingStatus(); dispatchCurrentFormValidatedCommand(true); } protected void performRemoveNode(NodeDefinition nodeDefn) { EntityDefinition parentDefn = (EntityDefinition) nodeDefn.getParentDefinition(); if ( parentDefn == null ) { //root entity UIOptions uiOpts = survey.getUIOptions(); UITabSet tabSet = uiOpts.getAssignedRootTabSet((EntityDefinition) nodeDefn); uiOpts.removeTabSet(tabSet); Schema schema = nodeDefn.getSchema(); String nodeName = nodeDefn.getName(); schema.removeRootEntityDefinition(nodeName); selectedRootEntity = null; rootTabSet = null; notifyChange("selectedRootEntity"); refreshTreeModel(); } else { if ( treeModel != null ) { treeModel.removeSelectedNode(); notifyChange("treeModel"); } parentDefn.removeChildDefinition(nodeDefn); } resetEditingStatus(); dispatchCurrentFormValidatedCommand(true); dispatchSchemaChangedCommand(); } @GlobalCommand public void editedNodeChanged(@ContextParam(ContextType.VIEW) Component view, @BindingParam("parentEntity") EntityDefinition parentEntity, @BindingParam("node") SurveyObject editedNode, @BindingParam("newItem") Boolean newNode) { if ( parentEntity == null && editedNode instanceof EntityDefinition ) { //root entity EntityDefinition rootEntity = (EntityDefinition) editedNode; updateRootTabLabel(view, rootEntity); } else { if ( newNode ) { //editing tab or nested node definition //update tree node selectedTreeNode.setDetached(false); BindUtils.postNotifyChange(null, null, selectedTreeNode, "detached"); this.newNode = false; notifyChange("newNode"); selectTreeNode(editedNode); } notifyChange("editedNodePath"); //to be called when not notifying changes on treeModel refreshSelectedTreeNode(view); } dispatchSchemaChangedCommand(); } private void updateRootTabLabel(Component view, EntityDefinition rootEntity) { UITab mainTab = survey.getUIOptions().getMainTab(rootTabSet); if ( DEFAULT_MAIN_TAB_LABEL.equals(mainTab.getLabel(currentLanguageCode))) { String label = rootEntity.getLabel(Type.INSTANCE, currentLanguageCode); if ( StringUtils.isNotBlank(label) ) { mainTab.setLabel(currentLanguageCode, label); updateTreeNodeLabel(view, mainTab, label); } } } protected void refreshSelectedTreeNode(Component view) { Treeitem selectedItem = nodesTree.getSelectedItem(); SchemaTreeNode treeNode = selectedItem.getValue(); SchemaNodeData data = treeNode.getData(); //update context menu Menupopup popupMenu = getPopupMenu(data); selectedItem.setContext(popupMenu); } protected EntityDefinition createRootEntityDefinition() { EntityDefinition rootEntity = createEntityDefinition(); rootEntity.setName(DEFAULT_ROOT_ENTITY_NAME); survey.getSchema().addRootEntityDefinition(rootEntity); UIOptions uiOptions = survey.getUIOptions(); rootTabSet = uiOptions.createRootTabSet((EntityDefinition) rootEntity); UITab mainTab = uiOptions.getMainTab(rootTabSet); mainTab.setLabel(currentLanguageCode, DEFAULT_MAIN_TAB_LABEL); return rootEntity; } protected EntityDefinition createEntityDefinition() { Schema schema = survey.getSchema(); EntityDefinition newNode = schema.createEntityDefinition(); return newNode; } protected void dispatchSchemaChangedCommand() { BindUtils.postGlobalCommand(null, null, SCHEMA_CHANGED_GLOBAL_COMMAND, null); } public SchemaTreeModel getTreeModel() { if ( treeModel == null ) { buildTreeModel(); } return treeModel; } protected void buildTreeModel() { CollectSurvey survey = getSurvey(); if ( survey == null ) { //TODO session expired...? } else { TreeViewType viewType = TreeViewType.valueOf(selectedTreeViewType.toUpperCase()); SurveyObjectTreeModelCreator modelCreator; switch (viewType) { case ENTRY: modelCreator = new UITreeModelCreator(selectedVersion, null, true, currentLanguageCode); break; default: modelCreator = new SchemaTreeModelCreator(selectedVersion, null, true, currentLanguageCode); } treeModel = modelCreator.createModel(selectedRootEntity); } } protected boolean isVersionSelected() { return survey.getVersions().isEmpty() || selectedVersion != null; } protected void refreshTreeModel() { //keep track of previous opened nodes Set<SurveyObject> openNodes; if (treeModel == null) { openNodes = Collections.emptySet(); } else { openNodes = treeModel.getOpenSchemaNodes(); } buildTreeModel(); if ( treeModel != null ) { treeModel.setOpenSchemaNodes(openNodes); treeModel.select(editedNode); treeModel.showSelectedNode(); if ( CollectionUtils.isEmpty(treeModel.getSelection()) ) { resetEditingStatus(); } } notifyChange("treeModel"); } public boolean isTab(SchemaNodeData data) { return data != null && data.getSurveyObject() instanceof UITab; } public boolean isMainTab(SchemaNodeData data) { if ( isTab(data) ) { UIOptions uiOptions = survey.getUIOptions(); return uiOptions.isMainTab((UITab) data.getSurveyObject()); } else { return false; } } public boolean isEntity(SchemaNodeData data) { return data != null && data.getSurveyObject() instanceof EntityDefinition; } public boolean isSingleEntity(SchemaNodeData data) { return isEntity(data) && ! ((NodeDefinition) data.getSurveyObject()).isMultiple(); } public boolean isTableEntity(SchemaNodeData data) { if ( isEntity(data) ) { UIOptions uiOptions = survey.getUIOptions(); EntityDefinition entityDefn = (EntityDefinition) data.getSurveyObject(); Layout layout = uiOptions.getLayout(entityDefn); return layout == Layout.TABLE; } else { return false; } } protected List<SurveyObject> getSiblingsInTree(SurveyObject surveyObject) { List<SurveyObject> result = treeModel.getSiblingsAndSelf(surveyObject, true); return result; } @DependsOn("selectedTreeNode") public boolean isMoveNodeUpDisabled() { return isMoveNodeDisabled(true); } @DependsOn("selectedTreeNode") public boolean isMoveNodeDownDisabled() { return isMoveNodeDisabled(false); } protected boolean isMoveNodeDisabled(boolean up) { if ( newNode || selectedTreeNode == null || isMainTab(selectedTreeNode) ) { return true; } else { SurveyObject surveyObject = selectedTreeNode.getSurveyObject(); List<SurveyObject> siblings = getSiblingsInTree(surveyObject); int index = siblings.indexOf(surveyObject); return isMoveItemDisabled(siblings, index, up); } } protected boolean isMoveItemDisabled(List<?> siblings, int index, boolean up) { return up ? index <= 0: index < 0 || index >= siblings.size() - 1; } @DependsOn({"newNode","editedNode"}) public String getNodeTypeHeaderLabel() { if ( editedNode != null ) { if ( editedNode instanceof NodeDefinition ) { return NodeType.getHeaderLabel((NodeDefinition) editedNode, editedNodeParentEntity == null, newNode); } else { return Labels.getLabel("survey.schema.node.layout.tab"); } } else { return null; } } @DependsOn("editedNode") public String getNodeType() { if ( editedNode != null && editedNode instanceof NodeDefinition ) { NodeType type = NodeType.valueOf((NodeDefinition) editedNode); return type.name(); } else { return null; } } @DependsOn("editedNode") public String getAttributeType() { if ( editedNode != null && editedNode instanceof AttributeDefinition ) { AttributeType type = AttributeType.valueOf((AttributeDefinition) editedNode); return type.name(); } else { return null; } } @DependsOn("editedNode") public String getAttributeTypeLabel() { String type = getAttributeType(); return getAttributeTypeLabel(type); } public String getAttributeTypeLabel(String typeValue) { if ( StringUtils.isNotBlank(typeValue) ) { AttributeType type = AttributeType.valueOf(typeValue); return type.getLabel(); } else { return null; } } public List<String> getAttributeTypeValues() { List<String> result = new ArrayList<String>(); AttributeType[] values = AttributeType.values(); for (AttributeType type : values) { result.add(type.name()); } return result; } public String getAttributeTypeLabelFromDefinition(AttributeDefinition attrDefn) { if ( attrDefn != null ) { AttributeType type = AttributeType.valueOf(attrDefn); return type.getLabel(); } else { return null; } } public String getAttributeInstanceLabel(AttributeDefinition attrDefn) { return attrDefn.getLabel(Type.INSTANCE, currentLanguageCode); } public static String getIcon(SchemaNodeData data) { SurveyObject surveyObject = data.getSurveyObject(); if ( surveyObject instanceof UITab ) { return "/assets/images/tab-small.png"; } else { if ( surveyObject instanceof EntityDefinition ) { return getEntityIcon((EntityDefinition) surveyObject); } else { AttributeType attributeType = AttributeType.valueOf((AttributeDefinition) surveyObject); return getAttributeIcon(attributeType.name()); } } } protected static String getEntityIcon(EntityDefinition entityDefn) { CollectSurvey survey = (CollectSurvey) entityDefn.getSurvey(); UIOptions uiOptions = survey.getUIOptions(); Layout layout = uiOptions.getLayout(entityDefn); String icon; if ( entityDefn.isMultiple() ) { switch ( layout ) { case TABLE: icon = "table-small.png"; break; case FORM: default: icon = "form-small.png"; } } else { icon = "grouping-small.png"; } return NODE_TYPES_IMAGES_PATH + icon; } public static String getAttributeIcon(String type) { AttributeType attributeType = AttributeType.valueOf(type); String result = NODE_TYPES_IMAGES_PATH + attributeType.name().toLowerCase() + "-small.png"; return result; } @DependsOn("editedNode") public String getEditedNodePath() { if ( editedNode == null ) { return null; } else if ( editedNode instanceof NodeDefinition ) { if ( newNode ) { return editedNodeParentEntity.getPath() + "/" + PATH_NULL_VALUES_REPLACE; } else { return ((NodeDefinition) editedNode).getPath(); } } else { //tab UITab tab = (UITab) editedNode; return tab.getPath(currentLanguageCode, PATH_NULL_VALUES_REPLACE); } } @Command @NotifyChange({"treeModel","selectedTab"}) public void addTab(@ContextParam(ContextType.BINDER) Binder binder) { if ( TreeViewType.DATA.name().equalsIgnoreCase(selectedTreeViewType) ) { MessageUtil.showWarning("survey.schema.unsupported_operation_in_data_view"); } else { treeModel.deselect(); addTabInternal(binder, rootTabSet); } } @Command @NotifyChange({"treeModel","selectedTab"}) public void addChildTab(@ContextParam(ContextType.BINDER) Binder binder) { if ( checkCanAddChildTab() ) { UITab parentTab = getSelectedNodeParentTab(); addTabInternal(binder, parentTab); } } private boolean checkCanAddChildTab() { if ( TreeViewType.DATA.name().equalsIgnoreCase(selectedTreeViewType) ) { MessageUtil.showWarning("survey.schema.unsupported_operation_in_data_view"); return false; } else { SurveyObject selectedSurveyObject = selectedTreeNode.getSurveyObject(); if ( selectedSurveyObject instanceof UITab ) { UITab parentTab = getSelectedNodeParentTab(); UIOptions uiOptions = survey.getUIOptions(); UITabSet rootTabSet = parentTab.getRootTabSet(); UITab mainTab = uiOptions.getMainTab(rootTabSet); if ( parentTab == mainTab ) { MessageUtil.showWarning("survey.schema.cannot_add_nested_tab.unsupported_nested_tabs_in_main_tab"); return false; } else if ( uiOptions.isAssociatedWithMultipleEntityForm(parentTab) ) { MessageUtil.showWarning("survey.schema.cannot_add_nested_tab.form_entity_assosicated"); return false; } else { MessageUtil.showWarning("survey.schema.cannot_add_nested_tab.maximum_depth_reached"); return false; } } else { return true; } } } protected void addTabInternal(final Binder binder, final UITabSet parentTabSet) { if ( rootTabSet != null ) { checkCanLeaveForm(new CanLeaveFormConfirmHandler() { @Override public void onOk(boolean confirmed) { CollectSurvey survey = getSurvey(); UIOptions uiOptions = survey.getUIOptions(); UITab tab = uiOptions.createTab(); String label = Labels.getLabel("survey.schema.node.layout.default_tab_label"); tab.setLabel(currentLanguageCode, label); parentTabSet.addTab(tab); editNode(binder, false, null, tab); afterNewNodeCreated(tab, false); //dispatchTabSetChangedCommand(); } }); } } @Command public void removeTab() { UITab tab = (UITab) selectedTreeNode.getSurveyObject(); removeTab(tab); } private UITab getSelectedNodeParentTab() { UITab parentTab; SurveyObject selectedSurveyObject = selectedTreeNode.getSurveyObject(); if ( selectedSurveyObject instanceof UITab ) { parentTab = (UITab) selectedSurveyObject; } else { UIOptions uiOptions = survey.getUIOptions(); parentTab = uiOptions.getAssignedTab((NodeDefinition) selectedSurveyObject); } return parentTab; } private void removeTab(final UITab tab) { String confirmMessageKey = null; if ( tab.getTabs().isEmpty() ) { CollectSurvey survey = getSurvey(); UIOptions uiOpts = survey.getUIOptions(); List<NodeDefinition> nodesPerTab = uiOpts.getNodesPerTab(tab, false); if ( ! nodesPerTab.isEmpty() ) { confirmMessageKey = "survey.layout.tab.remove.confirm.associated_nodes_present"; } } else { confirmMessageKey = "survey.layout.tab.remove.confirm.nested_tabs_present"; } if ( confirmMessageKey != null ) { MessageUtil.ConfirmParams params = new MessageUtil.ConfirmParams(new MessageUtil.ConfirmHandler() { @Override public void onOk() { performRemoveTab(tab); } }, confirmMessageKey); params.setOkLabelKey("global.delete_item"); MessageUtil.showConfirm(params); } else { performRemoveTab(tab); } } protected void performRemoveTab(UITab tab) { //remove all nodes associated to the tab UIOptions uiOptions = tab.getUIOptions(); List<NodeDefinition> nodesPerTab = uiOptions.getNodesPerTab(tab, false); for (NodeDefinition nodeDefn : nodesPerTab) { EntityDefinition parentDefn = nodeDefn.getParentEntityDefinition(); parentDefn.removeChildDefinition(nodeDefn); } UITabSet parent = tab.getParent(); parent.removeTab(tab); treeModel.removeSelectedNode(); notifyChange("treeModel", "selectedTab"); } @Command public void updateTabLabel(@BindingParam("tab") UITab tab, @BindingParam("label") String label) { if ( validateTabLabel(label) ) { tab.setLabel(currentLanguageCode, label.trim()); // dispatchTabChangedCommand(tab); } } protected boolean validateTabLabel(String label) { if ( StringUtils.isBlank(label) ) { MessageUtil.showWarning("survey.layout.tab.label.error.required"); return false; } else { return true; } } @Command public void treeViewTypeSelected(@BindingParam("type") String type) { selectedTreeViewType = type; resetEditingStatus(); refreshTreeModel(); } public Menupopup getPopupMenu(SchemaNodeData data) { if ( data == null ) { return null; } Menupopup popupMenu; if ( data.isDetached() ) { popupMenu = detachedNodePopup; } else if ( isTab(data) ) { if ( isMainTab(data) ) { popupMenu = mainTabPopup; } else { popupMenu = tabPopup; } } else if ( isEntity(data) ) { if ( isSingleEntity(data) ) { popupMenu = singleEntityPopup; } else if ( isTableEntity(data)) { popupMenu = tableEntityPopup; } else { popupMenu = formEntityPopup; } } else { popupMenu = attributePopup; } return popupMenu; } @Command public void openMoveNodePopup() { SchemaNodeData selectedTreeNode = getSelectedTreeNode(); if ( selectedTreeNode == null ) { return; } SurveyObject selectedItem = selectedTreeNode.getSurveyObject(); if ( selectedItem instanceof NodeDefinition ) { NodeDefinition selectedNode = (NodeDefinition) selectedItem; boolean changeParentNodeAllowed = checkChangeParentNodeAllowed(selectedNode); if ( changeParentNodeAllowed ) { openSelectParentNodePopup(selectedNode); } } else { //TODO support tab moving return; } } private boolean checkChangeParentNodeAllowed(NodeDefinition selectedNode) { UIOptions uiOptions = survey.getUIOptions(); if ( survey.isPublished() ) { //only tab changing allowed final List<UITab> assignableTabs = uiOptions.getAssignableTabs(editedNodeParentEntity, selectedNode); if ( assignableTabs.size() > 0 ) { return true; } else { MessageUtil.showWarning("survey.schema.move_node.published_survey.no_other_tabs_allowed"); return false; } } else { return true; } } private void openSelectParentNodePopup(final NodeDefinition selectedItem) { UIOptions uiOptions = survey.getUIOptions(); final Set<UITab> assignableTabs = new HashSet<UITab>(uiOptions.getAssignableTabs(editedNodeParentEntity, selectedItem)); final NodeDefinition parentDefn = selectedItem.getParentDefinition(); UITab inheritedTab = uiOptions.getAssignedTab(parentDefn); assignableTabs.add(inheritedTab); Predicate<SurveyObject> includedNodePredicate = new Predicate<SurveyObject>() { @Override public boolean evaluate(SurveyObject item) { return item instanceof UITab || item instanceof EntityDefinition; } }; Predicate<SurveyObject> disabledPredicate = new Predicate<SurveyObject>() { @Override public boolean evaluate(SurveyObject item) { if ( item instanceof UITab ) { return ! assignableTabs.contains(item); } else if ( item.equals(parentDefn) || (! survey.isPublished() && item instanceof EntityDefinition && ! item.equals(selectedItem)) ) { return false; } else { return true; } } }; String nodeName = editedNode instanceof NodeDefinition ? ((NodeDefinition) editedNode).getName(): ""; UITab assignedTab = survey.getUIOptions().getAssignedTab((NodeDefinition) editedNode); String assignedTabLabel = assignedTab.getLabel(currentLanguageCode); String title = Labels.getLabel("survey.schema.move_node_popup_title", new String[]{getNodeTypeHeaderLabel(), nodeName, assignedTabLabel}); //calculate parent item (tab or entity) SchemaTreeNode treeNode = treeModel.getTreeNode(selectedItem); TreeNode<SchemaNodeData> parentTreeNode = treeNode.getParent(); SurveyObject parentItem = parentTreeNode.getData().getSurveyObject(); nodeMovePopUp = SchemaTreePopUpVM.openPopup(title, selectedRootEntity, null, includedNodePredicate, true, disabledPredicate, null, parentItem); } @GlobalCommand public void closeSchemaNodeSelector() { if ( nodeMovePopUp != null ) { closePopUp(nodeMovePopUp); nodeMovePopUp = null; } } @GlobalCommand public void schemaTreeNodeSelected(@ContextParam(ContextType.BINDER) Binder binder, @BindingParam("node") SurveyObject surveyObject) { if ( surveyObject instanceof UITab ) { associateNodeToTab((NodeDefinition) editedNode, (UITab) surveyObject); } else if ( surveyObject instanceof EntityDefinition ) { changeEditedNodeParentEntity((EntityDefinition) surveyObject); } closeSchemaNodeSelector(); } private void changeEditedNodeParentEntity(EntityDefinition newParentEntity) { //update parent entity NodeDefinition node = (NodeDefinition) editedNode; Schema schema = survey.getSchema(); schema.changeParentEntity(node, newParentEntity); //update tab UIOptions uiOptions = survey.getUIOptions(); UITab newTab = uiOptions.getAssignedTab(newParentEntity); uiOptions.assignToTab(node, newTab); //update ui refreshTreeModel(); editedNodeParentEntity = newParentEntity; selectTreeNode(editedNode); treeModel.showSelectedNode(); notifyChange("selectedTreeNode","editedNode"); } private void associateNodeToTab(NodeDefinition node, UITab tab) { UIOptions uiOptions = survey.getUIOptions(); uiOptions.assignToTab(node, tab); refreshTreeModel(); selectTreeNode(node); treeModel.showSelectedNode(); notifyChange("selectedTreeNode","editedNode"); } public SchemaNodeData getSelectedTreeNode() { return selectedTreeNode; } public SurveyObject getEditedNode() { return editedNode; } @DependsOn("editedNode") public boolean isEditingNode() { return editedNode != null; } public boolean isNewNode() { return newNode; } public EntityDefinition getSelectedRootEntity() { return selectedRootEntity; } public ModelVersion getSelectedVersion() { return selectedVersion; } @DependsOn("selectedRootEntity") public boolean isRootEntitySelected() { return selectedRootEntity != null; } public String getSelectedTreeViewType() { return selectedTreeViewType; } public String[] getTreeViewTypes() { TreeViewType[] values = TreeViewType.values(); String[] result = new String[values.length]; for (int i = 0; i < values.length; i++) { TreeViewType type = values[i]; result[i] = type.name().toLowerCase(); } return result; } public String getTreeViewTypeLabel(String type) { return Labels.getLabel("survey.schema.tree.view_type." + type); } }
package com.archimatetool.model.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import com.archimatetool.model.IArchimateConcept; import com.archimatetool.model.IArchimatePackage; import com.archimatetool.model.IArchimateRelationship; import com.archimatetool.model.IDiagramModelArchimateConnection; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Relationship</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link com.archimatetool.model.impl.ArchimateRelationship#getSource <em>Source</em>}</li> * <li>{@link com.archimatetool.model.impl.ArchimateRelationship#getTarget <em>Target</em>}</li> * </ul> * * @generated */ public abstract class ArchimateRelationship extends ArchimateConcept implements IArchimateRelationship { /** * The cached value of the '{@link #getSource() <em>Source</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSource() * @generated * @ordered */ protected IArchimateConcept source; /** * The cached value of the '{@link #getTarget() <em>Target</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTarget() * @generated * @ordered */ protected IArchimateConcept target; /** * Stored references to Diagram Connections * Some of these may be orphaned so this is not an accurate list of live diagram connections */ Set<IDiagramModelArchimateConnection> diagramConnections = new HashSet<>(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ArchimateRelationship() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return IArchimatePackage.Literals.ARCHIMATE_RELATIONSHIP; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IArchimateConcept getSource() { return source; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public void setSource(IArchimateConcept newSource) { IArchimateConcept oldSource = source; source = newSource; if(oldSource != newSource) { // optimise if(oldSource != null) { oldSource.getSourceRelationships().remove(this); } if(newSource != null) { newSource.getSourceRelationships().add(this); } } if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, IArchimatePackage.ARCHIMATE_RELATIONSHIP__SOURCE, oldSource, source)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IArchimateConcept getTarget() { return target; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public void setTarget(IArchimateConcept newTarget) { IArchimateConcept oldTarget = target; target = newTarget; if(oldTarget != newTarget) { // optimise if(oldTarget != null) { oldTarget.getTargetRelationships().remove(this); } if(newTarget != null) { newTarget.getTargetRelationships().add(this); } } if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, IArchimatePackage.ARCHIMATE_RELATIONSHIP__TARGET, oldTarget, target)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public void connect(IArchimateConcept source, IArchimateConcept target) { setSource(source); setTarget(target); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public void reconnect() { if(source != null) { source.getSourceRelationships().add(this); } if(target != null) { target.getTargetRelationships().add(this); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public void disconnect() { if(source != null) { source.getSourceRelationships().remove(this); } if(target != null) { target.getTargetRelationships().remove(this); } } @Override public EObject getCopy() { IArchimateRelationship copy = (IArchimateRelationship)super.getCopy(); // Clear source and target. This will also clear connected components' references to this copy.setSource(null); copy.setTarget(null); return copy; } /* * It's not simply a case of returning the list of references. * If an *ancestor* of a dmc is deleted, or the diagram model itself, but not the direct parent, * the dmc will not be removed from the relation's dmc reference list, * so we check if there is a top model ancestor on the referenced dmc. * If there is a top model ancestor, it's used in a diagram model. */ @Override public List<IDiagramModelArchimateConnection> getReferencingDiagramConnections() { List<IDiagramModelArchimateConnection> list = new ArrayList<>(); for(IDiagramModelArchimateConnection dmc : diagramConnections) { if(dmc.getArchimateModel() != null) { list.add(dmc); } } return list; } @Override public List<IDiagramModelArchimateConnection> getReferencingDiagramComponents() { return getReferencingDiagramConnections(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case IArchimatePackage.ARCHIMATE_RELATIONSHIP__SOURCE: return getSource(); case IArchimatePackage.ARCHIMATE_RELATIONSHIP__TARGET: return getTarget(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case IArchimatePackage.ARCHIMATE_RELATIONSHIP__SOURCE: setSource((IArchimateConcept)newValue); return; case IArchimatePackage.ARCHIMATE_RELATIONSHIP__TARGET: setTarget((IArchimateConcept)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case IArchimatePackage.ARCHIMATE_RELATIONSHIP__SOURCE: setSource((IArchimateConcept)null); return; case IArchimatePackage.ARCHIMATE_RELATIONSHIP__TARGET: setTarget((IArchimateConcept)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case IArchimatePackage.ARCHIMATE_RELATIONSHIP__SOURCE: return source != null; case IArchimatePackage.ARCHIMATE_RELATIONSHIP__TARGET: return target != null; } return super.eIsSet(featureID); } } //ArchimateRelationship
package imagej.updater.ui; import imagej.updater.core.Checksummer; import imagej.updater.core.Dependency; import imagej.updater.core.FileObject; import imagej.updater.core.FileObject.Action; import imagej.updater.core.FileObject.Status; import imagej.updater.core.FilesCollection; import imagej.updater.core.FilesCollection.Filter; import imagej.updater.core.FilesCollection.UpdateSite; import imagej.updater.core.FilesUploader; import imagej.updater.core.Installer; import imagej.updater.core.XMLFileDownloader; import imagej.updater.util.Downloadable; import imagej.updater.util.Downloader; import imagej.updater.util.Progress; import imagej.updater.util.StderrProgress; import imagej.updater.util.UpdaterUserInterface; import imagej.updater.util.Util; import imagej.util.FileUtils; import imagej.util.Log; import java.awt.Frame; import java.io.Console; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * This is the command-line interface into the ImageJ Updater. * * @author Johannes Schindelin */ public class CommandLine { protected FilesCollection files; protected Progress progress; public CommandLine() throws IOException, ParserConfigurationException, SAXException { files = new FilesCollection(FileUtils.getBaseDirectory()); try { files.read(); } catch (final FileNotFoundException e) { /* ignore */} progress = new StderrProgress(80); final XMLFileDownloader downloader = new XMLFileDownloader(files); downloader.addProgress(progress); downloader.start(); String warnings = downloader.getWarnings(); if (!warnings.equals("")) System.err.println(warnings); new Checksummer(files, progress).updateFromLocal(); } protected class FileFilter implements Filter { protected Set<String> fileNames; public FileFilter(final List<String> files) { if (files != null && files.size() > 0) { fileNames = new HashSet<String>(); for (final String file : files) fileNames.add(Util.stripPrefix(file, "")); } } @Override public boolean matches(final FileObject file) { if (!file.isUpdateablePlatform()) return false; if (fileNames != null && !fileNames.contains(file.filename)) return false; return file.getStatus() != Status.OBSOLETE_UNINSTALLED; } } public void listCurrent(final List<String> list) { for (final FileObject file : files.filter(new FileFilter(list))) System.out.println(file.filename + "-" + file.getTimestamp()); } public void list(final List<String> list, Filter filter) { if (filter == null) filter = new FileFilter(list); else filter = files.and(new FileFilter(list), filter); files.sort(); for (final FileObject file : files.filter(filter)) System.out.println(file.filename + "\t(" + file.getStatus() + ")\t" + file.getTimestamp()); } public void list(final List<String> list) { list(list, null); } public void listUptodate(final List<String> list) { list(list, files.is(Status.INSTALLED)); } public void listNotUptodate(final List<String> list) { list(list, files.not(files.oneOf(new Status[] { Status.OBSOLETE, Status.INSTALLED, Status.LOCAL_ONLY }))); } public void listUpdateable(final List<String> list) { list(list, files.is(Status.UPDATEABLE)); } public void listModified(final List<String> list) { list(list, files.is(Status.MODIFIED)); } class OneFile implements Downloadable { FileObject file; OneFile(final FileObject file) { this.file = file; } @Override public File getDestination() { return files.prefix(file.filename); } @Override public String getURL() { return files.getURL(file); } @Override public long getFilesize() { return file.filesize; } @Override public String toString() { return file.filename; } } public void download(final FileObject file) { try { new Downloader(progress).start(new OneFile(file)); if (file.executable && !Util.platform.startsWith("win")) try { Runtime.getRuntime() .exec( new String[] { "chmod", "0755", files.prefix(file.filename).getPath() }); } catch (final Exception e) { e.printStackTrace(); throw new RuntimeException("Could not mark " + file.filename + " as executable"); } System.err.println("Installed " + file.filename); } catch (final IOException e) { System.err.println("IO error downloading " + file.filename + ": " + e.getMessage()); } } public void delete(final FileObject file) { if (new File(file.filename).delete()) System.err.println("Deleted " + file.filename); else System.err.println("Failed to delete " + file.filename); } protected void addDependencies(final FileObject file, final Set<FileObject> all) { if (all.contains(file)) return; all.add(file); for (final Dependency dependency : file.getDependencies()) { final FileObject file2 = files.get(dependency.filename); if (file2 != null) addDependencies(file2, all); } } public void update(final List<String> list) { update(list, false); } public void update(final List<String> list, final boolean force) { update(list, force, false); } public void update(final List<String> list, final boolean force, final boolean pristine) { // Include all dependencies final Set<FileObject> all = new HashSet<FileObject>(); for (final FileObject file : files.filter(new FileFilter(list))) addDependencies(file, all); for (final FileObject file : all) list.add(file.filename); try { for (final FileObject file : all) { switch (file.getStatus()) { case MODIFIED: if (!force) { System.err.println("Skipping locally-modified " + file.filename); break; } case UPDATEABLE: case NEW: case NOT_INSTALLED: file.setFirstValidAction(files, new Action[] { Action.UPDATE, Action.INSTALL }); break; case LOCAL_ONLY: if (!pristine) { System.err.println("Keeping local-only " + file.filename); break; } case OBSOLETE_MODIFIED: if (!force) { System.err.println("Keeping modified but obsolete " + file.filename); break; } case OBSOLETE: file.stageForUninstall(files); break; default: if (files != null && files.size() > 0) System.err.println("Not updating " + file.filename + " (" + file.getStatus() + ")"); } } Installer installer = new Installer(files, progress); installer.start(); installer.moveUpdatedIntoPlace(); files.write(); } catch (final Exception e) { System.err.println("Could not write db.xml.gz:"); e.printStackTrace(); } } public void upload(final List<String> list) { if (list == null || list.size() == 0) die("Which files do you mean to upload?"); String updateSite = null; for (final String name : list) { final FileObject file = files.get(name); if (file == null) die("No file '" + name + "' found!"); if (file.getStatus() == Status.INSTALLED) { System.err.println("Skipping up-to-date " + name); continue; } if (file.getStatus() == Status.LOCAL_ONLY && Util.isLauncher(file.filename)) { file.executable = true; file.addPlatform(Util.platformForLauncher(file.filename)); for (final String fileName : new String[] { "jars/ij-launcher.jar" }) { final FileObject dependency = files.get(fileName); if (dependency != null) file.addDependency(files, dependency); } } if (updateSite == null) { updateSite = file.updateSite; if (updateSite == null) updateSite = file.updateSite = chooseUploadSite(name); if (updateSite == null) die("Canceled"); } else if (file.updateSite == null) { System.err.println("Uploading new file '" + name + "' to site '" + updateSite + "'"); file.updateSite = updateSite; } else if (!file.updateSite.equals(updateSite)) die("Cannot upload to multiple update sites (" + files.get(0) + " to " + updateSite + " and " + name + " to " + file.updateSite + ")"); file.setAction(files, Action.UPLOAD); } System.err.println("Uploading to " + getLongUpdateSiteName(updateSite)); try { final FilesUploader uploader = new FilesUploader(files, updateSite); if (!uploader.login()) die("Login failed!"); uploader.upload(progress); files.write(); } catch (final Throwable e) { e.printStackTrace(); die("Error during upload: " + e); } } public String chooseUploadSite(final String file) { final List<String> names = new ArrayList<String>(); final List<String> options = new ArrayList<String>(); for (final String name : files.getUpdateSiteNames()) { final UpdateSite updateSite = files.getUpdateSite(name); if (updateSite.uploadDirectory == null || updateSite.uploadDirectory.equals("")) continue; names.add(name); options.add(getLongUpdateSiteName(name)); } if (names.size() == 0) { System.err.println("No uploadable sites found"); return null; } final String message = "Choose upload site for file '" + file + "'"; final int index = UpdaterUserInterface.get().optionDialog(message, message, options.toArray(new String[options.size()]), 0); return index < 0 ? null : names.get(index); } public String getLongUpdateSiteName(final String name) { final UpdateSite site = files.getUpdateSite(name); return name + " (" + (site.sshHost == null || site.equals("") ? "" : site.sshHost + ":") + site.uploadDirectory + ")"; } public static CommandLine getInstance() { try { return new CommandLine(); } catch (final Exception e) { e.printStackTrace(); System.err.println("Could not parse db.xml.gz: " + e.getMessage()); throw new RuntimeException(e); } } public static List<String> makeList(final String[] list, int start) { final List<String> result = new ArrayList<String>(); while (start < list.length) result.add(list[start++]); return result; } public static void die(final String message) { System.err.println(message); System.exit(1); } public static void usage() { System.err.println("Usage: imagej.updater.ui.CommandLine <command>\n" + "\n" + "Commands:\n" + "\tlist [<files>]\n" + "\tlist-uptodate [<files>]\n" + "\tlist-not-uptodate [<files>]\n" + "\tlist-updateable [<files>]\n" + "\tlist-modified [<files>]\n" + "\tlist-current [<files>]\n" + "\tupdate [<files>]\n" + "\tupdate-force [<files>]\n" + "\tupdate-force-pristine [<files>]\n" + "\tupload [<files>]"); } public static void main(final String[] args) { if (args.length == 0) { usage(); System.exit(0); } String http_proxy = System.getenv("http_proxy"); if (http_proxy != null && http_proxy.startsWith("http: final int colon = http_proxy.indexOf(':', 7); final int slash = http_proxy.indexOf('/', 7); int port = 80; if (colon < 0) http_proxy = slash < 0 ? http_proxy.substring(7) : http_proxy.substring(7, slash); else { port = Integer.parseInt(slash < 0 ? http_proxy.substring(colon + 1) : http_proxy.substring(colon + 1, slash)); http_proxy = http_proxy.substring(7, colon); } System.setProperty("http.proxyHost", http_proxy); System.setProperty("http.proxyPort", "" + port); } else Util.useSystemProxies(); Authenticator.setDefault(new ProxyAuthenticator()); setUserInterface(); final String command = args[0]; if (command.equals("list")) getInstance().list(makeList(args, 1)); else if (command.equals("list-current")) getInstance().listCurrent( makeList(args, 1)); else if (command.equals("list-uptodate")) getInstance().listUptodate( makeList(args, 1)); else if (command.equals("list-not-uptodate")) getInstance() .listNotUptodate(makeList(args, 1)); else if (command.equals("list-updateable")) getInstance().listUpdateable( makeList(args, 1)); else if (command.equals("list-modified")) getInstance().listModified( makeList(args, 1)); else if (command.equals("update")) getInstance().update(makeList(args, 1)); else if (command.equals("update-force")) getInstance().update( makeList(args, 1), true); else if (command.equals("update-force-pristine")) getInstance().update( makeList(args, 1), true, true); else if (command.equals("upload")) getInstance().upload(makeList(args, 1)); else usage(); } protected static class ProxyAuthenticator extends Authenticator { protected Console console = System.console(); @Override protected PasswordAuthentication getPasswordAuthentication() { final String user = console.readLine(" \rProxy User: "); final char[] password = console.readPassword("Proxy Password: "); return new PasswordAuthentication(user, password); } } protected static void setUserInterface() { UpdaterUserInterface.set(new ConsoleUserInterface()); } protected static class ConsoleUserInterface extends UpdaterUserInterface { protected Console console = System.console(); protected int count; @Override public String getPassword(final String message) { System.out.print(message + ": "); return new String(console.readPassword()); } @Override public boolean promptYesNo(final String title, final String message) { System.err.print(title + ": " + message); final String line = console.readLine(); return line.startsWith("y") || line.startsWith("Y"); } public void showPrompt(String prompt) { if (!prompt.endsWith(": ")) prompt += ": "; System.err.print(prompt); } public String getUsername(final String prompt) { showPrompt(prompt); return console.readLine(); } public int askChoice(final String[] options) { for (int i = 0; i < options.length; i++) System.err.println("" + (i + 1) + ": " + options[i]); for (;;) { System.err.print("Choice? "); final String answer = console.readLine(); if (answer.equals("")) return -1; try { return Integer.parseInt(answer) - 1; } catch (final Exception e) { /* ignore */} } } @Override public void error(final String message) { Log.error(message); } @Override public void info(final String message, final String title) { Log.info(title + ": " + message); } @Override public void log(final String message) { Log.info(message); } @Override public void debug(final String message) { Log.debug(message); } @Override public OutputStream getOutputStream() { return System.out; } @Override public void showStatus(final String message) { log(message); } @Override public void handleException(final Throwable exception) { exception.printStackTrace(); } @Override public boolean isBatchMode() { return false; } @Override public int optionDialog(final String message, final String title, final Object[] options, final int def) { for (int i = 0; i < options.length; i++) System.err.println("" + (i + 1) + ") " + options[i]); for (;;) { System.out.print("Your choice (default: " + def + ": " + options[def] + ")? "); final String line = console.readLine(); if (line.equals("")) return def; try { final int option = Integer.parseInt(line); if (option > 0 && option <= options.length) return option - 1; } catch (final NumberFormatException e) { // ignore } } } @Override public String getPref(final String key) { return null; } @Override public void setPref(final String key, final String value) { log("Ignoring setting '" + key + "'"); } @Override public void savePreferences() { /* do nothing */} @Override public void openURL(final String url) throws IOException { log("Please open " + url + " in your browser"); } @Override public String getString(final String title) { System.out.print(title + ": "); return console.readLine(); } @Override public void addWindow(final Frame window) { throw new UnsupportedOperationException(); } @Override public void removeWindow(final Frame window) { throw new UnsupportedOperationException(); } } }
package me.lucko.luckperms.common.storage.wrappings; import me.lucko.luckperms.common.storage.Storage; import java.lang.reflect.Proxy; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A storage wrapping that ensures all tasks are completed before {@link Storage#shutdown()} is called. */ public interface PhasedStorage extends Storage { /** * Creates a new instance of {@link PhasedStorage} which delegates called to the given * {@link Storage} instance. * * @param delegate the delegate storage impl * @return the new phased storage instance */ static PhasedStorage wrap(Storage delegate) { // create a new phaser to be used by the instance Phaser phaser = new Phaser(); // create and return a proxy instance which directs save calls through the phaser return (PhasedStorage) Proxy.newProxyInstance( PhasedStorage.class.getClassLoader(), new Class[]{PhasedStorage.class}, (proxy, method, args) -> { // provide implementation of #noBuffer if (method.getName().equals("noBuffer")) { return delegate; } // direct delegation switch (method.getName()) { case "getDao": case "getApiDelegate": case "getName": case "init": case "getMeta": return method.invoke(delegate, args); } // await the phaser on shutdown if (method.getName().equals("shutdown")) { try { phaser.awaitAdvanceInterruptibly(phaser.getPhase(), 10, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { e.printStackTrace(); } delegate.shutdown(); return null; } // for all other methods, run the call via the phaser phaser.register(); try { return method.invoke(delegate, args); } finally { phaser.arriveAndDeregister(); } } ); } }