answer
stringlengths
17
10.2M
package com.dmillerw.remoteIO.block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import com.dmillerw.remoteIO.RemoteIO; import com.dmillerw.remoteIO.block.tile.TileEntityIO; import com.dmillerw.remoteIO.core.CreativeTabRIO; import com.dmillerw.remoteIO.core.helper.InventoryHelper; import com.dmillerw.remoteIO.item.ItemTool; import com.dmillerw.remoteIO.lib.ModInfo; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockIO extends BlockContainer { public Icon[] icons; public BlockIO(int id) { super(id, Material.iron); this.setHardness(5F); this.setResistance(1F); this.setCreativeTab(CreativeTabRIO.tab); } public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) { super.onBlockPlacedBy(world, x, y, z, entity, stack); if (entity instanceof EntityPlayer && ((EntityPlayer)entity).capabilities.isCreativeMode) { TileEntityIO tile = (TileEntityIO) world.getBlockTileEntity(x, y, z); tile.creativeMode = true; } onNeighborBlockChange(world, x, y, z, 0); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float fx, float fy, float fz) { if (!player.isSneaking() && (player.getHeldItem() == null || !(player.getHeldItem().getItem() instanceof ItemTool))) { player.openGui(RemoteIO.instance, 0, world, x, y, z); return true; } return false; } public void onNeighborBlockChange(World world, int x, int y, int z, int id) { TileEntityIO tile = (TileEntityIO) world.getBlockTileEntity(x, y, z); if (tile != null) { tile.setRedstoneState(world.isBlockIndirectlyGettingPowered(x, y, z)); } } @Override public void breakBlock(World world, int x, int y, int z, int id, int meta) { TileEntityIO tile = (TileEntityIO) world.getBlockTileEntity(x, y, z); if (tile != null) { for (ItemStack stack : InventoryHelper.getContents(tile.upgrades)) { if (stack != null) this.dropBlockAsItem_do(world, x, y, z, stack); } } super.breakBlock(world, x, y, z, id, meta); } @SideOnly(Side.CLIENT) @Override public Icon getBlockTexture(IBlockAccess world, int x, int y, int z, int side) { TileEntityIO tile = (TileEntityIO) world.getBlockTileEntity(x, y, z); if (tile != null && tile.validCoordinates) { return this.icons[0]; } else { return this.icons[1]; } } @SideOnly(Side.CLIENT) @Override public Icon getIcon(int side, int meta) { return this.icons[1]; } @SideOnly(Side.CLIENT) @Override public void registerIcons(IconRegister register) { this.icons = new Icon[2]; this.icons[0] = register.registerIcon(ModInfo.RESOURCE_PREFIX + "blockIO"); this.icons[1] = register.registerIcon(ModInfo.RESOURCE_PREFIX + "blockIOInactive"); } @Override public TileEntity createNewTileEntity(World world) { return new TileEntityIO(); } }
package org.treetank.page; import org.treetank.access.PageWriteTrx; import org.treetank.exception.AbsTTException; import org.treetank.io.EStorage; import org.treetank.io.ITTSink; import org.treetank.io.ITTSource; import org.treetank.utils.IConstants; /** * <h1>IndirectPage</h1> * * <p> * Indirect page holds a set of references to build a reference tree. * </p> */ public final class IndirectPage implements IPage { /** Page references. */ private PageReference[] mReferences; /** revision of this page. */ private final long mRevision; /** * Create indirect page. * * @param paramRevision * Revision Number */ public IndirectPage(final long paramRevision) { mRevision = paramRevision; mReferences = new PageReference[IConstants.INP_REFERENCE_COUNT]; for (int i = 0; i < mReferences.length; i++) { mReferences[i] = new PageReference(); } } /** * Read indirect page. * * @param paramIn * Input bytes. */ protected IndirectPage(final ITTSource paramIn) { mRevision = paramIn.readLong(); mReferences = new PageReference[IConstants.INP_REFERENCE_COUNT]; for (int offset = 0; offset < mReferences.length; offset++) { getReferences()[offset] = new PageReference(); final EStorage storage = EStorage.getInstance(paramIn.readInt()); if (storage != null) { getReferences()[offset].setKey(storage.deserialize(paramIn)); } } } /** * Clone indirect page. * * @param page * Page to clone. * @param revisionToUse * Revision number to use */ public IndirectPage(final IndirectPage page, final long revisionToUse) { mRevision = revisionToUse; mReferences = page.getReferences(); } @Override public void commit(PageWriteTrx paramState) throws AbsTTException { for (final PageReference reference : getReferences()) { paramState.commit(reference); } } @Override public void serialize(ITTSink paramOut) { paramOut.writeLong(mRevision); for (final PageReference reference : getReferences()) { if (reference.getKey() == null) { paramOut.writeInt(0); } else { EStorage.getInstance(reference.getKey().getClass()).serialize(paramOut, reference.getKey()); } } } @Override public PageReference[] getReferences() { return mReferences; } @Override public long getRevision() { return mRevision; } }
package au.edu.uts.eng.remotelabs.rigclient.action.access; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import au.edu.uts.eng.remotelabs.rigclient.rig.IAccessAction; import au.edu.uts.eng.remotelabs.rigclient.util.ConfigFactory; import au.edu.uts.eng.remotelabs.rigclient.util.ILogger; import au.edu.uts.eng.remotelabs.rigclient.util.LoggerFactory; public class RemoteDesktopAccessAction implements IAccessAction { /** Default user group for remote desktop access. */ public static final String DEFAULT_GROUPNAME = "\"Remote Desktop Users\""; /** Default command for changing user groups for windows */ public static final String DEFAULT_COMMAND = "net"; /** Default command for changing user groups for windows */ public static final String DEFAULT_LOCALGROUP = "localgroup"; /** Domain name. */ private final String domainName; /** Default user group for remote desktop access. */ private String failureReason; /** Logger. */ protected ILogger logger; /** * Constructor. */ public RemoteDesktopAccessAction() { this.logger = LoggerFactory.getLoggerInstance(); /* RDP access only valid for Windows - check that the OS is windows */ if (System.getProperty("os.name").startsWith("Windows")) { /* Get domain if it is configured */ if (ConfigFactory.getInstance().getProperty("Remote_Desktop_Windows_Domain","").equals("")) { this.domainName = null; } else { this.domainName = ConfigFactory.getInstance().getProperty("Remote_Desktop_Windows_Domain"); } this.logger.info("The Remote Desktop Windows Domain has been set to " + this.domainName + " for the Remote Desktop Access Action."); } else { this.logger.error("Unable to instantiate the Remote Desktop Action (" + this.getClass().getName() + ") becuase the detected platform is not Windows. Detected platform is '" + System.getProperty("os.name") + "'."); throw new IllegalStateException("Remote Desktop Action is only valid for a WINDOWS platforms not " + System.getProperty("os.name")); } } @Override public boolean assign(final String name) { synchronized (this) { final List<String> commandBase = new ArrayList<String>(); commandBase.add(RemoteDesktopAccessAction.DEFAULT_COMMAND); commandBase.add(RemoteDesktopAccessAction.DEFAULT_LOCALGROUP); final String groupName = ConfigFactory.getInstance().getProperty("Remote_Desktop_Groupname", RemoteDesktopAccessAction.DEFAULT_GROUPNAME); this.logger.debug("The group name read is " + groupName + '.'); if (groupName.charAt(0) == '"' && groupName.charAt(groupName.length()-1) == '"') { commandBase.add(groupName); } else if (groupName.charAt(0) != '"' && groupName.charAt(groupName.length()-1) == '"') { commandBase.add('"' + groupName); } else if (groupName.charAt(0) == '"' && groupName.charAt(groupName.length()-1) != '"') { commandBase.add(groupName + '"'); } else { commandBase.add('"' + groupName + '"'); } this.logger.debug("The base command is " + commandBase.toString() + '.'); try { Process proc = this.executeCommand(commandBase); if (this.isUserInGroup(proc, name)) { return true; } else { this.logger.debug("The user " + name + " is not yet in the user group " + groupName + " for Remote Desktop Access Acction."); final List<String> commandAdd = new ArrayList<String>(); commandAdd.addAll(commandBase); commandAdd.add("/ADD"); if (this.domainName != null) { commandAdd.add("/DOMAIN " + this.domainName); } commandAdd.add(name); this.logger.debug("The command to be executed to add a user to the Remote Desktop Users group is " + commandAdd.toString()); proc = this.executeCommand(commandAdd); proc = this.executeCommand(commandBase); if (!this.isUserInGroup(proc, name)) { this.logger.info("The user " + name + " could not be added to the user group " + groupName + "for Remote Desktop Access using the command " + commandAdd.toString() + '.'); this.failureReason = "User could not be added to Remote Desktop Users group."; return false; } return true; } } catch (final Exception e) { this.logger.info("Executing the command to add user " + name + " to the Remote Desktop users group " + groupName + " failed with error " + e.getMessage() + '.'); this.failureReason = "Command to add user to Remote Desktop Users group has failed."; return false; } } } @Override public boolean revoke(final String name) { synchronized (this) { final List<String> command = new ArrayList<String>(); command.add("qwinsta"); command.add(name); Process proc; try { proc = this.executeCommand(command); final InputStream is = proc.getInputStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while (br.ready() && (line = br.readLine()) != null) { if (line.contains(name)) { final String qwinstaSplit[] = line.split("\\s+"); this.logger.debug("The split qwinsta command is: " + Arrays.toString(qwinstaSplit) + '.'); String logoffID = null; for (int i=0; i<qwinstaSplit.length-1; i++) { if (qwinstaSplit[i].trim().equals(name)) { logoffID = qwinstaSplit[i+1]; } } if (logoffID == null) continue; final List<String> logoffCommand = new ArrayList<String>(); logoffCommand.add("logoff"); logoffCommand.add(logoffID); Process procLogoff; procLogoff = this.executeCommand(logoffCommand); if (procLogoff.exitValue() != 0) { this.logger.warn("Attempt to log off Remote Desktop session ID " + qwinstaSplit[2] + " for user " + name + " returned unexpected result " + procLogoff.exitValue() + '.'); this.failureReason = "User session could not be ended - user acces revoke failed."; return false; } } } br.close(); final List<String> commandBase = new ArrayList<String>(); commandBase.add(RemoteDesktopAccessAction.DEFAULT_COMMAND); commandBase.add(RemoteDesktopAccessAction.DEFAULT_LOCALGROUP); final String groupName = ConfigFactory.getInstance().getProperty("Remote_Desktop_Groupname", RemoteDesktopAccessAction.DEFAULT_GROUPNAME); this.logger.debug("The group name read is " + groupName + '.'); if (groupName.charAt(0) == '"' && groupName.charAt(groupName.length()-1) == '"') { commandBase.add(groupName); } else if (groupName.charAt(0) != '"' && groupName.charAt(groupName.length()-1) == '"') { commandBase.add('"' + groupName); } else if (groupName.charAt(0) == '"' && groupName.charAt(groupName.length()-1) != '"') { commandBase.add(groupName + '"'); } else { commandBase.add('"' + groupName + '"'); } this.logger.debug("The base command is " + commandBase.toString() + '.'); Process procCheck = this.executeCommand(commandBase); if (this.isUserInGroup(procCheck, name)) { final List<String> commandDelete = new ArrayList<String>(); commandDelete.addAll(commandBase); commandDelete.add("/DELETE"); if (this.domainName != null) { commandDelete.add("/DOMAIN " + this.domainName); } commandDelete.add(name); procCheck = this.executeCommand(commandDelete); if (procCheck.exitValue() != 0) { this.failureReason = "User could not be be removed from Remote Desktop Users group."; return false; } } } catch (final Exception e) { this.logger.warn("Revoke action for Remote Desktop Access for user " + name + "failed with exception " + e.getClass().getName() + " and with message " + e.getMessage() + '.'); } } return true; } @Override public String getActionType() { return "Windows Remote Desktop Access"; } @Override public String getFailureReason() { return this.failureReason; } /** * Executes the access action specified using the command and working directory * * @param command * @return Process * @throws Exception */ private Process executeCommand(final List<String> command) throws Exception { final ProcessBuilder builder = new ProcessBuilder(command); Process accessProc = builder.start(); this.logger.info("The Remote Desktop Access Action has invoked the command: " + command.toString() + '.'); accessProc.waitFor(); return accessProc; } /** * Check that a user belongs to the user group. * * @param proc process whose input stream should be searched * @param name of user to be checked * @return true if user is in group * @throws IOException */ private boolean isUserInGroup(final Process proc, final String name) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while (br.ready() && (line = br.readLine()) != null) { if (line.contains(name)) { this.logger.debug("The user " + name + " is in the user group."); return true; } } this.logger.debug("The user " + name + " is NOT in the user group."); return false; } finally { if (br != null) br.close(); } } }
package net.juniper.contrail.vcenter; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import net.juniper.contrail.api.types.VirtualMachine; import net.juniper.contrail.api.types.VirtualMachineInterface; class VmwareVirtualMachineInfo { private String hostName; private String vrouterIpAddress; private String macAddress; private String name; public VmwareVirtualMachineInfo(String name, String hostName, String vrouterIpAddress, String macAddress) { this.name = name; this.hostName = hostName; this.vrouterIpAddress = vrouterIpAddress; this.macAddress = macAddress; } public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public String getVrouterIpAddress() { return vrouterIpAddress; } public void setVrouterIpAddress(String vrouterIpAddress) { this.vrouterIpAddress = vrouterIpAddress; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class VmwareVirtualNetworkInfo { private String name; private int vlanId; private SortedMap<String, VmwareVirtualMachineInfo> vmInfo; private String subnetAddress; private String subnetMask; private String gatewayAddress; public VmwareVirtualNetworkInfo(String name, int vlanId, SortedMap<String, VmwareVirtualMachineInfo> vmInfo, String subnetAddress, String subnetMask, String gatewayAddress) { this.name = name; this.vlanId = vlanId; this.vmInfo = vmInfo; this.subnetAddress = subnetAddress; this.subnetMask = subnetMask; this.gatewayAddress = gatewayAddress; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getVlanId() { return vlanId; } public void setVlanId(int vlanId) { this.vlanId = vlanId; } public SortedMap<String, VmwareVirtualMachineInfo> getVmInfo() { return vmInfo; } public void setVmInfo(SortedMap<String, VmwareVirtualMachineInfo> vmInfo) { this.vmInfo = vmInfo; } public String getSubnetAddress() { return subnetAddress; } public void setSubnetAddress(String subnetAddress) { this.subnetAddress = subnetAddress; } public String getSubnetMask() { return subnetMask; } public void setSubnetMask(String subnetMask) { this.subnetMask = subnetMask; } public String getGatewayAddress() { return gatewayAddress; } public void setGatewayAddress(String gatewayAddress) { this.gatewayAddress = gatewayAddress; } } class VncVirtualMachineInfo { private VirtualMachine vmInfo; private VirtualMachineInterface vmInterfaceInfo; public VncVirtualMachineInfo(VirtualMachine vmInfo, VirtualMachineInterface vmInterfaceInfo) { this.vmInfo = vmInfo; this.vmInterfaceInfo = vmInterfaceInfo; } public VirtualMachine getVmInfo() { return vmInfo; } public void setVmInfo(VirtualMachine vmInfo) { this.vmInfo = vmInfo; } public VirtualMachineInterface getVmInterfaceInfo() { return vmInterfaceInfo; } public void setVmInterfaceInfo(VirtualMachineInterface vmInterfaceInfo) { this.vmInterfaceInfo = vmInterfaceInfo; } } class VncVirtualNetworkInfo { private String name; private SortedMap<String, VncVirtualMachineInfo> vmInfo; public VncVirtualNetworkInfo(String name, SortedMap<String, VncVirtualMachineInfo> vmInfo) { this.name = name; this.vmInfo = vmInfo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public SortedMap<String, VncVirtualMachineInfo> getVmInfo() { return vmInfo; } public void setVmInfo(SortedMap<String, VncVirtualMachineInfo> vmInfo) { this.vmInfo = vmInfo; } } class VCenterMonitorTask implements Runnable { private static Logger s_logger = Logger.getLogger(VCenterMonitorTask.class); private VCenterDB vcenterDB; private VncDB vncDB; public VCenterMonitorTask(String vcenterURL, String vcenterUsername, String vcenterPassword, String apiServerIpAddress, int apiServerPort) throws Exception { vcenterDB = new VCenterDB(vcenterURL, vcenterUsername, vcenterPassword); vncDB = new VncDB(apiServerIpAddress, apiServerPort); // Initialize the databases vcenterDB.Initialize(); vncDB.Initialize(); } private void syncVirtualMachines(String vnUuid, VmwareVirtualNetworkInfo vmwareNetworkInfo, VncVirtualNetworkInfo vncNetworkInfo) throws IOException { String vncVnName = vncNetworkInfo.getName(); String vmwareVnName = vmwareNetworkInfo.getName(); s_logger.info("Syncing virtual machines in network: " + vnUuid + " across Vnc(" + vncVnName + ") and VCenter(" + vmwareVnName + ") DBs"); SortedMap<String, VmwareVirtualMachineInfo> vmwareVmInfos = vmwareNetworkInfo.getVmInfo(); SortedMap<String, VncVirtualMachineInfo> vncVmInfos = vncNetworkInfo.getVmInfo(); Iterator<Entry<String, VmwareVirtualMachineInfo>> vmwareIter = vmwareVmInfos.entrySet().iterator(); Iterator<Entry<String, VncVirtualMachineInfo>> vncIter = vncVmInfos.entrySet().iterator(); Map.Entry<String, VmwareVirtualMachineInfo> vmwareItem = (Entry<String, VmwareVirtualMachineInfo>) (vmwareIter.hasNext() ? vmwareIter.next() : null); Map.Entry<String, VncVirtualMachineInfo> vncItem = (Entry<String, VncVirtualMachineInfo>) (vncIter.hasNext() ? vncIter.next() : null); while (vmwareItem != null && vncItem != null) { // Do Vmware and Vnc virtual machines match? String vmwareVmUuid = vmwareItem.getKey(); String vncVmUuid = vncItem.getKey(); s_logger.info("Comparing Vnc virtual machine: " + vncVmUuid + " and VCenter virtual machine: " + vmwareVmUuid); if (!vmwareVmUuid.equals(vncVmUuid)) { // Delete Vnc virtual machine vncDB.DeleteVirtualMachine(vncItem.getValue()); vncItem = (Entry<String, VncVirtualMachineInfo>) (vncIter.hasNext() ? vncIter.next() : null); } else { // Match found, advance Vmware and Vnc iters vncItem = vncIter.hasNext() ? vncIter.next() : null; vmwareItem = vmwareIter.hasNext() ? vmwareIter.next() : null; } } while (vmwareItem != null) { // Create String vmwareVmUuid = vmwareItem.getKey(); VmwareVirtualMachineInfo vmwareVmInfo = vmwareItem.getValue(); vncDB.CreateVirtualMachine(vnUuid, vmwareVmUuid, vmwareVmInfo.getMacAddress(), vmwareVmInfo.getName(), vmwareVmInfo.getVrouterIpAddress(), vmwareVmInfo.getHostName()); vmwareItem = vmwareIter.hasNext() ? vmwareIter.next() : null; } while (vncItem != null) { // Delete vncDB.DeleteVirtualMachine(vncItem.getValue()); vncItem = vncIter.hasNext() ? vncIter.next() : null; } } private void syncVirtualNetworks() throws Exception { s_logger.info("Syncing Vnc and VCenter DBs"); SortedMap<String, VmwareVirtualNetworkInfo> vmwareVirtualNetworkInfos = vcenterDB.populateVirtualNetworkInfo(); SortedMap<String, VncVirtualNetworkInfo> vncVirtualNetworkInfos = vncDB.populateVirtualNetworkInfo(); Iterator<Entry<String, VmwareVirtualNetworkInfo>> vmwareIter = vmwareVirtualNetworkInfos.entrySet().iterator(); Iterator<Entry<String, VncVirtualNetworkInfo>> vncIter = vncVirtualNetworkInfos.entrySet().iterator(); Map.Entry<String, VmwareVirtualNetworkInfo> vmwareItem = (Entry<String, VmwareVirtualNetworkInfo>) (vmwareIter.hasNext() ? vmwareIter.next() : null); Map.Entry<String, VncVirtualNetworkInfo> vncItem = (Entry<String, VncVirtualNetworkInfo>) (vncIter.hasNext() ? vncIter.next() : null); while (vmwareItem != null && vncItem != null) { // Do Vmware and Vnc networks match? String vmwareVnUuid = vmwareItem.getKey(); String vncVnUuid = vncItem.getKey(); if (!vmwareVnUuid.equals(vncVnUuid)) { // Delete Vnc network vncDB.DeleteVirtualNetwork(vncVnUuid); vncItem = vncIter.hasNext() ? vncIter.next() : null; } else { // Sync syncVirtualMachines(vncVnUuid, vmwareItem.getValue(), vncItem.getValue()); // Advance vncItem = vncIter.hasNext() ? vncIter.next() : null; vmwareItem = vmwareIter.hasNext() ? vmwareIter.next() : null; } } while (vmwareItem != null) { // Create String vmwareVnUuid = vmwareItem.getKey(); VmwareVirtualNetworkInfo vnInfo = vmwareItem.getValue(); SortedMap<String, VmwareVirtualMachineInfo> vmInfos = vnInfo.getVmInfo(); String subnetAddr = vnInfo.getSubnetAddress(); String subnetMask = vnInfo.getSubnetMask(); String gatewayAddr = vnInfo.getGatewayAddress(); String vmwareVnName = vnInfo.getName(); vncDB.CreateVirtualNetwork(vmwareVnUuid, vmwareVnName, subnetAddr, subnetMask, gatewayAddr, vmInfos); vmwareItem = vmwareIter.hasNext() ? vmwareIter.next() : null; } while (vncItem != null) { // Delete vncDB.DeleteVirtualNetwork(vncItem.getKey()); vncItem = vncIter.hasNext() ? vncIter.next() : null; } } @Override public void run() { try { syncVirtualNetworks(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class ExecutorServiceShutdownThread extends Thread { private static final long timeoutValue = 60; private static final TimeUnit timeoutUnit = TimeUnit.SECONDS; private static Logger s_logger = Logger.getLogger(ExecutorServiceShutdownThread.class); private ExecutorService es; public ExecutorServiceShutdownThread(ExecutorService es) { this.es = es; } @Override public void run() { es.shutdown(); try { if (!es.awaitTermination(timeoutValue, timeoutUnit)) { es.shutdownNow(); if (!es.awaitTermination(timeoutValue, timeoutUnit)) { s_logger.error("ExecutorSevice: " + es + " did NOT terminate"); } } } catch (InterruptedException e) { s_logger.info("ExecutorServiceShutdownThread: " + Thread.currentThread() + " ExecutorService: " + e + " interrupted : " + e); } } } public class VCenterMonitor { private static ScheduledExecutorService scheduledTaskExecutor = Executors.newScheduledThreadPool(1); public static void main(String[] args) throws Exception { BasicConfigurator.configure(); final String vcenterURL = "https://10.84.24.111/sdk"; final String vcenterUsername = "admin"; final String vcenterPassword = "Contrail123!"; final String apiServerAddress = "10.84.13.23"; final int apiServerPort = 8082; // Launch the periodic VCenterMonitorTask VCenterMonitorTask monitorTask = new VCenterMonitorTask(vcenterURL, vcenterUsername, vcenterPassword, apiServerAddress, apiServerPort); scheduledTaskExecutor.scheduleWithFixedDelay(monitorTask, 0, 30, TimeUnit.SECONDS); Runtime.getRuntime().addShutdownHook( new ExecutorServiceShutdownThread(scheduledTaskExecutor)); } }
package org.endeavourhealth.queuereader; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import org.endeavourhealth.common.utility.MetricsHelper; import org.endeavourhealth.core.application.ApplicationHeartbeatHelper; import org.endeavourhealth.core.configuration.QueueReaderConfiguration; import org.endeavourhealth.core.queueing.ConnectionManager; import org.endeavourhealth.core.queueing.RabbitConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; public class RabbitHandler { private static final Logger LOG = LoggerFactory.getLogger(RabbitHandler.class); private String configId = null; private QueueReaderConfiguration configuration; private Connection connection; private Channel channel; private RabbitConsumer consumer; private boolean exclusiveReadingOnly; public RabbitHandler(QueueReaderConfiguration configuration, String configId) throws Exception { this.configId = configId; this.configuration = configuration; //some queues are allowed to be read by multiple Queue Readers, and the config tells us. If the config //doesn't, then assume it's exclusive reading only. this.exclusiveReadingOnly = configuration.isExclusive() == null || configuration.isExclusive().booleanValue(); // Connect to rabbit cluster connection = createRabbitConnection(); // Create a channel channel = connection.createChannel(); channel.basicQos(1); // Create consumer consumer = new RabbitConsumer(channel, configuration, configId, this); } private Connection createRabbitConnection() throws IOException, TimeoutException { //use same connection code as for publishing, to save on duplicating the code return ConnectionManager.getConnection( RabbitConfig.getInstance().getUsername(), RabbitConfig.getInstance().getPassword(), RabbitConfig.getInstance().getNodes(), RabbitConfig.getInstance().getSslProtocol(), false); } public void start() throws Exception { LOG.info("Connecting to Rabbit queue {} at {} ", configuration.getQueue(), RabbitConfig.getInstance().getNodes()); // Begin consuming messages AMQP.Queue.DeclareOk response = channel.queueDeclare( configuration.getQueue(), true, // Durable false, // Exclusive (but not the same as the exclusive parameter used below) false, // Auto delete null); //the above return value tells us how many consumers that queue has, which we use in the heartbeat table int consumerCount = response.getConsumerCount(); consumer.setInstanceNumber(consumerCount+1); LOG.info("Consumer number number:=" + consumerCount+1); //pass true for the exclusive parameter, so we can only have one consumer per queue //channel.basicConsume(configuration.getQueue(), false, consumer); channel.basicConsume(configuration.getQueue(), false, configId, false, exclusiveReadingOnly, null, consumer); //now we're running, start these MetricsHelper.startHeartbeat(); ApplicationHeartbeatHelper.start(consumer); } public void stop() throws IOException, TimeoutException { // Close channel channel.close(); // Close connection connection.close(); } }
package gov.nih.nci.ncicb.cadsr.umlmodelbrowser.struts.actions; import gov.nih.nci.cadsr.umlproject.domain.Project; import gov.nih.nci.cadsr.umlproject.domain.SemanticMetadata; import gov.nih.nci.cadsr.umlproject.domain.SubProject; import gov.nih.nci.cadsr.umlproject.domain.UMLAttributeMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLClassMetadata; import gov.nih.nci.cadsr.umlproject.domain.UMLPackageMetadata; import gov.nih.nci.ncicb.cadsr.jsp.bean.PaginationBean; import gov.nih.nci.ncicb.cadsr.service.UMLBrowserQueryService; import gov.nih.nci.ncicb.cadsr.umlmodelbrowser.dto.SearchPreferences; import gov.nih.nci.ncicb.cadsr.umlmodelbrowser.struts.common.UMLBrowserFormConstants; import gov.nih.nci.ncicb.cadsr.umlmodelbrowser.tree.TreeConstants; import gov.nih.nci.ncicb.cadsr.util.BeanPropertyComparator; import gov.nih.nci.ncicb.cadsr.util.UMLBrowserParams; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; 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.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; public class UMLSearchAction extends BaseDispatchAction { protected static Log log = LogFactory.getLog(UMLSearchAction.class.getName()); public UMLSearchAction() { } /** * This Action forwards to the default umplbrowser home. * * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * * @return * * @throws IOException * @throws ServletException */ public ActionForward sendHome( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { removeSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS); return mapping.findForward("umlbrowserHome"); } /** * This Action forwards to the default umlbrowser home. * * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * * @return * * @throws IOException * @throws ServletException */ public ActionForward initSearch( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { removeSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS); //added for New search method to clear the attributes search result from session removeSessionObject(request, UMLBrowserFormConstants.CLASS_NAME); removeSessionObject(request, UMLBrowserFormConstants.ATTRIBUT_NAME); removeSessionObject(request, UMLBrowserFormConstants.PROJECT_IDSEQ); removeSessionObject(request, UMLBrowserFormConstants.PROJECT_VERSION); removeSessionObject(request, UMLBrowserFormConstants.SUB_PROJECT_IDSEQ); removeSessionObject(request, UMLBrowserFormConstants.PACKAGE_IDSEQ); //removeSessionObject(request, "TreeContext"); //Set the lookup values in the session setInitLookupValues(request); setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS, getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS ),true); setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS, getSessionObject(request, UMLBrowserFormConstants.ALL_PACKAGES ),true); return mapping.findForward("umlSearch"); } public ActionForward classSearch( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm dynaForm = (DynaActionForm) form; String resetCrumbs = (String) dynaForm.get(UMLBrowserFormConstants.RESET_CRUMBS); UMLClassMetadata umlClass = this.populateClassFromForm(request,dynaForm); SearchPreferences searchPreferences = (SearchPreferences)getSessionObject(request,UMLBrowserFormConstants.SEARCH_PREFERENCES); this.findClassesLike(umlClass, searchPreferences, request); return mapping.findForward("umlSearch"); } public ActionForward attributeSearch( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // removeSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS); DynaActionForm dynaForm = (DynaActionForm) form; Collection<UMLAttributeMetadata> umlAttributes= new ArrayList(); UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce(); UMLAttributeMetadata umlAtt = new UMLAttributeMetadata(); String attName = ((String) dynaForm.get("attributeName")).trim(); if (attName !=null && attName.length()>0) umlAtt.setName(attName.replace('*','%') ); UMLClassMetadata umlClass = this.populateClassFromForm(request,dynaForm); if (umlClass != null) umlAtt.setUMLClassMetadata(umlClass); SearchPreferences searchPreferences = (SearchPreferences)getSessionObject(request, UMLBrowserFormConstants.SEARCH_PREFERENCES); umlAttributes = queryService.findUmlAttributes(umlAtt, searchPreferences); setupSessionForAttributeResults(umlAttributes, request); return mapping.findForward("showAttributes"); } /* * newSearch method added for newSearch Button. * The method invokes the initSearch method */ /*public ActionForward newSearch( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { return initSearch(mapping, form, request, response); }*/ public ActionForward getAttributesForClass( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String breadCrumb = ""; int selectedClassIndex = Integer.parseInt(request.getParameter("selectedClassIndex")); Collection umlClasses = (Collection) getSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS); Iterator it = umlClasses.iterator(); int umlClassesCounter = 0; UMLClassMetadata umlClass = null; while(it.hasNext() && (umlClassesCounter <= selectedClassIndex)){ umlClass = (UMLClassMetadata)it.next(); umlClassesCounter++; } //UMLClassMetadata umlClass =(UMLClassMetadata) umlClasses.toArray()[selectedClassIndex]; breadCrumb = umlClass.getObjectClass().getContext().getName() + ">>" + umlClass.getProject().getLongName() + ">>" + umlClass.getUMLPackageMetadata().getName() + ">>" + umlClass.getName(); DynaActionForm dynaForm = (DynaActionForm) form; Collection<UMLAttributeMetadata> umlAttributes= umlClass.getUMLAttributeMetadataCollection(); this.setupSessionForAttributeResults(umlAttributes, request); setFormValues(request,dynaForm); //GF 2579 //String cName = (String) getSessionObject(request,UMLBrowserFormConstants.CLASS_NAME); //dynaForm.set("className", umlClass.getName()); //dynaForm.set("className", cName); request.setAttribute(UMLBrowserFormConstants.ATTRIBUTE_CRUMB, breadCrumb); return mapping.findForward("showAttributes"); } /** * Sorts search results by fieldName * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * * @return * * @throws IOException * @throws ServletException */ public ActionForward sortResult( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Set the lookup values in the session DynaActionForm searchForm = (DynaActionForm) form; String sortField = (String) searchForm.get("sortField"); Integer sortOrder = (Integer) searchForm.get("sortOrder"); List umlClasses = (List)getSessionObject(request,UMLBrowserFormConstants.CLASS_SEARCH_RESULTS); //getLazyAssociationsForClass(umlClasses); BeanPropertyComparator comparator = (BeanPropertyComparator)getSessionObject(request,UMLBrowserFormConstants.CLASS_SEARCH_RESULT_COMPARATOR); comparator.setRelativePrimary(sortField); comparator.setOrder(sortOrder.intValue()); //Initialize and add the PagenationBean to the Session PaginationBean pb = new PaginationBean(); if (umlClasses != null) { pb.setListSize(umlClasses.size()); } Collections.sort(umlClasses,comparator); //GF 2579 setFormValues(request,searchForm); setSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS_PAGINATION, pb,true); setSessionObject(request, ANCHOR, "results",true); return mapping.findForward(SUCCESS); } /** * Sorts search results by fieldName * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * * @return * * @throws IOException * @throws ServletException */ public ActionForward sortAttributes( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Set the lookup values in the session DynaActionForm searchForm = (DynaActionForm) form; String sortField = (String) searchForm.get("sortField"); Integer sortOrder = (Integer) searchForm.get("sortOrder"); List umlClasses = (List)getSessionObject(request, UMLBrowserFormConstants.CLASS_ATTRIBUTES); BeanPropertyComparator comparator = (BeanPropertyComparator)getSessionObject(request,UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULT_COMPARATOR); comparator.setRelativePrimary(sortField); comparator.setOrder(sortOrder.intValue()); //Initialize and add the PagenationBean to the Session PaginationBean pb = new PaginationBean(); if (umlClasses != null) { pb.setListSize(umlClasses.size()); } Collections.sort(umlClasses, comparator); //GF 2579 setFormValues(request,searchForm); setSessionObject(request, UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULTS_PAGINATION, pb,true); setSessionObject(request, ANCHOR, "results",true); return mapping.findForward(SUCCESS); } private void findClassesLike (UMLClassMetadata umlClass, SearchPreferences searchPreferences,HttpServletRequest request ) throws Exception { Collection<UMLClassMetadata> umlClasses = new ArrayList(); UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce(); umlClasses = queryService.findUmlClass(umlClass, searchPreferences); setupSessionForClassResults(umlClasses, request); } private void setupSessionForAttributeResults(Collection<UMLAttributeMetadata> umlAttributes, HttpServletRequest request){ setSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW, false, true); setSessionObject(request, UMLBrowserFormConstants.CLASS_ATTRIBUTES, umlAttributes,true); PaginationBean pb = new PaginationBean(); if (umlAttributes != null) { pb.setListSize(umlAttributes.size()); } UMLAttributeMetadata anAttribute = null; if(umlAttributes.size()>0) { //Object[] attArr = umlAttributes.toArray(); anAttribute=(UMLAttributeMetadata)umlAttributes.iterator().next(); BeanPropertyComparator comparator = new BeanPropertyComparator(anAttribute.getClass()); comparator.setPrimary("name"); comparator.setOrder(comparator.ASCENDING); Collections.sort((List)umlAttributes,comparator); setSessionObject(request,UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULT_COMPARATOR,comparator); } setSessionObject(request, UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULTS_PAGINATION, pb,true); } private void setupSessionForClassResults(Collection umlClasses, HttpServletRequest request){ setSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS, umlClasses,true); setSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW, true, true); PaginationBean pb = new PaginationBean(); if (umlClasses != null) { pb.setListSize(umlClasses.size()); UMLClassMetadata aClass = null; if(umlClasses.size()>0) { aClass=(UMLClassMetadata)umlClasses.iterator().next(); BeanPropertyComparator comparator = new BeanPropertyComparator(aClass.getClass()); comparator.setPrimary("name"); comparator.setOrder(comparator.ASCENDING); Collections.sort((List)umlClasses,comparator); setSessionObject(request,UMLBrowserFormConstants.CLASS_SEARCH_RESULT_COMPARATOR,comparator); //getLazyAssociationsForClass(umlClasses); } } setSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS_PAGINATION, pb,true); } private UMLClassMetadata populateClassFromForm(HttpServletRequest request,DynaActionForm dynaForm) { UMLClassMetadata umlClass = null; Project project = null; String className = ((String) dynaForm.get("className")).trim(); if (className != null && className.length() >0) { umlClass = new UMLClassMetadata(); className = className.replace('*','%'); umlClass.setName(className); } setSessionObject(request,UMLBrowserFormConstants.CLASS_NAME,dynaForm.getString(UMLBrowserFormConstants.CLASS_NAME)); String attributeName = ((String) dynaForm.get("attributeName")).trim(); setSessionObject(request,UMLBrowserFormConstants.ATTRIBUT_NAME,dynaForm.getString(UMLBrowserFormConstants.ATTRIBUT_NAME)); String projectId = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_IDSEQ)).trim(); if (projectId != null && projectId.length() >0) { if (umlClass == null) umlClass = new UMLClassMetadata(); project = new Project(); project.setId(projectId); umlClass.setProject(project); } setSessionObject(request,UMLBrowserFormConstants.PROJECT_IDSEQ,dynaForm.getString(UMLBrowserFormConstants.PROJECT_IDSEQ)); String projectVersion = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_VERSION)).trim(); if (projectVersion != null && projectVersion.length() >0) { if (umlClass == null) umlClass = new UMLClassMetadata(); if (project == null) { project = new Project(); umlClass.setProject(project); } projectVersion = projectVersion.replace('*','%'); project.setVersion(projectVersion); } setSessionObject(request,UMLBrowserFormConstants.PROJECT_VERSION,dynaForm.getString(UMLBrowserFormConstants.PROJECT_VERSION)); UMLPackageMetadata packageMetadata = null; String subprojectId = ((String) dynaForm.get(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)).trim(); if (projectId != null && subprojectId.length() >0) { if (umlClass == null) umlClass = new UMLClassMetadata(); SubProject subproject = new SubProject(); subproject.setId(subprojectId); packageMetadata = new UMLPackageMetadata(); packageMetadata.setSubProject(subproject); } setSessionObject(request,UMLBrowserFormConstants.SUB_PROJECT_IDSEQ,dynaForm.getString(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)); String packageId = ((String) dynaForm.get(UMLBrowserFormConstants.PACKAGE_IDSEQ)).trim(); if (packageId != null && packageId.length() >0) { if (umlClass == null) umlClass = new UMLClassMetadata(); if (packageMetadata == null) packageMetadata = new UMLPackageMetadata(); packageMetadata.setId(packageId); } setSessionObject(request,UMLBrowserFormConstants.PACKAGE_IDSEQ,dynaForm.getString(UMLBrowserFormConstants.PACKAGE_IDSEQ)); if (packageMetadata != null) umlClass.setUMLPackageMetadata(packageMetadata); return umlClass; } private void setFormValues(HttpServletRequest request, DynaActionForm form){ form.set(UMLBrowserFormConstants.CLASS_NAME,(String)getSessionObject(request,UMLBrowserFormConstants.CLASS_NAME) ); form.set(UMLBrowserFormConstants.ATTRIBUT_NAME, (String) getSessionObject(request,UMLBrowserFormConstants.ATTRIBUT_NAME)); form.set(UMLBrowserFormConstants.PROJECT_IDSEQ,(String) getSessionObject(request,UMLBrowserFormConstants.PROJECT_IDSEQ)); form.set(UMLBrowserFormConstants.PROJECT_VERSION,(String) getSessionObject(request,UMLBrowserFormConstants.PROJECT_VERSION)); form.set(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ,(String) getSessionObject(request,UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)); form.set(UMLBrowserFormConstants.PACKAGE_IDSEQ,(String) getSessionObject(request,UMLBrowserFormConstants.PACKAGE_IDSEQ)); return; } private void reSetFormValues(HttpServletRequest request, DynaActionForm form){ form.set(UMLBrowserFormConstants.CLASS_NAME, "" ); form.set(UMLBrowserFormConstants.ATTRIBUT_NAME,""); form.set(UMLBrowserFormConstants.PROJECT_IDSEQ,""); form.set(UMLBrowserFormConstants.PROJECT_VERSION,""); form.set(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ,""); form.set(UMLBrowserFormConstants.PACKAGE_IDSEQ,""); removeSessionObject(request, UMLBrowserFormConstants.CLASS_NAME); removeSessionObject(request, UMLBrowserFormConstants.ATTRIBUT_NAME); removeSessionObject(request, UMLBrowserFormConstants.PROJECT_IDSEQ); removeSessionObject(request, UMLBrowserFormConstants.PROJECT_VERSION); removeSessionObject(request, UMLBrowserFormConstants.SUB_PROJECT_IDSEQ); removeSessionObject(request, UMLBrowserFormConstants.PACKAGE_IDSEQ); return; } public ActionForward resetSubProjPkgOptions( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { DynaActionForm dynaForm = (DynaActionForm) form; String projectId = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_IDSEQ)).trim(); if (projectId == null || projectId.length() == 0) { setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS, getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS ),true); setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS, getSessionObject(request, UMLBrowserFormConstants.ALL_PACKAGES ),true); } else { Project project = setPackageOptionsForProjectId(request, projectId); if (project != null ){ setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS, project.getSubProjectCollection(), true); } } Object classView = getSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW); String showClass = null; if (classView != null) showClass=classView.toString(); if (showClass == null || showClass.equalsIgnoreCase("true")) return mapping.findForward("umlSearch"); return mapping.findForward("showAttributes"); } public ActionForward resetPkgOptions( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { DynaActionForm dynaForm = (DynaActionForm) form; String projectId = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_IDSEQ)).trim(); String subprojId = ((String) dynaForm.get(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)).trim(); if (subprojId == null || subprojId.length() == 0) { // if subProject is ALL, set package options by project setPackageOptionsForProjectId(request, projectId); } else { SubProject subproject = null; Collection<SubProject> allSubProjects = (Collection) getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS); for (Iterator subprojIter =allSubProjects.iterator(); subprojIter.hasNext(); ) { subproject = (SubProject) subprojIter.next(); if (subproject.getId().equalsIgnoreCase(subprojId)) break; } if (subproject != null ){ setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS, subproject.getUMLPackageMetadataCollection(), true); } } String showClass = null; if (getSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW) != null) showClass=getSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW).toString(); if (showClass == null || showClass.equalsIgnoreCase("true")) return mapping.findForward("umlSearch"); return mapping.findForward("showAttributes"); } private Project setPackageOptionsForProjectId (HttpServletRequest request, String projectId){ Project project = null; Collection<Project> allProjects = (Collection) getSessionObject(request, UMLBrowserFormConstants.ALL_PROJECTS); for (Iterator projIter =allProjects.iterator(); projIter.hasNext(); ) { project = (Project) projIter.next(); if (project.getId().equalsIgnoreCase(projectId)) break; } if (project != null ){ UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce(); setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS, queryService.getAllPackageForProject(project),true); } return project; } private Project setSubProjectOptionsForProjectId (HttpServletRequest request, String projectId){ Project project = null; Collection<Project> allProjects = (Collection) getSessionObject(request, UMLBrowserFormConstants.ALL_PROJECTS); for (Iterator projIter =allProjects.iterator(); projIter.hasNext(); ) { project = (Project) projIter.next(); if (project.getId().equalsIgnoreCase(projectId)) break; } if (project != null ){ setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS, project.getSubProjectCollection(), true); } return project; } private SubProject setPackageOptionsForSubProjectId (HttpServletRequest request, String subProjectId){ SubProject subProject = null; Collection<SubProject> allSubProjects = (Collection) getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS); for (Iterator subprojIter =allSubProjects.iterator(); subprojIter.hasNext(); ) { subProject = (SubProject) subprojIter.next(); if (subProject.getId().equalsIgnoreCase(subProjectId)) break; } if (subProject != null ){ setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS, subProject.getUMLPackageMetadataCollection(), true); } return subProject; } /* * Retrieves form values from the TreeBreadCrumb and sets them in session */ private void getFormValuesFromTreeCrumb(HttpServletRequest request, UMLBrowserQueryService queryService){ String treeBreadCrumb = request.getParameter(TreeConstants.TREE_BREADCRUMBS); log.info("Setting formValues from TreeBreadCrumb: "+treeBreadCrumb); String[] treeCrumbs = null; String caDSRContext =""; String context = ""; String projectsText = ""; String projectName =""; String treeCrumbProjectId = ""; String subProjectName = ""; String treeCrumbSubProjectId = ""; String packageName = ""; String treeCrumbPackageId = ""; String className = ""; if(treeBreadCrumb != null){ treeCrumbs = treeBreadCrumb.split(">>"); for (int i=0; i<treeCrumbs.length; i++){ if(i==0) caDSRContext = treeCrumbs[0]; if(i==1) context = treeCrumbs[1]; if(i==2) projectsText = treeCrumbs[2]; if(i==3) projectName = treeCrumbs[3]; if(i==4) subProjectName = treeCrumbs[4]; if(i==5) packageName = treeCrumbs[5]; if(i==6) className = treeCrumbs[6]; } } List<Project> formProjects = new ArrayList<Project>(); List<SubProject> formSubProjects = new ArrayList<SubProject>(); List<UMLPackageMetadata> formPackages = new ArrayList<UMLPackageMetadata> (); if(projectName != null || !projectName.equals("")){ Project formProject = new Project(); formProject.setLongName(projectName); formProjects = queryService.findProject(formProject); //System.out.println(".... found "+formProjects.size()+" projects with LongName "+projectName); for (Object obj: formProjects){ Project proj = (Project)obj; treeCrumbProjectId = proj.getId(); ////Get Project Id to set in form //System.out.println("........ProjectId: "+proj.getId()); formSubProjects = (List<SubProject>) proj.getSubProjectCollection(); log.debug("--- "+formSubProjects.size()+" subProjects for the project "+projectName); if(formSubProjects.size() != 0){ for(Object oSub: formSubProjects){ SubProject formSub = (SubProject) oSub; if(subProjectName.equalsIgnoreCase(formSub.getName())){ treeCrumbSubProjectId = formSub.getId(); //System.out.println("........Sub_ProjectId: "+formSub.getId()); } }//Get subproject Id to set in form }else{ //If subproject does not exist for a Project, Rearrange breadcrumbs log.debug("---Rearranging BreadCrumbs"); className = packageName; packageName = subProjectName; } formPackages = (List<UMLPackageMetadata>) proj.getUMLPackageMetadataCollection(); if(!packageName.equals("")){ for(Object oPackage: formPackages){ UMLPackageMetadata formPackage = (UMLPackageMetadata)oPackage; if(packageName.equalsIgnoreCase(formPackage.getName())){ treeCrumbPackageId = formPackage.getId(); //System.out.println("........PackageId: "+formPackage.getId()); } } } //Get package Id to set in form } } setSessionObject(request,UMLBrowserFormConstants.PROJECT_IDSEQ,treeCrumbProjectId); setSessionObject(request,UMLBrowserFormConstants.SUB_PROJECT_IDSEQ,treeCrumbSubProjectId); setSessionObject(request,UMLBrowserFormConstants.PACKAGE_IDSEQ,treeCrumbPackageId); setSessionObject(request,UMLBrowserFormConstants.CLASS_NAME,className); setSessionObject(request,UMLBrowserFormConstants.ATTRIBUT_NAME, ""); setSessionObject(request,UMLBrowserFormConstants.PROJECT_VERSION,""); } public ActionForward treeClassSearch( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { String searchType = request.getParameter("P_PARAM_TYPE"); String searchId = request.getParameter("P_IDSEQ"); UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce(); Collection umlClasses = null; //GF: 2579 DynaActionForm dynaForm = (DynaActionForm)form; reSetFormValues(request, dynaForm); getFormValuesFromTreeCrumb(request,queryService); //This method will retrieve values from TreeBreadCrumb and set it in Session //GF 2579 if (searchType.equalsIgnoreCase("Class") ) { UMLClassMetadata umlClass = new UMLClassMetadata(); umlClass.setId(searchId); UMLAttributeMetadata umlAttribute = new UMLAttributeMetadata(); umlAttribute.setUMLClassMetadata(umlClass); Collection umlAttributes = queryService.findUmlAttributes(umlAttribute); dynaForm.set(UMLBrowserFormConstants.CLASS_NAME,(String)getSessionObject(request, UMLBrowserFormConstants.CLASS_NAME)); dynaForm.set(UMLBrowserFormConstants.PROJECT_IDSEQ,(String)getSessionObject(request, UMLBrowserFormConstants.PROJECT_IDSEQ)); dynaForm.set(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ, (String)getSessionObject(request, UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)); dynaForm.set(UMLBrowserFormConstants.PACKAGE_IDSEQ, (String)getSessionObject(request, UMLBrowserFormConstants.PACKAGE_IDSEQ)); setupSessionForAttributeResults(umlAttributes, request); return mapping.findForward("showAttributes"); } if (searchType.equalsIgnoreCase("Context") ) { setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS, getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS ),true); setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS, getSessionObject(request, UMLBrowserFormConstants.ALL_PACKAGES ),true); umlClasses = queryService.getClassesForContext(searchId); } if (searchType.equalsIgnoreCase("Project") ) { UMLClassMetadata umlClass = new UMLClassMetadata(); Project project = new Project(); project.setId(searchId); dynaForm.set(UMLBrowserFormConstants.PROJECT_IDSEQ,searchId); setSubProjectOptionsForProjectId(request,searchId); setPackageOptionsForProjectId(request, searchId); umlClass.setProject(project); umlClasses = queryService.findUmlClass(umlClass); } if (searchType.equalsIgnoreCase("Container") ) { umlClasses = queryService.findUmlClassForContainer(searchId); } if (searchType.equalsIgnoreCase("SubProject") ) { UMLClassMetadata umlClass = new UMLClassMetadata(); SubProject subproject = new SubProject(); subproject.setId(searchId); dynaForm.set(UMLBrowserFormConstants.PROJECT_IDSEQ,(String)getSessionObject(request, UMLBrowserFormConstants.PROJECT_IDSEQ)); dynaForm.set(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ,searchId); setPackageOptionsForSubProjectId(request, searchId); UMLPackageMetadata packageMetadata= new UMLPackageMetadata(); packageMetadata.setSubProject(subproject); umlClass.setUMLPackageMetadata(packageMetadata); umlClasses = queryService.findUmlClass(umlClass); } if (searchType.equalsIgnoreCase("Package") ) { UMLClassMetadata umlClass = new UMLClassMetadata(); UMLPackageMetadata packageMetadata= new UMLPackageMetadata(); packageMetadata.setId(searchId); dynaForm.set(UMLBrowserFormConstants.PROJECT_IDSEQ,(String)getSessionObject(request, UMLBrowserFormConstants.PROJECT_IDSEQ)); dynaForm.set(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ, (String)getSessionObject(request, UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)); dynaForm.set(UMLBrowserFormConstants.PACKAGE_IDSEQ,searchId); umlClass.setUMLPackageMetadata(packageMetadata); umlClasses = queryService.findUmlClass(umlClass); } setupSessionForClassResults(umlClasses, request); } catch (Exception e) { log.error(e); throw new ServletException("Error occurred while performing tree search", e); } return mapping.findForward("umlSearch"); } private void getLazyAssociationsForClass(Collection classList) { if(classList==null) return; int itemPerPage = UMLBrowserParams.getInstance().getItemPerPage(); int count = 0; for (Iterator resultsIterator = classList.iterator(); resultsIterator.hasNext();) { UMLClassMetadata returnedClass = (UMLClassMetadata) resultsIterator.next(); for (Iterator mdIterator = returnedClass.getSemanticMetadataCollection().iterator(); mdIterator.hasNext();) { SemanticMetadata metaData = (SemanticMetadata) mdIterator.next(); } } ++count; if(itemPerPage<=count) return; } }
package au.gov.ga.geodesy.support.mapper.dozer; import org.dozer.CustomConverter; import org.dozer.MappingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.opengis.iso19139.gco.v_20070417.CodeListValueType; /** * Convert: java.lang.String <--> net.opengis.gml.v_3_2_1.CodeListValueType * * Also handles these extending classes: * au.gov.xml.icsm.geodesyml.v_0_3.IgsReceiverModelCodeType * au.gov.xml.icsm.geodesyml.v_0_3.IgsAntennaModelCodeType * */ public class CodeListValueTypeConverter implements CustomConverter { Logger logger = LoggerFactory.getLogger(getClass()); @SuppressWarnings("rawtypes") public Object convert(Object destination, Object source, Class destClass, Class sourceClass) { if (source == null) { return null; } if (source instanceof String) { Object destClassInstance = null; if (destination == null) { try { destClassInstance = destClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.error("Error createing Dozer destination", e); } } else { destClassInstance = destination; } CodeListValueType destClassInstanceType = (CodeListValueType) destClassInstance; destClassInstanceType.setValue((String) source); destClassInstanceType.setCodeList("codelist"); destClassInstanceType.setCodeListValue("codeListValue"); return destClassInstance; } else if (source instanceof CodeListValueType) { return ((CodeListValueType) source).getValue(); } else { throw new MappingException("Converter " + getClass().getName() + "used incorrectly. Arguments passed in were:" + destination + " and " + source); } } }
package com.emarte.regurgitator.extensions.mq; public interface ExtensionsMqConfigConstants { String REQUEST_METADATA_CONTEXT = "request-metadata"; String REQUEST_PROPERTIES_CONTEXT = "request-properties"; String REQUEST_PAYLOAD_CONTEXT = "request-payload"; String RESPONSE_METADATA_CONTEXT = "response-metadata"; String RESPONSE_PROPERTIES_CONTEXT = "response-properties"; String JMS_MESSAGE_ID = "jms-message-id"; String JMS_TYPE = "jms-type"; String JMS_DESTINATION = "jms-destination"; String JMS_CORRELATION_ID = "jms-correlation-id"; String JMS_DELIVERY_MODE = "jms-delivery-mode"; String JMS_EXPIRATION = "jms-expiration"; String JMS_PRIORITY = "jms-priority"; String JMS_REDELIVERED = "jms-redelivered"; String JMS_REPLY_TO = "jms-reply-to"; String JMS_TIMESTAMP = "jms-timestamp"; String TEXT = "text"; }
package com.lothrazar.cyclicmagic.component.builder; import com.lothrazar.cyclicmagic.IHasRecipe; import com.lothrazar.cyclicmagic.block.base.BlockBaseFacingInventory; import com.lothrazar.cyclicmagic.block.base.IBlockHasTESR; import com.lothrazar.cyclicmagic.block.base.MachineTESR; import com.lothrazar.cyclicmagic.gui.ForgeGuiHandler; import com.lothrazar.cyclicmagic.registry.RecipeRegistry; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockStructureBuilder extends BlockBaseFacingInventory implements IHasRecipe, IBlockHasTESR { public BlockStructureBuilder() { super(Material.IRON, ForgeGuiHandler.GUI_INDEX_BUILDER); this.setHardness(3.0F).setResistance(5.0F); this.setSoundType(SoundType.METAL); this.setTickRandomly(true); } @SideOnly(Side.CLIENT) public void initModel() { ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory")); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityStructureBuilder.class, new MachineTESR(this, 0)); } @Override public TileEntity createTileEntity(World worldIn, IBlockState state) { return new TileEntityStructureBuilder(); } @Override public IRecipe addRecipe() { return RecipeRegistry.addShapedRecipe(new ItemStack(this), "rsr", "gbg", "ooo", 'o', "obsidian", 'g', Blocks.OBSERVER, 's', Blocks.DISPENSER, 'r', "blockRedstone", 'b', Blocks.MAGMA); } }
package com.royalrangers.controller.achievement; import com.royalrangers.bean.ResponseResult; import com.royalrangers.bean.UserBean; import com.royalrangers.model.achievement.*; import com.royalrangers.service.achievement.*; import com.royalrangers.utils.ResponseBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import static com.royalrangers.service.achievement.UserAchievementService.getUsersFromUserAchievements; @RestController @RequestMapping("/achievements/userAchievement") public class UserAchievementController { @Autowired private UserTaskService userTaskService; @Autowired private UserTestService userTestService; @Autowired private UserQuarterAchievementService userQuarterAchievementService; @Autowired private UserYearAchievementService userYearAchievementService; @Autowired private UserThreeYearAchievementService userThreeYearAchievementService; @Autowired private UserTwelveYearAchievementService userTwelveYearAchievementService; @GetMapping("/task") @PreAuthorize("hasRole('ADMIN')") public ResponseResult getUsersListForTask(@RequestParam Long platoonId, @RequestParam Long taskId, @RequestParam String achievementState){ List<UserTask> userAchievementList = userTaskService.getUserTasksByTaskId(taskId); List<UserBean> result = getUsersFromUserAchievements(userAchievementList, platoonId,achievementState); return ResponseBuilder.success(result); } @GetMapping("/test") @PreAuthorize("hasRole('ADMIN')") public ResponseResult getUsersListForTest(@RequestParam Long platoonId, @RequestParam Long testId, @RequestParam String achievementState){ List<UserTest> userAchievementList = userTestService.getUserTestsByTestId(testId); List<UserBean> result = getUsersFromUserAchievements(userAchievementList, platoonId,achievementState); return ResponseBuilder.success(result); } @GetMapping("/quarterAchievement") @PreAuthorize("hasRole('ADMIN')") public ResponseResult getUsersListForQuarterAchievement(@RequestParam Long platoonId, @RequestParam Long achievementId, @RequestParam String achievementState){ List<UserQuarterAchievement> userAchievementList = userQuarterAchievementService.getUserQuarterAchievementByAchievementId(achievementId); List<UserBean> result = getUsersFromUserAchievements(userAchievementList, platoonId,achievementState); return ResponseBuilder.success(result); } @GetMapping("/yearAchievement") @PreAuthorize("hasRole('ADMIN')") public ResponseResult getUsersListForYearAchievement(@RequestParam Long platoonId, @RequestParam Long achievementId, @RequestParam String achievementState){ List<UserYearAchievement> userAchievementList = userYearAchievementService.getUserYearAchievementByAchievementId(achievementId); List<UserBean> result = getUsersFromUserAchievements(userAchievementList, platoonId,achievementState); return ResponseBuilder.success(result); } @GetMapping("/threeYearAchievement") @PreAuthorize("hasRole('ADMIN')") public ResponseResult getUsersListForThreeYearAchievement(@RequestParam Long platoonId, @RequestParam Long achievementId, @RequestParam String achievementState){ List<UserThreeYearAchievement> userAchievementList = userThreeYearAchievementService.getUserThreeYearAchievementByAchievementId(achievementId); List<UserBean> result = getUsersFromUserAchievements(userAchievementList, platoonId,achievementState); return ResponseBuilder.success(result); } @GetMapping("/twelveYearAchievement") @PreAuthorize("hasRole('ADMIN')") public ResponseResult getUsersListForTwelveYearAchievement(@RequestParam Long platoonId, @RequestParam Long achievementId, @RequestParam String achievementState){ List<UserTwelveYearAchievement> userAchievementList = userTwelveYearAchievementService.getUserTwelveYearAchievementByAchievementId(achievementId); List<UserBean> result = getUsersFromUserAchievements(userAchievementList, platoonId,achievementState); return ResponseBuilder.success(result); } }
package com.skelril.skree.content.world.wilderness; import com.flowpowered.math.vector.Vector3d; import com.google.common.collect.Lists; import com.skelril.nitro.combat.PlayerCombatParser; import com.skelril.nitro.data.util.EnchantmentUtil; import com.skelril.nitro.droptable.DropTable; import com.skelril.nitro.droptable.DropTableEntryImpl; import com.skelril.nitro.droptable.DropTableImpl; import com.skelril.nitro.droptable.MasterDropTable; import com.skelril.nitro.droptable.resolver.SimpleDropResolver; import com.skelril.nitro.droptable.roller.SlipperySingleHitDiceRoller; import com.skelril.nitro.entity.EntityHealthPrinter; import com.skelril.nitro.item.ItemDropper; import com.skelril.nitro.numeric.MathExt; import com.skelril.nitro.probability.Probability; import com.skelril.nitro.registry.dynamic.ItemStackConfig; import com.skelril.nitro.registry.dynamic.QuantityBoundedItemStackConfig; import com.skelril.nitro.text.CombinedText; import com.skelril.nitro.text.PlaceHolderText; import com.skelril.nitro.time.IntegratedRunnable; import com.skelril.nitro.time.TimedRunnable; import com.skelril.skree.SkreePlugin; import com.skelril.skree.content.droptable.CofferResolver; import com.skelril.skree.content.modifier.Modifiers; import com.skelril.skree.content.world.main.MainWorldWrapper; import com.skelril.skree.content.world.wilderness.wanderer.Fangz; import com.skelril.skree.content.world.wilderness.wanderer.GraveDigger; import com.skelril.skree.content.world.wilderness.wanderer.StormBringer; import com.skelril.skree.content.world.wilderness.wanderer.WanderingBoss; import com.skelril.skree.service.ModifierService; import com.skelril.skree.service.PvPService; import com.skelril.skree.service.WorldService; import com.skelril.skree.service.internal.world.WorldEffectWrapperImpl; import org.apache.commons.lang3.Validate; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.mutable.entity.HealthData; import org.spongepowered.api.data.meta.ItemEnchantment; import org.spongepowered.api.data.type.HandTypes; import org.spongepowered.api.data.value.mutable.Value; import org.spongepowered.api.effect.particle.ParticleEffect; import org.spongepowered.api.effect.particle.ParticleTypes; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.effect.potion.PotionEffectTypes; import org.spongepowered.api.entity.*; import org.spongepowered.api.entity.explosive.PrimedTNT; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.monster.Boss; import org.spongepowered.api.entity.living.monster.Creeper; import org.spongepowered.api.entity.living.monster.Monster; import org.spongepowered.api.entity.living.monster.Wither; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.gamemode.GameModes; import org.spongepowered.api.entity.projectile.Egg; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.explosive.fireball.Fireball; import org.spongepowered.api.event.Cancellable; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.NamedCause; import org.spongepowered.api.event.cause.entity.damage.DamageModifier; import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource; import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource; import org.spongepowered.api.event.cause.entity.spawn.BlockSpawnCause; import org.spongepowered.api.event.cause.entity.spawn.SpawnCause; import org.spongepowered.api.event.cause.entity.spawn.SpawnTypes; import org.spongepowered.api.event.entity.CollideEntityEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.event.entity.living.humanoid.player.RespawnPlayerEvent; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.filter.cause.Named; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.item.Enchantments; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.scheduler.Task; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextStyles; import org.spongepowered.api.text.title.Title; import org.spongepowered.api.util.Tuple; import org.spongepowered.api.world.BlockChangeFlag; import org.spongepowered.api.world.DimensionTypes; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.extent.Extent; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import static com.skelril.nitro.item.ItemStackFactory.newItemStack; import static com.skelril.nitro.transformer.ForgeTransformer.tf; import static com.skelril.skree.content.registry.TypeCollections.ore; import static com.skelril.skree.content.registry.block.CustomBlockTypes.GRAVE_STONE; import static com.skelril.skree.content.registry.item.CustomItemTypes.*; import static java.util.concurrent.TimeUnit.SECONDS; public class WildernessWorldWrapper extends WorldEffectWrapperImpl implements Runnable { private WildernessConfig config; private DropTable commonDropTable; private DropTable netherMobDropTable; private Map<UUID, WildernessPlayerMeta> playerMetaMap = new HashMap<>(); private WanderingMobManager wanderingMobManager; public WildernessWorldWrapper(WildernessConfig config) { this(config, new ArrayList<>()); } public WildernessWorldWrapper(WildernessConfig config, Collection<World> worlds) { super("Wilderness", worlds); this.config = config; SlipperySingleHitDiceRoller slipRoller = new SlipperySingleHitDiceRoller((a, b) -> (int) (a + b)); commonDropTable = new MasterDropTable( slipRoller, Lists.newArrayList( new DropTableImpl( slipRoller, Lists.newArrayList( new DropTableEntryImpl(new CofferResolver(50), 12) ) ), new DropTableImpl( slipRoller, Lists.newArrayList( new DropTableEntryImpl( new SimpleDropResolver( Lists.newArrayList( newItemStack((ItemType) SCROLL_OF_SUMMATION) ) ), 2000 ), new DropTableEntryImpl( new SimpleDropResolver( Lists.newArrayList( newItemStack("skree:two_tailed_sword") ) ), 10000 ) ) ), new DropTableImpl( slipRoller, Lists.newArrayList( new DropTableEntryImpl( new SimpleDropResolver( Lists.newArrayList( newItemStack((ItemType) RED_FEATHER) ) ), 100000 ) ) ) ) ); netherMobDropTable = new MasterDropTable( slipRoller, Lists.newArrayList( commonDropTable, new DropTableImpl( slipRoller, Lists.newArrayList( new DropTableEntryImpl( new SimpleDropResolver( Lists.newArrayList( newItemStack("skree:nether_bow") ) ), 10000 ), new DropTableEntryImpl( new SimpleDropResolver( Lists.newArrayList( newItemStack((ItemType) NETHER_BOWL) ) ), 20000 ) ) ) ) ); Task.builder().execute(this).interval(1, SECONDS).submit(SkreePlugin.inst()); setupWanderers(); } private void setupWanderers() { Map<String, WanderingBoss<? extends Entity>> wanderers = new HashMap<>(); wanderers.put("fangz", new Fangz()); wanderers.put("grave_digger", new GraveDigger()); wanderers.put("storm_bringer", new StormBringer()); wanderingMobManager = new WanderingMobManager(wanderers); } public WanderingMobManager getWanderingMobManager() { return wanderingMobManager; } @Override public void addWorld(World world) { super.addWorld(world); tf(world).setAllowedSpawnTypes(true, true); } @Listener public void onEntitySpawn(SpawnEntityEvent event) { List<Entity> entities = event.getEntities(); Optional<BlockSpawnCause> optBlockCause = event.getCause().first(BlockSpawnCause.class); for (Entity entity : entities) { Location<World> loc = entity.getLocation(); Optional<Integer> optLevel = getLevel(loc); if (!optLevel.isPresent()) { continue; } int level = optLevel.get(); if (entity instanceof Egg && optBlockCause.isPresent()) { PrimedTNT explosive = (PrimedTNT) entity.getLocation().getExtent().createEntity( EntityTypes.PRIMED_TNT, entity.getLocation().getPosition() ); explosive.setVelocity(entity.getVelocity()); explosive.offer(Keys.FUSE_DURATION, 20 * 4); // TODO used to have a 1/4 chance of creating fire entity.getLocation().getExtent().spawnEntity( explosive, Cause.source(SpawnCause.builder().type(SpawnTypes.DISPENSE).build()).build() ); event.setCancelled(true); return; } if (level > 1) { // TODO move damage modification if (entity instanceof Monster) { HealthData healthData = ((Monster) entity).getHealthData(); double curMax = healthData.maxHealth().get(); if (curMax <= 80) { // TODO do this a better way, but for now it prevents super mobs double newMax = curMax * getHealthMod(level); healthData.set(Keys.MAX_HEALTH, newMax); healthData.set(Keys.HEALTH, newMax); entity.offer(healthData); } // Wandering Bosses Collection<String> wanderers = wanderingMobManager.getSupportedWanderersOfType(entity.getType()); for (String wanderer : wanderers) { if (wanderingMobManager.chanceBind(wanderer, level, entity)) { break; } } } } Optional<Value<Integer>> optExplosiveRadius = Optional.empty(); // Optional<Value<Integer>> optExplosiveRadius = event.getEntity().getValue(Keys.EXPLOSIVE_RADIUS); if (optExplosiveRadius.isPresent()) { Value<Integer> explosiveRadius = optExplosiveRadius.get(); int min = explosiveRadius.get(); entity.offer( Keys.EXPLOSION_RADIUS, Optional.of(MathExt.bound((min + level) / 2, min, entity instanceof Fireball ? 4 : 9)) ); } } } @Listener public void onRespawn(RespawnPlayerEvent event) { if (isApplicable(event.getToTransform().getExtent())) { Optional<WorldService> optWorldService = Sponge.getServiceManager().provide(WorldService.class); if (optWorldService.isPresent()) { Collection<World> worlds = optWorldService.get().getEffectWrapper(MainWorldWrapper.class).get().getWorlds(); event.setToTransform(new Transform<>(worlds.iterator().next().getSpawnLocation())); } } } private final EntityHealthPrinter healthPrinter = new EntityHealthPrinter( CombinedText.of( TextColors.DARK_AQUA, "Entity Health: ", new PlaceHolderText("health int"), " / ", new PlaceHolderText("max health int") ), CombinedText.of(TextColors.GOLD, TextStyles.BOLD, "KO!") ); private PlayerCombatParser createFor(Cancellable event, int level) { return new PlayerCombatParser() { @Override public void processPvP(Player attacker, Player defender) { if (allowsPvP(level)) { return; } Optional<PvPService> optService = Sponge.getServiceManager().provide(PvPService.class); if (optService.isPresent()) { PvPService service = optService.get(); if (service.getPvPState(attacker).allowByDefault() && service.getPvPState(defender).allowByDefault()) { return; } } attacker.sendMessage(Text.of(TextColors.RED, "PvP is opt-in only in this part of the Wilderness!")); attacker.sendMessage(Text.of(TextColors.RED, "Mandatory PvP is from level ", getFirstPvPLevel(), " and on.")); event.setCancelled(true); } @Override public void processMonsterAttack(Living attacker, Player defender) { if (!(event instanceof DamageEntityEvent)) { return; } DamageEntityEvent dEvent = (DamageEntityEvent) event; // If they're endermites they hit through armor, otherwise they get a damage boost if (attacker.getType() == EntityTypes.ENDERMITE) { for (Tuple<DamageModifier, Function<? super Double, Double>> modifier : dEvent.getModifiers()) { dEvent.setDamage(modifier.getFirst(), (a) -> 0D); } dEvent.setBaseDamage(Probability.getCompoundRandom(getDamageMod(level), 3)); if (Probability.getChance(5)) { List<PotionEffect> potionEffects = defender.getOrElse(Keys.POTION_EFFECTS, new ArrayList<>()); potionEffects.add(PotionEffect.of(PotionEffectTypes.POISON, 2, 30 * 20)); defender.offer(Keys.POTION_EFFECTS, potionEffects); } } else { dEvent.setBaseDamage(dEvent.getBaseDamage() + getDamageMod(level)); } // Only apply scoring while in survival mode if (defender.get(Keys.GAME_MODE).orElse(GameModes.SURVIVAL) != GameModes.SURVIVAL) { return; } WildernessPlayerMeta meta = playerMetaMap.get(defender.getUniqueId()); if (meta != null) { meta.hit(); } } @Override public void processPlayerAttack(Player attacker, Living defender) { Task.builder().delayTicks(1).execute( () -> healthPrinter.print(MessageChannel.fixed(attacker), defender) ).submit(SkreePlugin.inst()); if (!(defender instanceof Monster) || defender instanceof Creeper) { return; } // Only apply scoring while in survival mode if (attacker.get(Keys.GAME_MODE).orElse(GameModes.SURVIVAL) != GameModes.SURVIVAL) { return; } WildernessPlayerMeta meta = playerMetaMap.get(attacker.getUniqueId()); if (meta != null) { meta.attack(); if (meta.getRatio() > 30 && meta.getFactors() > 35) { Deque<Entity> spawned = new ArrayDeque<>(); for (int i = Probability.getRandom(5); i > 0; --i) { Entity entity = attacker.getWorld().createEntity( EntityTypes.ENDERMITE, defender.getLocation().getPosition() ); entity.getWorld().spawnEntity( entity, Cause.source(SpawnCause.builder().type(SpawnTypes.PLUGIN).build()).build() ); spawned.add(entity); } IntegratedRunnable runnable = new IntegratedRunnable() { @Override public boolean run(int times) { Entity mob = spawned.poll(); if (mob.isLoaded() && mob.getWorld().equals(attacker.getWorld())) { mob.setLocation(attacker.getLocation()); } return true; } @Override public void end() { } }; TimedRunnable timedRunnable = new TimedRunnable<>(runnable, spawned.size()); timedRunnable.setTask(Task.builder().execute( timedRunnable ).delayTicks(40).intervalTicks(20).submit(SkreePlugin.inst())); } if (System.currentTimeMillis() - meta.getLastReset() >= TimeUnit.MINUTES.toMillis(5)) { meta.reset(); } } } }; } @Listener public void onPlayerCombat(DamageEntityEvent event) { Optional<Integer> optLevel = getLevel(event.getTargetEntity().getLocation()); if (!optLevel.isPresent()) { return; } createFor(event, optLevel.get()).parse(event); } @Listener public void onPlayerCombat(CollideEntityEvent.Impact event, @First Projectile projectile) { Optional<Integer> optLevel = getLevel(projectile.getLocation()); if (!optLevel.isPresent()) { return; } createFor(event, optLevel.get()).parse(event); } @Listener public void onEntityDeath(DestructEntityEvent.Death event) { Entity entity = event.getTargetEntity(); Location<World> loc = entity.getLocation(); Optional<Integer> optLevel = getLevel(loc); if (!optLevel.isPresent()) { return; } int level = optLevel.get(); if (entity instanceof Monster) { DropTable dropTable; if (entity.getLocation().getExtent().getDimension() == DimensionTypes.NETHER || entity instanceof Wither) { dropTable = netherMobDropTable; } else { dropTable = commonDropTable; } Optional<EntityDamageSource> optDamageSource = event.getCause().first(EntityDamageSource.class); if (optDamageSource.isPresent()) { Entity srcEntity; if (optDamageSource.get() instanceof IndirectEntityDamageSource) { srcEntity = ((IndirectEntityDamageSource) optDamageSource.get()).getIndirectSource(); } else { srcEntity = optDamageSource.get().getSource(); } int dropTier = level; if (srcEntity instanceof Player) { Optional<ItemStack> optHeldItem = ((Player) srcEntity).getItemInHand(HandTypes.MAIN_HAND); if (optHeldItem.isPresent()) { Optional<ItemEnchantment> optLooting = EnchantmentUtil.getHighestEnchantment( optHeldItem.get(), Enchantments.LOOTING ); if (optLooting.isPresent()) { dropTier += optLooting.get().getLevel(); } } dropTier = getDropTier(dropTier); Collection<ItemStack> drops = dropTable.getDrops( (entity instanceof Boss ? 5 : 1) * dropTier, getDropMod( dropTier, ((Monster) entity).getHealthData().maxHealth().get(), entity.getType() ) ); int times = 1; Optional<ModifierService> optService = Sponge.getServiceManager().provide(ModifierService.class); if (optService.isPresent()) { ModifierService service = optService.get(); if (service.isActive(Modifiers.DOUBLE_WILD_DROPS)) { times *= 2; } } ItemDropper dropper = new ItemDropper(loc); for (int i = 0; i < times; ++i) { dropper.dropStacks(drops, SpawnTypes.DROPPED_ITEM); } } } if (entity.getType() == EntityTypes.ENDERMITE && Probability.getChance(20)) { entity.getWorld().triggerExplosion( Explosion.builder() .location(entity.getLocation()) .shouldBreakBlocks(true) .radius(4F) .build(), Cause.source(SkreePlugin.container()).build() ); } } GRAVE_STONE.createGraveFromDeath(event); } private Set<Location<World>> markedOrePoints = new HashSet<>(); @Listener public void onBlockBreak(ChangeBlockEvent.Break event, @Named(NamedCause.SOURCE) Entity srcEnt) { List<Transaction<BlockSnapshot>> transactions = event.getTransactions(); for (Transaction<BlockSnapshot> block : transactions) { BlockSnapshot original = block.getOriginal(); Optional<Location<World>> optLoc = original.getLocation(); if (!optLoc.isPresent()) { continue; } Optional<Integer> optLevel = getLevel(optLoc.get()); if (!optLevel.isPresent()) { continue; } int level = optLevel.get(); Location<World> loc = optLoc.get(); BlockState state = original.getState(); BlockType type = state.getType(); // Prevent item dupe glitch by removing the position before subsequent breaks markedOrePoints.remove(loc); if (config.getDropAmplificationConfig().amplifies(state)) { markedOrePoints.add(loc); } if (srcEnt instanceof Player && type.equals(BlockTypes.STONE) && Probability.getChance(Math.max(12, 250 - level))) { Vector3d max = loc.getPosition().add(1, 1, 1); Vector3d min = loc.getPosition().sub(1, 1, 1); Extent world = loc.getExtent(); if (Probability.getChance(3)) { Entity entity = world.createEntity(EntityTypes.SILVERFISH, loc.getPosition().add(.5, 0, .5)); world.spawnEntity(entity, Cause.source(SpawnCause.builder().type(SpawnTypes.BLOCK_SPAWNING).build()).build()); } // Do this one tick later to guarantee no collision with transaction data Task.builder().delayTicks(1).execute(() -> { for (int x = min.getFloorX(); x <= max.getFloorX(); ++x) { for (int z = min.getFloorZ(); z <= max.getFloorZ(); ++z) { for (int y = min.getFloorY(); y <= max.getFloorY(); ++y) { if (!world.containsBlock(x, y, z)) { continue; } if (world.getBlockType(x, y, z) == BlockTypes.STONE) { world.setBlockType( x, y, z, BlockTypes.MONSTER_EGG, BlockChangeFlag.NONE, Cause.source(SkreePlugin.container()).build() ); } } } } }).submit(SkreePlugin.inst()); } } } @Listener public void onBlockPlace(ChangeBlockEvent.Place event, @Named(NamedCause.SOURCE) Player player) { for (Transaction<BlockSnapshot> block : event.getTransactions()) { Optional<Location<World>> optLoc = block.getFinal().getLocation(); if (!optLoc.isPresent() || !isApplicable(optLoc.get())) { continue; } Location<World> loc = optLoc.get(); BlockState finalState = block.getFinal().getState(); if (config.getDropAmplificationConfig().amplifies(finalState)) { // Allow creative mode players to still place blocks if (player.getGameModeData().type().get().equals(GameModes.CREATIVE)) { continue; } BlockType originalType = block.getOriginal().getState().getType(); if (ore().contains(originalType)) { continue; } try { Vector3d origin = loc.getPosition(); World world = loc.getExtent(); for (int i = 0; i < 40; ++i) { ParticleEffect effect = ParticleEffect.builder().type( ParticleTypes.MAGIC_CRITICAL_HIT ).velocity( new Vector3d( Probability.getRangedRandom(-1, 1), Probability.getRangedRandom(-.7, .7), Probability.getRangedRandom(-1, 1) ) ).quantity(1).build(); world.spawnParticles(effect, origin.add(.5, .5, .5)); } } catch (Exception ex) { player.sendMessage( /* ChatTypes.SYSTEM, */ Text.of( TextColors.RED, "You find yourself unable to place that block." ) ); } block.setValid(false); } } } private ItemStackSnapshot getPoolItemDrop(ItemStackSnapshot snapshot) { Map<String, QuantityBoundedItemStackConfig> replacementMapping = config.getDropAmplificationConfig().getItemReplacementMapping(); ItemStackConfig replacementItem = replacementMapping.get(snapshot.getType().getId()); if (replacementItem != null) { return ((ItemStack) (Object) replacementItem.toNSMStack()).createSnapshot(); } return snapshot; } @Listener public void onItemDrop(DropItemEvent.Destruct event, @Named(NamedCause.SOURCE) BlockSpawnCause spawnCause) { BlockSnapshot blockSnapshot = spawnCause.getBlockSnapshot(); Optional<Location<World>> optLocation = blockSnapshot.getLocation(); if (!optLocation.isPresent()) { return; } Location<World> loc = optLocation.get(); if (!markedOrePoints.remove(loc)) { return; } Optional<Integer> optLevel = getLevel(loc); if (!optLevel.isPresent()) { return; } List<ItemStackSnapshot> itemStacks = new ArrayList<>(); event.getEntities().forEach((entity -> { if (entity instanceof Item) { ItemStackSnapshot snapshot = ((Item) entity).item().get(); itemStacks.add(getPoolItemDrop(snapshot)); } })); addPool(loc, () -> itemStacks); } public Set<Map.Entry<Player, WildernessPlayerMeta>> getMetaInformation() { Set<Map.Entry<Player, WildernessPlayerMeta>> resultSets = new HashSet<>(); for (Map.Entry<UUID, WildernessPlayerMeta> entry : playerMetaMap.entrySet()) { Optional<Player> optPlayer = Sponge.getServer().getPlayer(entry.getKey()); if (!optPlayer.isPresent()) { continue; } Player player = optPlayer.get(); if (!player.isOnline()) { continue; } resultSets.add(new AbstractMap.SimpleEntry<>(player, entry.getValue())); } return resultSets; } public Optional<Integer> getLevel(Location<World> location) { // Not in Wilderness if (!isApplicable(location)) { return Optional.empty(); } // In Wilderness return Optional.of( Math.max( 0, Math.max( Math.abs(location.getBlockX()), Math.abs(location.getBlockZ())) / getLevelUnit(location.getExtent() ) ) + 1 ); } public int getLevelUnit(World world) { return 500; } public int getFirstPvPLevel() { return 6; } public boolean allowsPvP(int level) { return level >= getFirstPvPLevel(); } public int getDropTier(int level) { return Math.min(level, 30); } public double getDropMod(int dropTier) { return getDropMod(dropTier, null, null); } public double getDropMod(int dropTier, @Nullable Double mobHealth, @Nullable EntityType entityType) { double modifier = (dropTier * .2) + (mobHealth != null ? mobHealth * .04 : 0); if (entityType != null) { if (entityType == EntityTypes.WITHER || entityType == EntityTypes.CREEPER) { modifier *= 5; } else if (entityType == EntityTypes.SILVERFISH) { modifier *= 2; } else if (entityType == EntityTypes.ENDERMITE) { modifier *= .1; } } return modifier; } public int getHealthMod(int level) { return level > 1 ? level : 1; } public int getDamageMod(int level) { return level > 1 ? (level - 1) * 2 : 0; } public int getOreMod(int dropTier) { int modifier = (int) Math.round(Math.max(1, dropTier * 1.5)); Optional<ModifierService> optService = Sponge.getServiceManager().provide(ModifierService.class); if (optService.isPresent()) { ModifierService service = optService.get(); if (service.isActive(Modifiers.DOUBLE_WILD_ORES)) { modifier *= 2; } } return modifier; } private void addPool(Location<World> block, Supplier<Collection<ItemStackSnapshot>> itemStackSupplier) { Optional<Integer> optLevel = getLevel(block); Validate.isTrue(optLevel.isPresent()); int level = optLevel.get(); int times = Probability.getRandom(getOreMod(getDropTier(level))); WildernessDropPool dropPool = new WildernessDropPool(block, itemStackSupplier, times); TimedRunnable<IntegratedRunnable> runnable = new TimedRunnable<>(dropPool, times); Task task = Task.builder().execute(runnable).delay(1, SECONDS).interval( 1, SECONDS ).submit(SkreePlugin.inst()); runnable.setTask(task); } @Override public void run() { for (Player player : Sponge.getServer().getOnlinePlayers()) { int currentLevel = getLevel(player.getLocation()).orElse(-1); WildernessPlayerMeta meta = playerMetaMap.getOrDefault(player.getUniqueId(), new WildernessPlayerMeta()); int lastLevel = meta.getLevel(); // Always set the level so as to mark the player meta as relevant // if it is -1 no time stamp update shall be performed meta.setLevel(currentLevel); // Display a title change, unless the current level is -1 (outside of the Wilderness) if (currentLevel != -1 && currentLevel != lastLevel) { TextColor color = (allowsPvP(currentLevel) ? TextColors.RED : TextColors.WHITE); player.sendTitle( Title.builder() .title(Text.of(color, "Wilderness Level")) .subtitle(Text.of(color, currentLevel)) .fadeIn(20) .fadeOut(20) .build() ); playerMetaMap.putIfAbsent(player.getUniqueId(), meta); } } playerMetaMap.entrySet().removeIf(entry -> System.currentTimeMillis() - entry.getValue().getLastChange() >= TimeUnit.MINUTES.toMillis(5) ); } }
package de.bayern.lfstad.test.contionuousIntegrationBeispiel; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * Erlaubt es eine Zahl in ihre Prrim-Faktoren zu zerlegen. */ public class PrimeNumbers { private Deque<Integer> primeNumbers = new LinkedList<>(Arrays.asList(2)); public List<Integer> split(final int value) { if(value == 0) { throw new RuntimeException("0 kann nicht zerlegt werden."); } if(value == 1) { return Arrays.asList(1); } final List<Integer> result = new LinkedList<>(); int tempValue; if(value >= 0) { tempValue = value; } else { result.add(Integer.valueOf(-1)); tempValue = -1 * value; } OUTER_LOOP: while(tempValue != 1) { for(final Integer primeNumber : primeNumbers) { if(tempValue % primeNumber.intValue() == 0) { result.add(primeNumber); tempValue = tempValue / primeNumber.intValue(); continue OUTER_LOOP; } } primeNumbers.addLast(createNextPrimeNumber()); } return result; } private int createNextPrimeNumber() { int canidate = primeNumbers.pollLast().intValue(); do { canidate = canidate + 1; if(isNextPrime(canidate)) { return canidate; } } while(canidate <= Integer.MAX_VALUE); throw new RuntimeException("Es konnte kein weiterer Primfaktor bestimmt werden."); } private boolean isNextPrime(final int value) { for(final Integer primeNumber : primeNumbers) { if(value % primeNumber == 0) { return false; } } return true; } }
package de.craften.plugins.rpgplus.components.entitymanager; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import de.craften.plugins.rpgplus.util.components.PluginComponentBase; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import java.util.*; /** * A manager for entities. */ public class EntityManager extends PluginComponentBase implements Listener { private Map<UUID, ManagedEntity> entities; private Multimap<UUID, Player> nearbyPlayers; protected void onActivated() { entities = new HashMap<>(); nearbyPlayers = MultimapBuilder.hashKeys().arrayListValues().build(); runTaskTimer(new Runnable() { @Override public void run() { for (ManagedEntity entity : new ArrayList<ManagedEntity>(entities.values())) { switch (entity.getMovementType()) { case FROZEN: entity.getEntity().teleport(entity.getLocalLocation()); entity.getEntity().setVelocity(new Vector(0, 0, 0)); break; case LOCAL: Location currentLocation = entity.getEntity().getLocation(); Location local = entity.getLocalLocation(); currentLocation.setX(local.getX()); currentLocation.setY(local.getY()); currentLocation.setZ(local.getZ()); entity.getEntity().teleport(currentLocation); entity.getEntity().setVelocity(new Vector(0, 0, 0)); break; case MOVING: entity.getEntity().teleport(entity.getLocalLocation()); break; } } } }, 0, 1); } @EventHandler public void onEntityDamage(EntityDamageEvent event) { ManagedEntity entity = getEntity(event.getEntity().getUniqueId()); if (entity != null && !entity.isTakingDamage()) { event.setCancelled(true); } } @EventHandler public void onEntityDeath(EntityDeathEvent event) { ManagedEntity entity = getEntity(event.getEntity()); if(entity != null){ unregisterEntity(entity); if (entity instanceof CustomDrops) { Player killer = event.getEntity().getKiller(); if (killer != null) { event.setDroppedExp(((CustomDrops) entity).getExp((Player) killer)); Location location = event.getEntity().getLocation(); World world = location.getWorld(); for (ItemStack items : ((CustomDrops) entity).getDrops((Player) killer)) { world.dropItemNaturally(location, items); } } } } } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { for (ManagedEntity entity : entities.values()) { if (entity instanceof NearbyPlayerAware) { handleNearbyPlayers(entity, event); } } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { for (ManagedEntity entity : entities.values()) { //remove all references to this player nearbyPlayers.remove(entity.getEntity().getUniqueId(), event.getPlayer()); } } @EventHandler public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { ManagedEntity entity = getEntity(event.getRightClicked()); if(entity != null){ entity.onPlayerInteract(event); } } private void handleNearbyPlayers(ManagedEntity entity, PlayerMoveEvent event) { assert entity instanceof NearbyPlayerAware; NearbyPlayerAware npaEntity = (NearbyPlayerAware) entity; Location playerLocation = event.getTo(); Location entityLocation = entity.getEntity().getLocation(); if (playerLocation.getWorld().equals(entityLocation.getWorld())) { double distanceSquared = playerLocation.distanceSquared(entityLocation); double radiusSquared = npaEntity.getPlayerAwareRadius() * npaEntity.getPlayerAwareRadius(); boolean justEntered = !nearbyPlayers.containsKey(entity.getEntity().getUniqueId()); if (distanceSquared <= radiusSquared) { npaEntity.onPlayerNearby(event.getPlayer(), justEntered, distanceSquared); nearbyPlayers.put(entity.getEntity().getUniqueId(), event.getPlayer()); } else { nearbyPlayers.remove(entity.getEntity().getUniqueId(), event.getPlayer()); if (!justEntered) { npaEntity.onPlayerGone(event.getPlayer()); } } } } /** * Register the given entity. * * @param entity entity to register */ public void registerEntity(ManagedEntity entity) { entities.put(entity.getEntity().getUniqueId(), entity); } /** * Unregister the given entity. * * @param entity entity to unregister */ public void unregisterEntity(ManagedEntity entity) { entities.remove(entity.getEntity().getUniqueId()); nearbyPlayers.removeAll(entity.getEntity().getUniqueId()); } /** * Unregister the given entity. * * @param entity entity to unregister */ public void unregisterEntity(Entity entity) { entities.remove(entity.getUniqueId()); } /** * Get a managed entity by its ID. * * @param id ID of the entity * @return managed entity with the given ID or null if no such entity is registered */ public ManagedEntity getEntity(UUID id) { return entities.get(id); } /** * Get all entities. * * @return all entities */ public Collection<ManagedEntity> getEntities() { return entities.values(); } /** * Get a managed entity of an unmanaged entity. * * @param entity unmanaged entity * @return managed entity of the given entity or null if no such entity is registered */ @SuppressWarnings("unchecked") public <T extends Entity> ManagedEntity<T> getEntity(T entity) { return entities.get(entity.getUniqueId()); } }
package eu.yaga.stockanalyzer.service.impl; import eu.yaga.stockanalyzer.model.FundamentalData; import eu.yaga.stockanalyzer.model.StockType; import eu.yaga.stockanalyzer.service.HistoricalExchangeRateService; import eu.yaga.stockanalyzer.service.StockRatingBusinessService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Implementation of StockRatingBusinessService */ public class StockRatingBusinessServiceImpl implements StockRatingBusinessService { private static final Logger log = LoggerFactory.getLogger(StockRatingBusinessServiceImpl.class); private HistoricalExchangeRateService historicalExchangeRateService; public StockRatingBusinessServiceImpl(HistoricalExchangeRateService historicalExchangeRateService) { this.historicalExchangeRateService = historicalExchangeRateService; } /** * rate a stock * * @param fd the stock * @return the FundamentalData with ratings */ @Override public FundamentalData rate(FundamentalData fd) { fd = rateRoe(fd); fd = rateEbit(fd); fd = rateEquityRatio(fd); fd = ratePer5years(fd); fd = ratePerCurrent(fd); fd = rateAnalystEstimation(fd); fd = rateQuarterlyFigures(fd); fd = rateRateProgress6month(fd); fd = rateRateProgress1year(fd); fd = rateRateMomentum(fd); fd = rateReversal3Month(fd); fd = rateProfitGrowth(fd); fd = rateEarningsRevision(fd); fd = rateOverall(fd); return fd; } private FundamentalData rateEarningsRevision(FundamentalData fd) { log.info("Rating earnings revision..."); double earningsRevision = fd.getEarningsRevision(); if (earningsRevision > 5) { fd.setEarningsRevisionRating(1); } else if (earningsRevision < -5) { fd.setEarningsRevisionRating(-1); } else { fd.setEarningsRevisionRating(0); } return fd; } private FundamentalData rateProfitGrowth(FundamentalData fd) { log.info("Rating profit growth..."); double epsCurrentYear = fd.getEpsCurrentYear(); double epsNextYear = fd.getEpsNextYear(); double profitGrowth = (epsNextYear - epsCurrentYear) / epsCurrentYear * 100; fd.setProfitGrowth(profitGrowth); if (profitGrowth > 5) { fd.setProfitGrowthRating(1); } else if (profitGrowth < -5) { fd.setProfitGrowthRating(-1); } else { fd.setProfitGrowthRating(0); } return fd; } private FundamentalData rateReversal3Month(FundamentalData fd) { log.info("Rating 3 month reversal..."); StockType stockType = fd.getStockType(); if (stockType.equals(StockType.MID_CAP) || stockType.equals(StockType.SMALL_CAP)) { fd.setReversal3Month(new ArrayList<>(Arrays.asList(0.0, 0.0, 0.0))); fd.setReversal3MonthRating(0); } else { List<Double> reversal3Month = historicalExchangeRateService.getReversal3Month(fd); fd.setReversal3Month(reversal3Month); int score = 0; if (reversal3Month != null) { for (double reversal : reversal3Month) { if (reversal > 0) { score++; } else if (reversal < 0) { score } } } switch (score) { case 3: fd.setReversal3MonthRating(-1); break; case -3: fd.setReversal3MonthRating(1); break; default: fd.setReversal3MonthRating(0); } } return fd; } private FundamentalData rateRateMomentum(FundamentalData fd) { log.info("Rating rate momentum..."); int rateProgress6monthRating = fd.getRateProgress6monthRating(); int rateProgress1yearRating = fd.getRateProgress1yearRating(); if (rateProgress6monthRating == 1 && rateProgress1yearRating <= 0) { fd.setRateMomentumRating(1); } else if (rateProgress6monthRating == -1 && rateProgress1yearRating >= 0) { fd.setRateMomentumRating(-1); } else { fd.setRateMomentumRating(0); } return fd; } private FundamentalData rateRateProgress1year(FundamentalData fd) { log.info("Rating rate progress 1 year..."); double rateProgress1year = historicalExchangeRateService.getRateProgress1year(fd); fd.setRateProgress1year(rateProgress1year); if (rateProgress1year > 5) { fd.setRateProgress1yearRating(1); } else if (rateProgress1year < -5) { fd.setRateProgress1yearRating(-1); } else { fd.setRateProgress1yearRating(0); } return fd; } private FundamentalData rateRateProgress6month(FundamentalData fd) { log.info("Rating rate progress 6 month..."); double rateProgress6month = historicalExchangeRateService.getRateProgress6month(fd); fd.setRateProgress6month(rateProgress6month); if (rateProgress6month > 5) { fd.setRateProgress6monthRating(1); } else if (rateProgress6month < -5) { fd.setRateProgress6monthRating(-1); } else { fd.setRateProgress6monthRating(0); } return fd; } private FundamentalData rateQuarterlyFigures(FundamentalData fd) { log.info("Rating quarterly figures..."); double reactionToQuarterlyFigures = historicalExchangeRateService.getReactionToQuarterlyFigures(fd); if (reactionToQuarterlyFigures >= 1) { fd.setLastQuarterlyFiguresRating(1); } else if (reactionToQuarterlyFigures <= -1) { fd.setLastQuarterlyFiguresRating(-1); } else { fd.setLastQuarterlyFiguresRating(0); } return fd; } private FundamentalData rateAnalystEstimation(FundamentalData fd) { log.info("Rating analyst estimation..."); double analystEstimation = fd.getAnalystEstimation(); StockType stockType = fd.getStockType(); int analystEstimationCount = fd.getAnalystEstimationCount(); if (stockType == StockType.SMALL_CAP && analystEstimationCount > 0 && analystEstimationCount < 5) { if (analystEstimation >= 2.5) { fd.setAnalystEstimationRating(-1); } else if (analystEstimation <= 1.5) { fd.setAnalystEstimationRating(1); } else { fd.setAnalystEstimationRating(0); } } else { if (analystEstimation >= 2.5) { fd.setAnalystEstimationRating(1); } else if (analystEstimation <= 1.5) { fd.setAnalystEstimationRating(-1); } else { fd.setAnalystEstimationRating(0); } } return fd; } private FundamentalData rateOverall(FundamentalData fd) { log.info("Creating overall rating..."); int overallRating = fd.getRoeRating() + fd.getEbitRating() + fd.getEquityRatioRating() + fd.getPer5yearsRating() + fd.getPerCurrentRating() + fd.getAnalystEstimationRating() + fd.getLastQuarterlyFiguresRating() + fd.getRateProgress6monthRating() + fd.getRateProgress1yearRating() + fd.getRateMomentumRating() + fd.getReversal3MonthRating() + fd.getProfitGrowthRating() + fd.getEarningsRevisionRating(); fd.setOverallRating(overallRating); return fd; } private FundamentalData ratePerCurrent(FundamentalData fd) { log.info("Rating current per..."); double perCurrent = fd.getPerCurrent(); if (perCurrent < 12) { fd.setPerCurrentRating(1); } else if (perCurrent > 16) { fd.setPerCurrentRating(-1); } else { fd.setPerCurrentRating(0); } return fd; } private FundamentalData ratePer5years(FundamentalData fd) { log.info("Rating per 5 years..."); double per5years = fd.getPer5years(); if (per5years < 12) { fd.setPer5yearsRating(1); } else if (per5years > 16) { fd.setPer5yearsRating(-1); } else { fd.setPer5yearsRating(0); } return fd; } private FundamentalData rateEquityRatio(FundamentalData fd) { log.info("Rating equity ratio..."); double equityRatio = fd.getEquityRatio(); if (fd.getStockType() == StockType.LARGE_FINANCE) { if (equityRatio > 10) { fd.setEquityRatioRating(1); } else if (equityRatio < 5) { fd.setEquityRatioRating(-1); } else { fd.setEquityRatioRating(0); } } else { if (equityRatio > 25) { fd.setEquityRatioRating(1); } else if (equityRatio < 15) { fd.setEquityRatioRating(-1); } else { fd.setEquityRatioRating(0); } } return fd; } private FundamentalData rateEbit(FundamentalData fd) { log.info("Rating ebit..."); if (fd.getStockType() == StockType.LARGE_FINANCE) { fd.setEbitRating(0); } else { double ebit = fd.getEbit(); if (ebit > 12) { fd.setEbitRating(1); } else if (ebit < 6) { fd.setEbitRating(-1); } else { fd.setEbitRating(0); } } return fd; } private FundamentalData rateRoe(FundamentalData fd) { log.info("Rating roe..."); double roe = fd.getRoe(); if (roe > 20) { fd.setRoeRating(1); } else if (roe < 10) { fd.setRoeRating(-1); } else { fd.setRoeRating(0); } return fd; } }
package io.github.sporklibrary.binders.component; import io.github.sporklibrary.Spork; import io.github.sporklibrary.annotations.BindComponent; import io.github.sporklibrary.annotations.Component; import io.github.sporklibrary.binders.AnnotatedField; import io.github.sporklibrary.exceptions.BindException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; /** * Manages Component instances for types that are annotated with the Component annotation. */ class ComponentInstanceManager { private final Map<Class<?>, Object> mSingletonInstances = new HashMap<>(); /** * Gets an instance of a component within its scope. * The scope is either singleton or default. * If the scope is unsupported, default is assumed. * @param annotatedField the annotated field to get an instance for * @param parent the parent object that holds the field * @return the component instance */ public Object getInstance(AnnotatedField<BindComponent> annotatedField, Object parent) { Class<?> field_target_class = getTargetClass(annotatedField); if (!annotatedField.getField().getType().isAssignableFrom(field_target_class)) { throw new BindException(BindComponent.class, parent.getClass(), annotatedField.getField(), "incompatible type"); } Component component_annotation = field_target_class.getAnnotation(Component.class); if (component_annotation == null) { throw new BindException(BindComponent.class, parent.getClass(), annotatedField.getField(), "no Component annotation found at target class"); } switch (component_annotation.scope()) { case SINGLETON: Object instance = mSingletonInstances.get(field_target_class); return (instance != null) ? instance : createSingletonInstance(field_target_class); case DEFAULT: default: return create(field_target_class); } } private Class<?> getTargetClass(AnnotatedField<BindComponent> annotatedField) { Class<?> override_class = annotatedField.getAnnotation().implementation(); if (override_class == BindComponent.Default.class) { return annotatedField.getField().getType(); } else // override class is never null per annotation design { return override_class; } } private Object create(Class<?> classObject) { try { Constructor<?> constructor = classObject.getConstructor(); if (constructor.isAccessible()) { Object instance = constructor.newInstance(); Spork.bind(instance); return instance; } else { constructor.setAccessible(true); Object instance = constructor.newInstance(); Spork.bind(instance); constructor.setAccessible(false); return instance; } } catch (NoSuchMethodException e) { throw new BindException(Component.class, classObject, "no default constructor found for " + classObject.getName() + " (must have a constructor with zero arguments)"); } catch (InstantiationException e) { throw new BindException(Component.class, classObject, "failed to create instance of " + classObject.getName(), e); } catch (IllegalAccessException e) { throw new BindException(Component.class, classObject, "failed to create instance due to access restrictions for " + classObject.getName(), e); } catch (InvocationTargetException e) { throw new BindException(Component.class, classObject, "constructor threw exception for " + classObject.getName(), e); } } private synchronized Object createSingletonInstance(Class<?> classObject) { Object instance = create(classObject); mSingletonInstances.put(classObject, instance); return instance; } }
package net.floodlightcontroller.nfvtest.nfvcorestructure; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.HashSet; import net.floodlightcontroller.nfvtest.nfvutils.Pair; import net.floodlightcontroller.nfvtest.nfvutils.GlobalConfig.*; public class NFVServiceChain { public final ServiceChainConfig serviceChainConfig; private final List<Map<String, NFVNode>> nfvNodeMaps; private final List<String> baseNodeIpList; private final int[] rrStore; private final Map<String, NFVNode> entryMacNodeMap; private final Map<String, NFVNode> exitMacNodeMap; private final Map<String, NFVNode> managementIpNodeMap; private final boolean[] scaleIndicators; public final long[] scaleDownCounter; public final List<Map<String, Integer>> scaleDownList; NFVServiceChain(ServiceChainConfig serviceChainConfig){ this.serviceChainConfig = serviceChainConfig; this.nfvNodeMaps = new ArrayList<Map<String, NFVNode>>(); this.rrStore = new int[this.serviceChainConfig.stages.size()]; this.baseNodeIpList = new ArrayList<String>(this.serviceChainConfig.stages.size()); for(int i=0; i<this.serviceChainConfig.stages.size(); i++){ this.baseNodeIpList.add("fakeIp"); } this.managementIpNodeMap = new HashMap<String, NFVNode>(); if(serviceChainConfig.nVmInterface == 3){ this.entryMacNodeMap = new HashMap<String, NFVNode>(); this.exitMacNodeMap = new HashMap<String, NFVNode>(); } else{ this.entryMacNodeMap = null; this.exitMacNodeMap = null; } for(int i=0; i<this.serviceChainConfig.stages.size(); i++){ Map<String, NFVNode> nodeMap = new HashMap<String, NFVNode>(); this.nfvNodeMaps.add(nodeMap); this.rrStore[i] = 0; } scaleIndicators = new boolean[this.serviceChainConfig.stages.size()]; for(int i=0; i<scaleIndicators.length; i++){ scaleIndicators[i] = false; } scaleDownList = new ArrayList<Map<String, Integer>>(); scaleDownCounter = new long[serviceChainConfig.stages.size()]; for(int i=0; i<this.serviceChainConfig.stages.size(); i++){ Map<String, Integer> nodeMap = new HashMap<String, Integer>(); this.scaleDownList.add(nodeMap); scaleDownCounter[i] = -1; } } public synchronized void addNodeToChain(NFVNode node){ if(node.vmInstance.serviceChainConfig.name == serviceChainConfig.name){ Map<String, NFVNode> stageMap = this.nfvNodeMaps.get(node.vmInstance.stageIndex); if(stageMap.size() == 0){ stageMap.put(node.getManagementIp(), node); this.managementIpNodeMap.put(node.getManagementIp(), node); this.baseNodeIpList.set(node.vmInstance.stageIndex, node.getManagementIp()); if(this.serviceChainConfig.nVmInterface == 3){ this.entryMacNodeMap.put(node.vmInstance.macList.get(0), node); this.exitMacNodeMap.put(node.vmInstance.macList.get(1), node); } } else{ if(!stageMap.containsKey(node.getManagementIp())){ stageMap.put(node.getManagementIp(), node); this.managementIpNodeMap.put(node.getManagementIp(), node); if(this.serviceChainConfig.nVmInterface == 3){ this.entryMacNodeMap.put(node.vmInstance.macList.get(0), node); this.exitMacNodeMap.put(node.vmInstance.macList.get(1), node); } } } } } public synchronized void deleteNodeFromChain(NFVNode node){ if(node.vmInstance.serviceChainConfig.name == serviceChainConfig.name){ Map<String, NFVNode> stageMap = this.nfvNodeMaps.get(node.vmInstance.stageIndex); if( (stageMap.containsKey(node.getManagementIp())) && (node.getManagementIp()!=this.baseNodeIpList.get(node.vmInstance.stageIndex)) ){ stageMap.remove(node.getManagementIp()); this.managementIpNodeMap.remove(node.getManagementIp()); if(this.serviceChainConfig.nVmInterface == 3){ this.entryMacNodeMap.remove(node.vmInstance.macList.get(0)); this.exitMacNodeMap.remove(node.vmInstance.macList.get(1)); } } } } public synchronized List<NFVNode> forwardRoute(){ //a simple round rubin. List<NFVNode> routeList = new ArrayList<NFVNode>(); for(int i=0; i<this.nfvNodeMaps.size(); i++){ Map<String, Integer> stageScaleDownMap = this.scaleDownList.get(i); Map<String, NFVNode> stageMap = this.nfvNodeMaps.get(i); HashSet<String> nonScaleDownSet = new HashSet<String>(stageMap.keySet()); nonScaleDownSet.removeAll(stageScaleDownMap.keySet()); String[] nonScaleDownArray = nonScaleDownSet.toArray(new String[nonScaleDownSet.size()]); String managementIp = null; for(int j=0; j<nonScaleDownArray.length; j++){ String tmp = nonScaleDownArray[j]; if(stageMap.get(tmp).getState() != NFVNode.OVERLOAD){ managementIp = tmp; break; } } if(managementIp!=null){ int smallestFlowNum = stageMap.get(managementIp).getActiveFlows(); for(int j=0; j<nonScaleDownArray.length; j++){ String tmp = nonScaleDownArray[j]; int flowNum = stageMap.get(tmp).getActiveFlows(); int state = stageMap.get(tmp).getState(); if( (flowNum<smallestFlowNum) && (state!=NFVNode.OVERLOAD) ){ smallestFlowNum = flowNum; managementIp = tmp; } } routeList.add(stageMap.get(managementIp)); } else{ if(stageScaleDownMap.size()>0){ String[] scaleDownArray = stageScaleDownMap.keySet() .toArray(new String[stageScaleDownMap.size()]); managementIp = scaleDownArray[0]; int smallestFlowNum = stageMap.get(managementIp).getActiveFlows(); for(int j=0; j<scaleDownArray.length; j++){ String tmp = scaleDownArray[j]; int flowNum = stageMap.get(tmp).getActiveFlows(); if(flowNum<smallestFlowNum){ smallestFlowNum = flowNum; managementIp = tmp; } } routeList.add(stageMap.get(managementIp)); } else{ String[] nodeArray = stageMap.keySet() .toArray(new String[stageScaleDownMap.size()]); managementIp = nodeArray[0]; int smallestFlowNum = stageMap.get(managementIp).getActiveFlows(); for(int j=0; j<nodeArray.length; j++){ String tmp = nodeArray[j]; int flowNum = stageMap.get(tmp).getActiveFlows(); if(flowNum<smallestFlowNum){ smallestFlowNum = flowNum; managementIp = tmp; } } routeList.add(stageMap.get(managementIp)); } } } return routeList; } public synchronized String getEntryDpid(){ Map<String, NFVNode> nodeMap = this.nfvNodeMaps.get(0); NFVNode baseNode = nodeMap.get(this.baseNodeIpList.get(0)); return baseNode.vmInstance.bridgeDpidList.get(0); } public synchronized String getDpidForMac(String mac){ if(this.serviceChainConfig.nVmInterface == 3){ if(this.entryMacNodeMap.containsKey(mac)){ return this.entryMacNodeMap.get(mac).vmInstance.bridgeDpidList.get(0); } else if(this.exitMacNodeMap.containsKey(mac)){ return this.exitMacNodeMap.get(mac).vmInstance.bridgeDpidList.get(1); } else { return null; } } else{ return null; } } public synchronized boolean macOnRearSwitch(String mac){ boolean returnVal = false; if(this.entryMacNodeMap.containsKey(mac)){ returnVal = false; } else if(this.exitMacNodeMap.containsKey(mac)){ NFVNode node = this.exitMacNodeMap.get(mac); if(node.vmInstance.stageIndex == (node.vmInstance.serviceChainConfig.stages.size()-1)){ returnVal = true; } else{ returnVal = false; } } return returnVal; } public synchronized void updateDataNodeStat(String managementIp, ArrayList<String> statList){ if(this.managementIpNodeMap.containsKey(managementIp)){ NFVNode node = this.managementIpNodeMap.get(managementIp); String cpu = statList.get(2); String[] cpuStatArray = cpu.trim().split("\\s+"); float sum = 0; for(int i=0; i<cpuStatArray.length; i++){ sum += Float.parseFloat(cpuStatArray[i]); } float cpuUsage = (sum-Float.parseFloat(cpuStatArray[3]))*100/sum; String mem = statList.get(4); String[] memStatArray = mem.trim().split("\\s+"); float memUsage = Float.parseFloat(memStatArray[1])*100/Float.parseFloat(memStatArray[0]); memUsage = 100-memUsage; String interrupt = statList.get(6); String[] intStatArray = interrupt.trim().split("\\s+"); int eth0RecvInt = Integer.parseInt(intStatArray[0]); int eth0SendInt = Integer.parseInt(intStatArray[1]); int eth1RecvInt = Integer.parseInt(intStatArray[2]); int eth1SendInt = Integer.parseInt(intStatArray[3]); String eth0 = statList.get(8); String[] eth0StatArray = eth0.trim().split("\\s+"); long eth0RecvPkt = Long.parseLong(eth0StatArray[1]); long eth0SendPkt = Long.parseLong(eth0StatArray[9]); String eth1 = statList.get(10); String[] eth1StatArray = eth1.trim().split("\\s+"); long eth1RecvPkt = Long.parseLong(eth1StatArray[1]); long eth1SendPkt = Long.parseLong(eth1StatArray[9]); node.updateNodeProperty(new Float(cpuUsage), new Float(memUsage), new Integer(eth0RecvInt), new Long(eth0RecvPkt), new Integer(eth0SendInt), new Long(eth0SendPkt), new Integer(eth1RecvInt), new Long(eth1RecvPkt), new Integer(eth1SendInt), new Long(eth1SendPkt)); } } public synchronized void updateControlNodeStat(String managementIp, ArrayList<String> statList){ if(this.managementIpNodeMap.containsKey(managementIp)){ NFVNode node = this.managementIpNodeMap.get(managementIp); if(statList.get(1).equals("cpu")){ String cpu = statList.get(2); String[] cpuStatArray = cpu.trim().split("\\s+"); float sum = 0; for(int i=0; i<cpuStatArray.length; i++){ sum += Float.parseFloat(cpuStatArray[i]); } float cpuUsage = (sum-Float.parseFloat(cpuStatArray[3]))*100/sum; String mem = statList.get(4); String[] memStatArray = mem.trim().split("\\s+"); float memUsage = Float.parseFloat(memStatArray[1])*100/Float.parseFloat(memStatArray[0]); memUsage = 100-memUsage; String interrupt = statList.get(6); String[] intStatArray = interrupt.trim().split("\\s+"); int eth0RecvInt = Integer.parseInt(intStatArray[0]); int eth0SendInt = Integer.parseInt(intStatArray[1]); String eth0 = statList.get(8); String[] eth0StatArray = eth0.trim().split("\\s+"); long eth0RecvPkt = Long.parseLong(eth0StatArray[1]); long eth0SendPkt = Long.parseLong(eth0StatArray[9]); node.updateNodeProperty(new Float(cpuUsage), new Float(memUsage), new Integer(eth0RecvInt), new Long(eth0RecvPkt), new Integer(eth0SendInt), new Long(eth0SendPkt), new Integer(1), new Long(0), new Integer(0), new Long(0)); } else if(statList.get(1).equals("transaction_counter")){ int goodTran = Integer.parseInt(statList.get(3)); int badTran = Integer.parseInt(statList.get(4)); int srdSt250ms = Integer.parseInt(statList.get(6)); int srdLt250ms = Integer.parseInt(statList.get(5))+ Integer.parseInt(statList.get(7)); node.updateTranProperty(new Integer(goodTran), new Integer(badTran), new Integer(srdSt250ms), new Integer(srdLt250ms)); } } } public synchronized boolean hasNode(String managementIp){ if(this.managementIpNodeMap.containsKey(managementIp)){ return true; } else{ return false; } } public synchronized Map<String, NFVNode> getManagementIpNodeMap(){ return this.managementIpNodeMap; } public synchronized NFVNode getNode(String managementIp){ return this.managementIpNodeMap.get(managementIp); } public synchronized Map<String, NFVNode> getStageMap(int stage){ return this.nfvNodeMaps.get(stage); } public synchronized void setScaleIndicator(int stage, boolean val){ this.scaleIndicators[stage] = val; } public synchronized int getNodeWithLeastFlows(int stageIndex, ArrayList<Pair<String, Integer>> flowNumArray){ String baseNodeIp = this.baseNodeIpList.get(stageIndex); if(flowNumArray.size() == 0){ return -1; } if((flowNumArray.size() == 1)&&(flowNumArray.get(0).first.equals(baseNodeIp))){ return -1; } int smallestFlowNum = 0; int smallestIndex = 0; for(int i=0; i<flowNumArray.size(); i++){ String managementIp = flowNumArray.get(i).first; int flowNum = flowNumArray.get(i).second.intValue(); if(!managementIp.equals(baseNodeIp)){ smallestFlowNum = flowNum; smallestIndex = i; break; } } for(int i=0; i<flowNumArray.size(); i++){ String managementIp = flowNumArray.get(i).first; int flowNum = flowNumArray.get(i).second.intValue(); if( (flowNum<smallestFlowNum) && (!managementIp.equals(baseNodeIp)) ){ smallestFlowNum = flowNum; smallestIndex = i; } } return smallestIndex; } public synchronized ArrayList<Pair<String, Integer>> getFlowNumArray(int stageIndex){ Map<String,NFVNode> nodeMap = this.nfvNodeMaps.get(stageIndex); ArrayList<Pair<String, Integer>> flowNumArray = new ArrayList<Pair<String, Integer>>(); for(String ip : nodeMap.keySet()){ NFVNode node = nodeMap.get(ip); flowNumArray.add(new Pair<String, Integer>(node.getManagementIp(), new Integer(node.getActiveFlows()))); } return flowNumArray; } public synchronized boolean getScaleIndicator(int stage){ return this.scaleIndicators[stage]; } }
package cz.vutbr.fit.iha.menu; import java.util.List; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Bitmap; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Toast; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import cz.vutbr.fit.iha.Constants; import cz.vutbr.fit.iha.R; import cz.vutbr.fit.iha.activity.AdapterUsersActivity; import cz.vutbr.fit.iha.activity.AddAdapterActivity; import cz.vutbr.fit.iha.activity.MainActivity; import cz.vutbr.fit.iha.activity.SettingsMainActivity; import cz.vutbr.fit.iha.activity.dialog.InfoDialogFragment; import cz.vutbr.fit.iha.activity.menuItem.AdapterMenuItem; import cz.vutbr.fit.iha.activity.menuItem.CustomViewMenuItem; import cz.vutbr.fit.iha.activity.menuItem.EmptyMenuItem; import cz.vutbr.fit.iha.activity.menuItem.GroupImageMenuItem; import cz.vutbr.fit.iha.activity.menuItem.LocationMenuItem; import cz.vutbr.fit.iha.activity.menuItem.MenuItem; import cz.vutbr.fit.iha.activity.menuItem.ProfileMenuItem; import cz.vutbr.fit.iha.activity.menuItem.SeparatorMenuItem; import cz.vutbr.fit.iha.activity.menuItem.SettingMenuItem; import cz.vutbr.fit.iha.adapter.Adapter; import cz.vutbr.fit.iha.adapter.location.Location; import cz.vutbr.fit.iha.arrayadapter.MenuListAdapter; import cz.vutbr.fit.iha.asynctask.CallbackTask.CallbackTaskListener; import cz.vutbr.fit.iha.asynctask.SwitchAdapterTask; import cz.vutbr.fit.iha.asynctask.UnregisterAdapterTask; import cz.vutbr.fit.iha.controller.Controller; import cz.vutbr.fit.iha.household.ActualUser; import cz.vutbr.fit.iha.persistence.Persistence; import cz.vutbr.fit.iha.thread.ToastMessageThread; import cz.vutbr.fit.iha.util.Log; public class NavDrawerMenu { private static final String TAG = "NavDrawerMenu"; private final static String TAG_INFO = "tag_info"; private MainActivity mActivity; private Controller mController; private DrawerLayout mDrawerLayout; private StickyListHeadersListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private String mDrawerTitle = "IHA"; private String mActiveLocationId; private String mActiveCustomViewId; private String mActiveAdapterId; private String mAdaterIdUnregist; private boolean mIsDrawerOpen; private boolean backPressed = false; private SwitchAdapterTask mSwitchAdapterTask; private UnregisterAdapterTask mUnregisterAdapterTask; private MenuListAdapter mMenuAdapter; private ActionMode mMode; private MenuItem mSelectedMenuItem; public NavDrawerMenu(MainActivity activity) { // Set activity mActivity = activity; backPressed = mActivity.getBackPressed(); // Get controller mController = Controller.getInstance(mActivity); // Get GUI element for menu getGUIElements(); // Set all of listener for (listview) menu items settingsMenu(); } private void getGUIElements() { // Locate DrawerLayout in activity_location_screen.xml mDrawerLayout = (DrawerLayout) mActivity.findViewById(R.id.drawer_layout); // Locate ListView in activity_location_screen.xml mDrawerList = (StickyListHeadersListView) mActivity.findViewById(R.id.listview_drawer); } private void settingsMenu() { // Set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); mDrawerLayout.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { backPressed = ((MainActivity) mActivity).getBackPressed(); Log.d(TAG, "BackPressed = " + String.valueOf(backPressed)); if (mDrawerLayout == null) { return false; } if (mDrawerLayout.isDrawerOpen(mDrawerList) && !backPressed) { firstTapBack(); return true; } else if (mDrawerLayout.isDrawerOpen(mDrawerList) && backPressed) { secondTapBack(); return true; } } return false; } }); // Capture listview menu item click mDrawerList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mSelectedMenuItem = (MenuItem) mMenuAdapter.getItem(position); switch (mSelectedMenuItem.getType()) { case ADAPTER: // if it is not chosen, switch to selected adapter if (!mController.getActiveAdapter().getId().equals(mSelectedMenuItem.getId())) { doSwitchAdapter(mSelectedMenuItem.getId()); } break; case CUSTOM_VIEW: // TODO: otevrit custom view, jeste nedelame s customView, takze pozdeji // TEMP mActiveLocationId = null; mActiveCustomViewId = mSelectedMenuItem.getId(); changeCustomView(true); redrawMenu(); break; case SETTING: if (mSelectedMenuItem.getId().equals(cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_ABOUT)) { InfoDialogFragment dialog = new InfoDialogFragment(); dialog.show(mActivity.getSupportFragmentManager(), TAG_INFO); } else if (mSelectedMenuItem.getId().equals(cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_SETTINGS)) { Intent intent = new Intent(mActivity, SettingsMainActivity.class); mActivity.startActivity(intent); } break; case LOCATION: // Get the title followed by the position Adapter adapter = mController.getActiveAdapter(); if (adapter != null) { mActiveCustomViewId = null; changeLocation(mController.getLocation(adapter.getId(), mSelectedMenuItem.getId()), true); redrawMenu(); } break; default: break; } } }); mDrawerList.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if(mMode != null) { // Action Mode is active and I want change mSelectedMenuItem.setNotSelected(); mMode = null; } Log.d(TAG, "Item Long press"); mSelectedMenuItem = (MenuItem) mMenuAdapter.getItem(position); switch (mSelectedMenuItem.getType()) { case LOCATION: if(!mSelectedMenuItem.getId().equals(Constants.GUI_MENU_ALL_SENSOR_ID)) mMode = mActivity.startActionMode(new ActionModeLocations()); break; case ADAPTER: Log.i(TAG, "Long press - adapter"); //mAdaterIdUnregist = item.getId(); mMode = mActivity.startActionMode(new ActionModeAdapters()); mSelectedMenuItem.setIsSelected(); break; default: // do nothing break; } return true; } }); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { backPressed = mActivity.getBackPressed(); if (backPressed) mActivity.onBackPressed(); // Set the title on the action when drawer closed Adapter adapter = mController.getActiveAdapter(); Location location = null; if(adapter != null && mActiveLocationId!= null) { location = mController.getLocation(adapter.getId(), mActiveLocationId); } if (adapter != null && location != null) { mActivity.getSupportActionBar().setTitle(location.getName()); } else { setDefaultTitle(); } super.onDrawerClosed(view); Log.d(TAG, "BackPressed - onDrawerClosed " + String.valueOf(backPressed)); mIsDrawerOpen = false; finishActinMode(); } public void onDrawerOpened(View drawerView) { // Set the title on the action when drawer open mActivity.getSupportActionBar().setTitle(mDrawerTitle); super.onDrawerOpened(drawerView); mIsDrawerOpen = true; // backPressed = true; } }; mDrawerLayout.setDrawerListener(mDrawerToggle); mDrawerToggle.syncState(); // Enable ActionBar app icon to behave as action to toggle nav drawer mActivity.getSupportActionBar().setHomeButtonEnabled(true); mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); mActivity.setSupportProgressBarIndeterminateVisibility(false); openMenu(); } public void openMenu() { mIsDrawerOpen = true; mDrawerLayout.openDrawer(mDrawerList); } public void closeMenu() { mIsDrawerOpen = false; mDrawerLayout.closeDrawer(mDrawerList); if (mMode != null) { mMode.finish(); } } public void redrawMenu() { mMenuAdapter = getMenuAdapter(); mDrawerList.setAdapter(mMenuAdapter); Adapter adapter = mController.getActiveAdapter(); Location location = null; if(adapter != null && mActiveLocationId!= null) { location = mController.getLocation(adapter.getId(), mActiveLocationId); } if (adapter != null && location != null) { mActivity.getSupportActionBar().setTitle(location.getName()); } else if (adapter != null && mActiveLocationId == Constants.GUI_MENU_ALL_SENSOR_ID){ // All sensors mActivity.getSupportActionBar().setTitle("All sensors"); } else { setDefaultTitle(); } if (!mIsDrawerOpen) { // Close drawer closeMenu(); Log.d(TAG, "LifeCycle: onOrientation"); } } protected void changeCustomView(boolean closeDrawer) { // (CustomView customView, boolean closeDrawer){ // ((MainActivity) mActivity).setActiveCustomView(param); mActivity.setActiveCustomViewID("tempValeu"); mActivity.redrawCustomView(); // Close drawer if (closeDrawer) { closeMenu(); } } private void changeLocation(Location location, boolean closeDrawer) { // save current location SharedPreferences prefs = mController.getUserSettings(); // UserSettings can be null when user is not logged in! if (prefs != null && location != null) { Editor edit = prefs.edit(); String pref_key = Persistence.getPreferencesLastLocation(mController.getActiveAdapter().getId()); edit.putString(pref_key, location.getId()); edit.commit(); } if(location != null ){ mActiveLocationId = location.getId(); } else { // All sensors item mActiveLocationId = Constants.GUI_MENU_ALL_SENSOR_ID; } // TODO mActivity.setActiveAdapterID(mActiveAdapterId); mActivity.setActiveLocationID(mActiveLocationId); mActivity.redrawDevices(); // Close drawer if (closeDrawer) { closeMenu(); } } private void doSwitchAdapter(String adapterId) { mSwitchAdapterTask = new SwitchAdapterTask(mActivity, false); mSwitchAdapterTask.setListener(new CallbackTaskListener() { @Override public void onExecute(boolean success) { if (success) { mActivity.setActiveAdapterAndLocation(); mActivity.redrawDevices(); redrawMenu(); } mActivity.setSupportProgressBarIndeterminateVisibility(false); } }); mActivity.setSupportProgressBarIndeterminateVisibility(true); mSwitchAdapterTask.execute(adapterId); } private void doUnregistAdapter(String adapterId) { mUnregisterAdapterTask = new UnregisterAdapterTask(mActivity); mUnregisterAdapterTask.setListener(new CallbackTaskListener() { @Override public void onExecute(boolean success) { if (success) { new ToastMessageThread(mActivity, R.string.toast_adapter_removed).start(); mActivity.setActiveAdapterAndLocation(); mActivity.redrawDevices(); mActivity.redrawMenu(); } mActivity.setSupportProgressBarIndeterminateVisibility(false); } }); mActivity.setSupportProgressBarIndeterminateVisibility(true); mUnregisterAdapterTask.execute(adapterId); } public MenuListAdapter getMenuAdapter() { mMenuAdapter = new MenuListAdapter(mActivity); // Adding profile header ActualUser actUser = mController.getActualUser(); Bitmap picture = actUser.getPicture(); if (picture == null) picture = actUser.getDefaultPicture(mActivity); mMenuAdapter.addHeader(new ProfileMenuItem(actUser.getName(), actUser.getEmail(), picture)); List<Adapter> adapters = mController.getAdapters(); Adapter activeAdapter = mController.getActiveAdapter(); // Adding separator as item (we don't want to let it float as header) mMenuAdapter.addItem(new SeparatorMenuItem()); mMenuAdapter.addHeader(new GroupImageMenuItem(mActivity.getResources().getString(R.string.adapter), R.drawable.add_custom_view, new OnClickListener() { @Override public void onClick(View v) { //DialogFragment newFragment = new AddAdapterFragmentDialog(); //newFragment.show(mActivity.getSupportFragmentManager(), MainActivity.ADD_ADAPTER_TAG); Intent intent = new Intent(mActivity, AddAdapterActivity.class); mActivity.startActivityForResult(intent, Constants.ADD_ADAPTER_REQUEST_CODE); } })); if (!adapters.isEmpty()) { // Adding separator as item (we don't want to let it float as header) //mMenuAdapter.addItem(new SeparatorMenuItem()); // Adding adapters for (Adapter actAdapter : adapters) { mMenuAdapter.addItem(new AdapterMenuItem(actAdapter.getName(), actAdapter.getRole().name(), activeAdapter.getId().equals(actAdapter.getId()), actAdapter.getId())); } // Adding separator as item (we don't want to let it float as header) mMenuAdapter.addItem(new SeparatorMenuItem()); // Adding location header mMenuAdapter.addHeader(new GroupImageMenuItem(mActivity.getResources().getString(R.string.location), R.drawable.add_custom_view, new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(mActivity, "Not implemented yet", Toast.LENGTH_SHORT).show(); } })); List<Location> locations = mController.getLocations(activeAdapter != null ? activeAdapter.getId() : ""); if (locations.size() > 0) { boolean boolActLoc = false; if(locations.size() > 1) { if(mActiveLocationId != null ) { boolActLoc = (mActiveLocationId.equals(Constants.GUI_MENU_ALL_SENSOR_ID)) ? true : false; } // ALL Sensor from adapter mMenuAdapter.addItem(new LocationMenuItem("All sensors", R.drawable.loc_all, false, Constants.GUI_MENU_ALL_SENSOR_ID,boolActLoc )); } // Adding location for (int i = 0; i < locations.size(); i++) { Location actLoc = locations.get(i); boolActLoc = false; if(mActiveLocationId != null ) { boolActLoc = (mActiveLocationId.equals(actLoc.getId())) ? true : false; } mMenuAdapter.addItem(new LocationMenuItem(actLoc.getName(), actLoc.getIconResource(), false, actLoc.getId(),boolActLoc )); } } else { mMenuAdapter.addItem(new EmptyMenuItem(mActivity.getResources().getString(R.string.no_location))); } mMenuAdapter.addItem(new SeparatorMenuItem()); // Adding custom view header mMenuAdapter.addHeader(new GroupImageMenuItem(mActivity.getResources().getString(R.string.custom_view), R.drawable.add_custom_view, new OnClickListener() { @Override public void onClick(View v) { // TODO doplnit spusteni dialogu pro vytvoreni custom view Toast.makeText(mActivity, "Not implemented yet", Toast.LENGTH_SHORT).show(); } })); // Adding custom views // TODO pridat custom views // mMenuAdapter.addItem(new EmptyMenuItem(mActivity.getResources().getString(R.string.no_custom_view))); mMenuAdapter.addItem(new CustomViewMenuItem("Graph view", R.drawable.loc_living_room, false, "Custom001", (mActiveCustomViewId != null) ? true : false)); } else { mMenuAdapter.addItem(new EmptyMenuItem(mActivity.getResources().getString(R.string.no_adapters))); } // Adding separator as header mMenuAdapter.addItem(new SeparatorMenuItem()); // Adding settings, about etc. mMenuAdapter.addItem(new SettingMenuItem(mActivity.getResources().getString(R.string.action_settings), R.drawable.settings, cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_SETTINGS)); mMenuAdapter.addItem(new SettingMenuItem(mActivity.getResources().getString(R.string.action_about), R.drawable.info, cz.vutbr.fit.iha.activity.menuItem.MenuItem.ID_ABOUT)); // menuAdapter.log(); return mMenuAdapter; } public void clickOnHome() { if (mDrawerLayout.isDrawerOpen(mDrawerList)) { closeMenu(); } else { openMenu(); } } /** * Handling first tap back button */ public void firstTapBack() { Log.d(TAG, "firtstTap"); Toast.makeText(mActivity, mActivity.getString(R.string.toast_tap_again_exit), Toast.LENGTH_SHORT).show(); // backPressed = true; ((MainActivity) mActivity).setBackPressed(true); openMenu(); } /** * Handling second tap back button - exiting */ public void secondTapBack() { Log.d(TAG, "secondTap"); mActivity.finish(); } public void onConfigurationChanged(Configuration newConfig) { mDrawerToggle.onConfigurationChanged(newConfig); } public void setDefaultTitle() { mDrawerTitle = "IHA"; } public void setIsDrawerOpen(boolean value) { mIsDrawerOpen = value; } public boolean getIsDrawerOpen() { return mIsDrawerOpen; } public void setLocationID(String locID) { mActiveLocationId = locID; mActiveCustomViewId = null; } public void setAdapterID(String adaID) { mActiveAdapterId = adaID; } public void cancelAllTasks() { if (mSwitchAdapterTask != null) { mSwitchAdapterTask.cancel(true); } if (mUnregisterAdapterTask != null) { mUnregisterAdapterTask.cancel(true); } } class ActionModeAdapters implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { if(mController.isUserAllowed(mController.getAdapter(mSelectedMenuItem.getId()).getRole()) ) { menu.add("Edit").setIcon(R.drawable.ic_mode_edit_white_24dp).setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_ALWAYS); menu.add("Users").setIcon(R.drawable.ic_group_white_24dp).setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_ALWAYS); } menu.add("Unregist").setIcon(R.drawable.ic_delete_white_24dp).setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_IF_ROOM); //menu.add("Cancel").setIcon(R.drawable.iha_ic_action_cancel).setTitle("Cancel").setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } @Override public void onDestroyActionMode(ActionMode mode) { mMode = null; mSelectedMenuItem.setNotSelected(); } @Override public boolean onActionItemClicked(ActionMode mode, com.actionbarsherlock.view.MenuItem item) { if (item.getTitle().equals("Unregist")) { // UNREGIST ADAPTER doUnregistAdapter(mSelectedMenuItem.getId()); } else if (item.getTitle().equals("Users")) { // GO TO USERS OF ADAPTER Intent intent = new Intent(mActivity, AdapterUsersActivity.class); intent.putExtra(Constants.GUI_SELECTED_ADAPTER_ID, mSelectedMenuItem.getId()); mActivity.startActivity(intent); } else if (item.getTitle().equals("Edit")) { // RENAME ADAPTER new ToastMessageThread(mActivity, R.string.toast_not_implemented).start(); } mode.finish(); return true; } } class ActionModeLocations implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { menu.add("Edit").setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_ALWAYS); // menu.add("Unregist").setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_IF_ROOM); menu.add("Cancel").setIcon(R.drawable.iha_ic_action_cancel).setTitle("Cancel").setShowAsAction(com.actionbarsherlock.view.MenuItem.SHOW_AS_ACTION_ALWAYS); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } @Override public void onDestroyActionMode(ActionMode mode) { mMode = null; } @Override public boolean onActionItemClicked(ActionMode mode, com.actionbarsherlock.view.MenuItem item) { if (item.getTitle().equals("Edit")) { new ToastMessageThread(mActivity, R.string.toast_not_implemented).start(); } mode.finish(); return true; } } public void finishActinMode() { Log.d(TAG, "Close action mode"); if (mMode != null) mMode.finish(); } }
package org.restheart.handlers.metadata; import io.undertow.server.HttpServerExchange; import java.util.List; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonValue; import org.restheart.hal.metadata.InvalidMetadataException; import org.restheart.hal.metadata.RepresentationTransformer; import org.restheart.hal.metadata.singletons.NamedSingletonsFactory; import org.restheart.hal.metadata.singletons.Transformer; import org.restheart.handlers.PipedHttpHandler; import org.restheart.handlers.RequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * handler that applies the transformers defined in the collection properties to * the request * * @author Andrea Di Cesare {@literal <andrea@softinstigate.com>} */ public class RequestTransformerMetadataHandler extends AbstractTransformerMetadataHandler { static final Logger LOGGER = LoggerFactory.getLogger(RequestTransformerMetadataHandler.class); /** * Creates a new instance of RequestTransformerMetadataHandler * * @param next */ public RequestTransformerMetadataHandler(PipedHttpHandler next) { super(next); } @Override boolean canCollRepresentationTransformersAppy(RequestContext context) { return (!context.isInError() && (context.getType() == RequestContext.TYPE.DOCUMENT || context.getType() == RequestContext.TYPE.BULK_DOCUMENTS || context.getType() == RequestContext.TYPE.COLLECTION || context.getType() == RequestContext.TYPE.AGGREGATION || context.getType() == RequestContext.TYPE.FILE || context.getType() == RequestContext.TYPE.FILES_BUCKET || context.getType() == RequestContext.TYPE.INDEX || context.getType() == RequestContext.TYPE.COLLECTION_INDEXES || context.getType() == RequestContext.TYPE.SCHEMA_STORE || context.getType() == RequestContext.TYPE.SCHEMA) && context.getCollectionProps() != null && context.getCollectionProps() .containsKey(RepresentationTransformer.RTS_ELEMENT_NAME)); } @Override boolean canDBRepresentationTransformersAppy(RequestContext context) { return (!context.isInError() && (context.getType() == RequestContext.TYPE.DB || context.getType() == RequestContext.TYPE.COLLECTION || context.getType() == RequestContext.TYPE.FILES_BUCKET || context.getType() == RequestContext.TYPE.COLLECTION_INDEXES || context.getType() == RequestContext.TYPE.SCHEMA_STORE) && context.getDbProps() != null && context.getDbProps() .containsKey(RepresentationTransformer.RTS_ELEMENT_NAME)); } @Override void enforceDbRepresentationTransformLogic( HttpServerExchange exchange, RequestContext context) throws InvalidMetadataException { List<RepresentationTransformer> dbRts = RepresentationTransformer.getFromJson(context.getDbProps()); RequestContext.TYPE requestType = context.getType(); // DB, COLLECTION or FILES_BUCKET for (RepresentationTransformer rt : dbRts) { Transformer t; try { t = (Transformer) NamedSingletonsFactory .getInstance() .get("transformers", rt.getName()); } catch (IllegalArgumentException ex) { context.addWarning("error applying transformer: " + ex.getMessage()); return; } if (t == null) { throw new IllegalArgumentException("cannot find singleton " + rt.getName() + " in singleton group transformers"); } if (rt.getPhase() == RepresentationTransformer.PHASE.REQUEST) { if (rt.getScope() == RepresentationTransformer.SCOPE.THIS && requestType == RequestContext.TYPE.DB) { t.transform( exchange, context, context.getContent(), rt.getArgs()); } else { t.transform( exchange, context, context.getContent(), rt.getArgs()); } } } } @Override void enforceCollRepresentationTransformLogic( HttpServerExchange exchange, RequestContext context) throws InvalidMetadataException { List<RepresentationTransformer> collRts = RepresentationTransformer .getFromJson(context.getCollectionProps()); for (RepresentationTransformer rt : collRts) { if (rt.getPhase() == RepresentationTransformer.PHASE.REQUEST) { Transformer t = (Transformer) NamedSingletonsFactory .getInstance() .get("transformers", rt.getName()); if (t == null) { throw new IllegalArgumentException("cannot find singleton " + rt.getName() + " in singleton group transformers"); } BsonValue content = context.getContent(); // content can be an array for bulk POST if (content == null) { t.transform( exchange, context, new BsonDocument(), rt.getArgs()); } else if (content.isDocument()) { t.transform( exchange, context, content.asDocument(), rt.getArgs()); } else if (content.isArray()) { BsonArray arrayContent = content.asArray(); arrayContent.stream().forEach(obj -> { if (obj.isDocument()) { t.transform( exchange, context, obj.asDocument(), rt.getArgs()); } else { LOGGER.warn("an element of content array " + "is not an object"); } }); } } } } }
package pl.edu.pw.mini.msi.knowledgerepresentation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.antlr.v4.runtime.misc.FlexibleHashMap; import org.antlr.v4.runtime.tree.ErrorNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Action; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Actor; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Event; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Fluent; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Scenario; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Task; import pl.edu.pw.mini.msi.knowledgerepresentation.data.Time; import pl.edu.pw.mini.msi.knowledgerepresentation.engine.EngineManager; import pl.edu.pw.mini.msi.knowledgerepresentation.engine.Knowledge; import pl.edu.pw.mini.msi.knowledgerepresentation.grammar.ActionLanguageBaseListener; import pl.edu.pw.mini.msi.knowledgerepresentation.grammar.ActionLanguageParser; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; public class ActionLanguageListener extends ActionLanguageBaseListener { public enum QueryType { GENERALLY, ALWAYS, EVER, NONE } private static final Logger log = LoggerFactory.getLogger(ActionLanguageListener.class); private final Knowledge knowledge; private final HashMap<String, Scenario> scenarios = Maps.newLinkedHashMap(); private EngineManager engineManager; private Collection<Event> events = Lists.newArrayList(); private Multimap<Time, Fluent> observations = LinkedHashMultimap.create(); private Collection<Fluent> lastFluentsList = Sets.newHashSet(); private Collection<Fluent> underConditionFluentList = Sets.newHashSet(); private Collection<Actor> lastActorsList = Sets.newHashSet(); private Action previousLastAction; private Action lastAction; private Actor lastActor; private Time lastTime; private Task lastTask; private Fluent lastFluent; private String lastScenarioId; private QueryType lastQueryType; private boolean typically; public ActionLanguageListener(Knowledge knowledge) { this.knowledge = knowledge; } public Knowledge getKnowledge() { return knowledge; } public HashMap<String, Scenario> getScenarios() { return scenarios; } @Override public void exitInitiallisation(ActionLanguageParser.InitiallisationContext ctx) { log.debug("Set initial state: %s", lastFluentsList); for (Fluent fluent : lastFluentsList) { //knowledge._Initially.add(fluent); } } @Override public void exitCauses(ActionLanguageParser.CausesContext ctx) { log.debug(String.format("(Typically=%s) %s CAUSES %s after %s IF %s", typically, lastAction, lastFluentsList, lastTime, underConditionFluentList)); knowledge.addEffectCause(typically, lastAction, new ArrayList<Fluent>(lastFluentsList), new ArrayList<Fluent>(underConditionFluentList)); } @Override public void exitInvokes(ActionLanguageParser.InvokesContext ctx) { log.debug(String.format("(Typically=%s) %s INVOKES %s after %s IF %s", typically, previousLastAction, lastAction, lastTime, underConditionFluentList)); knowledge.addEffectInvokes(typically, previousLastAction, lastAction, lastTime.getTime(), new ArrayList<Fluent>(underConditionFluentList)); } @Override public void exitReleases(ActionLanguageParser.ReleasesContext ctx) { log.debug(String.format("(Typically=%s) %s RELEASES %s AFTER %s IF %s", typically, lastAction, lastFluentsList, lastTime, underConditionFluentList)); knowledge.releases(typically, lastAction, lastFluentsList, lastTime.getTime(), underConditionFluentList); } @Override public void exitTriggers(ActionLanguageParser.TriggersContext ctx) { log.debug(String.format("(Typically=%s) %s TRIGGERS %s", typically, lastAction, underConditionFluentList)); knowledge.addEffectTriggers(typically, lastAction, new ArrayList<Fluent>(underConditionFluentList)); } @Override public void exitOccurs(ActionLanguageParser.OccursContext ctx) { } @Override public void exitImpossible(ActionLanguageParser.ImpossibleContext ctx) { log.debug(String.format("IMPOSSIBLE %s AT %s IF %s", lastAction, lastTime, underConditionFluentList)); knowledge.impossible(lastAction, lastTime.getTime(), underConditionFluentList); } @Override public void exitAlways(ActionLanguageParser.AlwaysContext ctx) { log.debug(String.format("ALWAYS %s", lastFluent)); knowledge.addAlways(lastFluent); } @Override public void exitState(ActionLanguageParser.StateContext ctx) { //log.debug(String.format("ALWAYS %s ", lastFluent)); //engineManager.conditionAt(lastQueryType, lastFluentsList, lastTime, ctx.scenarioId().IDENTIFIER().getText()); } @Override public void exitPerformed(ActionLanguageParser.PerformedContext ctx) { //log.debug(String.format("ALWAYS %s PERFORMED", lastFluent)); //engineManager.performed(lastQueryType, lastAction, lastTime, ctx.scenarioId().IDENTIFIER().getText()); } @Override public void exitInvolved(ActionLanguageParser.InvolvedContext ctx) { //log.debug(String.format("%s INVOLVED %s WHEN %s", lastQueryType, lastActorsList, scenario)); Scenario scenario = scenarios.get(ctx.scenarioId().IDENTIFIER().getText()); //engineManager.involved(lastQueryType, lastActorsList, ctx.scenarioId().IDENTIFIER().getText()); } @Override public void enterQuery(ActionLanguageParser.QueryContext ctx) { lastQueryType = QueryType.NONE; } @Override public void exitQuestion(ActionLanguageParser.QuestionContext ctx) { if (ctx.TYPICALLY() != null) { lastQueryType = QueryType.GENERALLY; } } @Override public void exitBasicQuestion(ActionLanguageParser.BasicQuestionContext ctx) { if (ctx.ALWAYS() != null) { lastQueryType = QueryType.ALWAYS; } else if (ctx.EVER() != null) { lastQueryType = QueryType.EVER; } } @Override public void enterUnderCondition(ActionLanguageParser.UnderConditionContext ctx) { underConditionFluentList = ImmutableList.copyOf(lastFluentsList); } @Override public void exitUnderCondition(ActionLanguageParser.UnderConditionContext ctx) { Collection<Fluent> fluents = ImmutableList.copyOf(underConditionFluentList); underConditionFluentList = ImmutableList.copyOf(lastFluentsList); lastFluentsList = fluents; } @Override public void enterActor(ActionLanguageParser.ActorContext ctx) { Actor actor = new Actor(ctx.IDENTIFIER().getText()); lastActor = actor; if(!lastActorsList.contains(actor)){ lastActorsList.add(actor); } } @Override public void enterTask(ActionLanguageParser.TaskContext ctx) { lastTask = new Task(ctx.IDENTIFIER().getText()); } @Override public void exitAction(ActionLanguageParser.ActionContext ctx) { previousLastAction = lastAction; lastAction = new Action(lastActor, lastTask); } @Override public void enterFluent(ActionLanguageParser.FluentContext ctx) { lastFluent = new Fluent(ctx.IDENTIFIER().getText(), ctx.NOT() == null); lastFluentsList.add(lastFluent); } @Override public void enterInstruction(ActionLanguageParser.InstructionContext ctx) { log.debug("Enter " + ctx.getText()); log.debug("Clean previous instruction context"); events.clear(); observations.clear(); lastFluentsList.clear(); lastActorsList.clear(); } @Override public void enterEntry(ActionLanguageParser.EntryContext ctx) { typically = ctx.TYPICALLY() != null; } @Override public void enterTime(ActionLanguageParser.TimeContext ctx) { lastTime = new Time(Integer.parseInt(ctx.DecimalConstant().getText())); } @Override public void enterFluentsList(ActionLanguageParser.FluentsListContext ctx) { log.debug("Clean previously parsed fluent list data"); lastFluentsList.clear(); } @Override public void exitScenario(ActionLanguageParser.ScenarioContext ctx) { String name = ctx.IDENTIFIER().getText(); Map<Time, Action> actions = events.stream().collect(Collectors.toMap(Event::getTime, Event::getAction)); Scenario scenario = new Scenario(name, ImmutableMultimap.copyOf(observations), actions); log.debug("Create scenario: ", scenario); scenarios.put(name, scenario); //engineManager = new EngineManager(knowledge, scenario, 20); } @Override public void exitEvent(ActionLanguageParser.EventContext ctx) { events.add(new Event(lastAction, lastTime)); } @Override public void exitObservation(ActionLanguageParser.ObservationContext ctx) { for (Fluent fluent : lastFluentsList) { observations.put(lastTime, fluent); } } @Override public void visitErrorNode(ErrorNode node) { log.error("Visit error node: " + node.getText()); } }
package org.apache.jmeter.protocol.http.modifier; import java.io.Serializable; import junit.framework.TestCase; import org.apache.jmeter.config.Argument; import org.apache.jmeter.config.Arguments; import org.apache.jmeter.config.ResponseBasedModifier; import org.apache.jmeter.protocol.http.sampler.HTTPSampler; import org.apache.jmeter.protocol.http.util.HTTPArgument; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.testelement.AbstractTestElement; import org.apache.log.Hierarchy; import org.apache.log.Logger; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.MatchResult; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; /** * @author mstover * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class URLRewritingModifier extends AbstractTestElement implements Serializable, ResponseBasedModifier { transient private static Logger log = Hierarchy.getDefaultHierarchy().getLoggerFor("jmeter.protocol.http"); private Pattern case1, case2, case3; transient Perl5Compiler compiler = new Perl5Compiler(); private final static String ARGUMENT_NAME = "argument_name"; private final static String PATH_EXTENSION = "path_extension"; /** * @see ResponseBasedModifier#modifyEntry(Sampler, SampleResult) */ public boolean modifyEntry(Sampler sampler, SampleResult responseText) { if(case1 == null) { initRegex(getArgumentName()); } String text = new String(responseText.getResponseData()); Perl5Matcher matcher = new Perl5Matcher(); String value = ""; if (matcher.contains(text, case1)) { MatchResult result = matcher.getMatch(); value = result.group(1); } else if (matcher.contains(text, case2)) { MatchResult result = matcher.getMatch(); value = result.group(1); } else if (matcher.contains(text, case3)) { MatchResult result = matcher.getMatch(); value = result.group(1); } modify((HTTPSampler) sampler, value); if (value.length() > 0) { return true; } return false; } private void modify(HTTPSampler sampler, String value) { if (isPathExtension()) { sampler.setPath( sampler.getPath() + ";" + getArgumentName() + "=" + value); } else { sampler.getArguments().removeArgument(getArgumentName()); sampler.getArguments().addArgument( new HTTPArgument(getArgumentName(), value, true)); } } public void setArgumentName(String argName) { setProperty(ARGUMENT_NAME, argName); case1 = case2 = case3 = null; } private void initRegex(String argName) { try { case1 = compiler.compile(argName + "=([^\"'>& \n\r]*)[& \\n\\r\"'>]?$?"); case2 = compiler.compile( "[Nn][Aa][Mm][Ee]=\"" + argName + "\"[^>]+[vV][Aa][Ll][Uu][Ee]=\"([^\"]*)\""); case3 = compiler.compile( "[vV][Aa][Ll][Uu][Ee]=\"([^\"]*)\"[^>]+[Nn][Aa][Mm][Ee]=\"" + argName + "\""); } catch (MalformedPatternException e) { log.error("", e); } } public String getArgumentName() { return getPropertyAsString(ARGUMENT_NAME); } public void setPathExtension(boolean pathExt) { setProperty(PATH_EXTENSION, new Boolean(pathExt)); } public boolean isPathExtension() { return getPropertyAsBoolean(PATH_EXTENSION); } public static class Test extends TestCase { SampleResult response; public Test(String name) { super(name); } public void setUp() { } public void testGrabSessionId() throws Exception { String html = "location: http://server.com/index.html?session_id=jfdkjdkf%jddkfdfjkdjfdf"; response = new SampleResult(); response.setResponseData(html.getBytes()); URLRewritingModifier mod = new URLRewritingModifier(); mod.setArgumentName("session_id"); HTTPSampler sampler = new HTTPSampler(); sampler.setDomain("server.com"); sampler.setPath("index.html"); sampler.setMethod(HTTPSampler.GET); sampler.setProtocol("http"); sampler.addArgument("session_id", "adfasdfdsafasdfasd"); mod.modifyEntry(sampler, response); Arguments args = sampler.getArguments(); assertEquals( "jfdkjdkf%jddkfdfjkdjfdf", ((Argument) args.getArguments().get(0)).getValue()); assertEquals( "http://server.com:80/index.html?session_id=jfdkjdkf%jddkfdfjkdjfdf", sampler.toString()); } public void testGrabSessionId2() throws Exception { String html = "<a href=\"http://server.com/index.html?session_id=jfdkjdkfjddkfdfjkdjfdf\">"; response = new SampleResult(); response.setResponseData(html.getBytes()); URLRewritingModifier mod = new URLRewritingModifier(); mod.setArgumentName("session_id"); HTTPSampler sampler = new HTTPSampler(); sampler.setDomain("server.com"); sampler.setPath("index.html"); sampler.setMethod(HTTPSampler.GET); sampler.setProtocol("http"); mod.modifyEntry(sampler, response); Arguments args = sampler.getArguments(); assertEquals( "jfdkjdkfjddkfdfjkdjfdf", ((Argument) args.getArguments().get(0)).getValue()); } public void testGrabSessionId3() throws Exception { String html = "href='index.html?session_id=jfdkjdkfjddkfdfjkdjfdf'"; response = new SampleResult(); response.setResponseData(html.getBytes()); URLRewritingModifier mod = new URLRewritingModifier(); mod.setArgumentName("session_id"); HTTPSampler sampler = new HTTPSampler(); sampler.setDomain("server.com"); sampler.setPath("index.html"); sampler.setMethod(HTTPSampler.GET); sampler.setProtocol("http"); mod.modifyEntry(sampler, response); Arguments args = sampler.getArguments(); assertEquals( "jfdkjdkfjddkfdfjkdjfdf", ((Argument) args.getArguments().get(0)).getValue()); } } }
package org.ow2.proactive.scheduler.exception; /** * * Exceptions Generated during the run of a native process. * * @author The ProActive Team * @since ProActive Scheduling 0.9 * */ public class RunningProcessException extends ProcessException { /** * Attaches a message to the Exception * @param message message attached */ public RunningProcessException(String message) { super(message); } public RunningProcessException(String message, Throwable cause) { super(message, cause); } }
package com.markupartist.sthlmtraveling.provider.site; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.util.Pair; import android.text.TextUtils; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; public class Site implements Parcelable { public static String TYPE_MY_LOCATION = "MY_LOCATION"; public static int SOURCE_STHLM_TRAVELING = 0; public static int SOURCE_GOOGLE_PLACES = 1; private static String NAME_RE = "[^\\p{Alnum}\\(\\)\\s]"; private String mId; private String mName; private String mLocality; private String mType; private Location mLocation; private int mSource = SOURCE_STHLM_TRAVELING; public Site() { } /** * Create a new Stop that is a copy of the given Stop. * @param site the site */ public Site(Site site) { mName = site.getName(); mLocality = site.getLocality(); mLocation = site.getLocation(); mId = site.getId(); mType = site.getType(); mSource = site.getSource(); } private String getType() { return mType; } public Site(Parcel parcel) { mId = parcel.readString(); mName = parcel.readString(); mType = parcel.readString(); double latitude = parcel.readDouble(); double longitude = parcel.readDouble(); if (latitude > 0 && longitude > 0) { Location location = new Location("sthlmtraveling"); location.setLatitude(latitude); location.setLongitude(longitude); setLocation(location); } mLocality = parcel.readString(); mSource = parcel.readInt(); } /** * @return the id */ public String getId() { return mId; } /** * @return the name */ public String getName() { return mName; } /** * @param id the id to set */ public void setId(int id) { mId = String.valueOf(id); } /** * @param id the id to set */ public void setId(String id) { mId = id; } /** * @param name the name to set */ public void setName(String name) { if (!TextUtils.isEmpty(name)) { if (name.equals(TYPE_MY_LOCATION)) { mName = name; } else { //mName = name.trim().replaceAll(NAME_RE, ""); mName = name; } } } public void setLocality(String locality) { mLocality = locality; } public String getLocality() { return mLocality; } public int getSource() { return mSource; } public void setSource(int source) { this.mSource = source; } public void setType(String type) { mType = type; } public void setLocation(Location location) { mLocation = location; } public Location getLocation() { return mLocation; } public boolean isAddress() { if (mType == null) { return false; } return mType.equals("A"); } public boolean hasName() { return !TextUtils.isEmpty(mName); } @Override public String toString() { return mName; // This is used by adapters. } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mId); parcel.writeString(mName); parcel.writeString(mType); if (this.hasLocation()) { parcel.writeDouble(mLocation.getLatitude()); parcel.writeDouble(mLocation.getLongitude()); } else { parcel.writeDouble(0); parcel.writeDouble(0); } parcel.writeString(mLocality); parcel.writeInt(mSource); } public static final Parcelable.Creator<Site> CREATOR = new Parcelable.Creator<Site>() { public Site createFromParcel(Parcel in) { return new Site(in); } public Site[] newArray(int size) { return new Site[size]; } }; // public static Site fromPlannerLocation(Planner.Location loc) { // Site s = new Site(); // s.setId(String.valueOf(loc.id)); // s.setLocation(loc.latitude, loc.longitude); // s.setName(loc.name); // return s; public static Site fromJson(JSONObject json) throws JSONException { Site site = new Site(); site.setSource(Site.SOURCE_STHLM_TRAVELING); site.setId(String.valueOf(json.getInt("site_id"))); Pair<String, String> nameAndLocality = SitesStore.nameAsNameAndLocality(json.getString("name")); site.setName(nameAndLocality.first); site.setLocality(nameAndLocality.second); if (json.has("type")) { site.setType(json.getString("type")); } if (json.has("location") && !json.isNull("location")) { JSONObject locationJson = json.getJSONObject("location"); try { Location location = new Location("sthlmtraveling"); location.setLatitude(locationJson.getDouble("latitude")); location.setLongitude(locationJson.getDouble("longitude")); site.setLocation(location); } catch(Exception e) { Log.e("SITE", e.getMessage()); } } return site; } public boolean isMyLocation() { return hasName() && mName.equals(TYPE_MY_LOCATION); } public boolean looksValid() { if (isMyLocation()) { return true; } if (hasLocation() && hasName() && mId == null) { return true; } if (hasName() && mId != null) { return true; } return false; } public static boolean looksValid(String name) { if (TextUtils.isEmpty(name) || TextUtils.getTrimmedLength(name) == 0) { return false; } return !name.matches(NAME_RE); } /** * Fill this Site with the values from another Site. If other is null this will be nullified. * @param value */ public void fromSite(Site value) { if (value != null) { mId = value.mId; mLocation = value.mLocation; mName = value.mName; mType = value.mType; mLocality = value.mLocality; } else { mId = null; mLocation = null; mName = null; mType = null; mLocality = null; } } public String getNameOrId() { if (hasLocation() || mId == null) { return mName; } return String.valueOf(mId); } public boolean hasLocation() { return mLocation != null; } public void setLocation(double lat, double lng) { mLocation = new Location("sthlmtraveling"); mLocation.setLatitude(lat); mLocation.setLongitude(lng); } public void setLocation(int lat, int lng) { if (lat == 0 || lng == 0) { return; } mLocation = new Location("sthlmtraveling"); mLocation.setLatitude(lat / 1E6); mLocation.setLongitude(lng / 1E6); } public String toDump() { return "Site [mId=" + mId + ", mName=" + mName + ", mType=" + mType + ", mLocation=" + mLocation + ", mSource=" + mSource + ", mLocality=" + mLocality + "]"; } }
package com.splicemachine.hbase.backup; import com.splicemachine.constants.SpliceConstants; import com.splicemachine.derby.impl.job.ZkTask; import com.splicemachine.derby.impl.job.coprocessor.RegionTask; import com.splicemachine.derby.impl.job.operation.OperationJob; import com.splicemachine.derby.impl.job.scheduler.SchedulerPriorities; import com.splicemachine.utils.SpliceLogUtils; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; public class RestoreBackupTask extends ZkTask { private static final long serialVersionUID = 5l; private BackupItem backupItem; public RestoreBackupTask() { } public RestoreBackupTask(BackupItem backupItem, String jobId) { super(jobId, OperationJob.operationTaskPriority); this.backupItem = backupItem; } @Override protected String getTaskType() { return "restoreBackupTask"; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(backupItem); // TODO Needs to be replaced with protobuf } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); backupItem = (BackupItem) in.readObject(); // TODO Needs to be replaced with protobuf } @Override public boolean invalidateOnClose() { return true; } @Override public RegionTask getClone() { return new RestoreBackupTask(backupItem, jobId); } @Override public void doExecute() throws ExecutionException, InterruptedException { if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG, String.format("executing %S backup on region %s", backupItem.getBackup().isIncrementalBackup() ? "incremental" : "full", region.toString())); try { BackupItem.RegionInfo regionInfo = getRegionInfo(); if (regionInfo == null) { return; } List<Pair<byte[], String>> famPaths = regionInfo.getFamPaths(); List<Pair<byte[], String>> copyPaths = copyStoreFiles(famPaths); region.bulkLoadHFiles(copyPaths); } catch (IOException e) { SpliceLogUtils.error(LOG, "Couldn't recover region " + region, e); throw new ExecutionException("Failed recovery of region " + region, e); } } private List<Pair<byte[], String>> copyStoreFiles(List<Pair<byte[], String>> famPaths) throws IOException { List<Pair<byte[], String>> copy = new ArrayList<Pair<byte[], String>>(famPaths.size()); FileSystem fs = region.getFilesystem(); for (Pair<byte[], String> pair : famPaths) { Path srcPath = new Path(pair.getSecond()); FileSystem srcFs = srcPath.getFileSystem(SpliceConstants.config); Path localDir = region.getRegionDir(); Path tmpPath = getRandomFilename(fs, localDir); FileUtil.copy(srcFs, srcPath, fs, tmpPath, false, SpliceConstants.config); copy.add(new Pair<byte[], String>(pair.getFirst(), tmpPath.toString())); } return copy; } private BackupItem.RegionInfo getRegionInfo() { Bytes.ByteArrayComparator comparator = new Bytes.ByteArrayComparator(); for (BackupItem.RegionInfo ri : backupItem.getRegionInfoList()) { if (comparator.compare(ri.getHRegionInfo().getEndKey(), region.getEndKey()) == 0) { return ri; } } SpliceLogUtils.warn(LOG, "Couldn't find matching backup data for region " + region); return null; } @Override public int getPriority() { return SchedulerPriorities.INSTANCE.getBasePriority(RestoreBackupTask.class); } static Path getRandomFilename(final FileSystem fs, final Path dir) throws IOException { return new Path(dir, UUID.randomUUID().toString().replaceAll("-", "")); } }
package com.emc.mongoose.tests.system; import com.github.akurilov.commons.system.SizeInBytes; import com.emc.mongoose.api.common.env.PathUtil; import com.emc.mongoose.api.model.io.IoType; import com.emc.mongoose.run.scenario.JsonScenario; import com.emc.mongoose.tests.system.base.ScenarioTestBase; import com.emc.mongoose.tests.system.base.params.Concurrency; import com.emc.mongoose.tests.system.base.params.DriverCount; import com.emc.mongoose.tests.system.base.params.ItemSize; import com.emc.mongoose.tests.system.base.params.StorageType; import com.emc.mongoose.tests.system.util.DirWithManyFilesDeleter; import com.emc.mongoose.tests.system.util.EnvUtil; import com.emc.mongoose.tests.system.util.HttpStorageMockUtil; import com.emc.mongoose.ui.log.LogUtil; import static com.emc.mongoose.api.common.env.PathUtil.getBaseDir; import static com.emc.mongoose.run.scenario.Scenario.DIR_SCENARIO; import org.apache.commons.csv.CSVRecord; import org.junit.After; import org.junit.Assert; import org.junit.Before; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.atomic.LongAdder; import java.util.function.Consumer; public class CopyUsingInputPathTest extends ScenarioTestBase { private String itemSrcPath; private String itemDstPath; private String stdOutput; private static final int COUNT_LIMIT = 100_000; public CopyUsingInputPathTest( final StorageType storageType, final DriverCount driverCount, final Concurrency concurrency, final ItemSize itemSize ) throws Exception { super(storageType, driverCount, concurrency, itemSize); } @Override protected Path makeScenarioPath() { return Paths.get( getBaseDir(), DIR_SCENARIO, "systest", "CopyUsingInputPath.json" ); } @Override protected String makeStepId() { return CopyUsingInputPathTest.class.getSimpleName() + '-' + storageType.name() + '-' + driverCount.name() + 'x' + concurrency.name() + '-' + itemSize.name(); } @Before public void setUp() throws Exception { super.setUp(); if(storageType.equals(StorageType.FS)) { itemSrcPath = Paths.get( Paths.get(PathUtil.getBaseDir()).getParent().toString(), stepId ).toString(); } else { itemSrcPath = '/' + stepId; } itemDstPath = itemSrcPath + "-Dst"; itemSrcPath += "-Src"; if(storageType.equals(StorageType.FS)) { try { DirWithManyFilesDeleter.deleteExternal(itemSrcPath); } catch(final Throwable ignored) { } try { DirWithManyFilesDeleter.deleteExternal(itemDstPath); } catch(final Throwable ignored) { } } EnvUtil.set("ITEM_SRC_PATH", itemSrcPath); EnvUtil.set("ITEM_DST_PATH", itemDstPath); scenario = new JsonScenario(config, scenarioPath.toFile()); stdOutStream.startRecording(); scenario.run(); LogUtil.flushAll(); stdOutput = stdOutStream.stopRecordingAndGet(); } @After public void tearDown() throws Exception { if(storageType.equals(StorageType.FS)) { try { DirWithManyFilesDeleter.deleteExternal(itemSrcPath); } catch(final Exception e) { e.printStackTrace(System.err); } try { DirWithManyFilesDeleter.deleteExternal(itemDstPath); } catch(final Exception e) { e.printStackTrace(System.err); } } super.tearDown(); } @Override public void test() throws Exception { final LongAdder ioTraceRecCount = new LongAdder(); final LongAdder lostItemsCount = new LongAdder(); final Consumer<CSVRecord> ioTraceRecTestFunc; if(storageType.equals(StorageType.FS)) { ioTraceRecTestFunc = ioTraceRecord -> { File nextSrcFile; File nextDstFile; final String nextItemPath = ioTraceRecord.get("ItemPath"); nextSrcFile = new File(nextItemPath); final String nextItemId = nextItemPath.substring( nextItemPath.lastIndexOf(File.separatorChar) + 1 ); nextDstFile = Paths.get(itemSrcPath, nextItemId).toFile(); Assert.assertTrue( "File \"" + nextItemPath + "\" doesn't exist", nextSrcFile.exists() ); if(!nextDstFile.exists()) { lostItemsCount.increment(); } else { Assert.assertEquals( "Source file (" + nextItemPath + ") size (" + nextSrcFile.length() + " is not equal to the destination file (" + nextDstFile.getAbsolutePath() + ") size (" + nextDstFile.length(), nextSrcFile.length(), nextDstFile.length() ); } testIoTraceRecord( ioTraceRecord, IoType.CREATE.ordinal(), new SizeInBytes(nextSrcFile.length()) ); ioTraceRecCount.increment(); }; } else { final String node = httpStorageMocks.keySet().iterator().next(); ioTraceRecTestFunc = ioTraceRecord -> { testIoTraceRecord(ioTraceRecord, IoType.CREATE.ordinal(), itemSize.getValue()); final String nextItemPath = ioTraceRecord.get("ItemPath"); if(HttpStorageMockUtil.getContentLength(node, nextItemPath) < 0) { // not found lostItemsCount.increment(); } final String nextItemId = nextItemPath.substring( nextItemPath.lastIndexOf(File.separatorChar) + 1 ); HttpStorageMockUtil.assertItemExists( node, itemSrcPath + '/' + nextItemId, itemSize.getValue().get() ); ioTraceRecCount.increment(); }; } testIoTraceLogRecords(ioTraceRecTestFunc); assertTrue( "There should be " + COUNT_LIMIT + " records in the I/O trace log file", ioTraceRecCount.sum() <= COUNT_LIMIT ); assertEquals(0, lostItemsCount.sum(), COUNT_LIMIT / 10_000); final List<CSVRecord> totalMetricsLogRecords = getMetricsTotalLogRecords(); assertEquals( "There should be 1 total metrics records in the log file", 1, totalMetricsLogRecords.size() ); if(storageType.equals(StorageType.FS)) { // some files may remain not written fully testTotalMetricsLogRecord( totalMetricsLogRecords.get(0), IoType.CREATE, concurrency.getValue(), driverCount.getValue(), new SizeInBytes(itemSize.getValue().get() / 2, itemSize.getValue().get(), 1), 0, 0 ); } else { testTotalMetricsLogRecord( totalMetricsLogRecords.get(0), IoType.CREATE, concurrency.getValue(), driverCount.getValue(), itemSize.getValue(), 0, 0 ); } final List<CSVRecord> metricsLogRecords = getMetricsLogRecords(); assertTrue( "There should be more than 0 metrics records in the log file", metricsLogRecords.size() > 0 ); if(storageType.equals(StorageType.FS)) { // some files may remain not written fully testMetricsLogRecords( metricsLogRecords, IoType.CREATE, concurrency.getValue(), driverCount.getValue(), new SizeInBytes(itemSize.getValue().get() / 2, itemSize.getValue().get(), 1), 0, 0, config.getOutputConfig().getMetricsConfig().getAverageConfig().getPeriod() ); } else { testMetricsLogRecords( metricsLogRecords, IoType.CREATE, concurrency.getValue(), driverCount.getValue(), itemSize.getValue(), 0, 0, config.getOutputConfig().getMetricsConfig().getAverageConfig().getPeriod() ); } testSingleMetricsStdout( stdOutput.replaceAll("[\r\n]+", " "), IoType.CREATE, concurrency.getValue(), driverCount.getValue(), itemSize.getValue(), config.getOutputConfig().getMetricsConfig().getAverageConfig().getPeriod() ); } }
package com.thinkaurelius.titan.graphdb; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.thinkaurelius.titan.core.*; import com.thinkaurelius.titan.diskstorage.util.TestLockerManager; import com.thinkaurelius.titan.graphdb.database.StandardTitanGraph; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * @author Matthias Broecheler (me@matthiasb.com) */ public class TitanEventualGraphTest extends TitanGraphTestCommon { private Logger log = LoggerFactory.getLogger(TitanEventualGraphTest.class); public TitanEventualGraphTest(Configuration config) { super(config); } public void updateConfiguration(Map<String,? extends Object> settings) { super.close(); BaseConfiguration newConfig = new BaseConfiguration(); newConfig.copy(config); for (Map.Entry<String,? extends Object> entry : settings.entrySet()) newConfig.addProperty(entry.getKey(),entry.getValue()); graph = (StandardTitanGraph) TitanFactory.open(newConfig); tx = graph.newTransaction(); } @Test public void concurrentIndexTest() { TitanKey id = tx.makeKey("uid").single().unique().indexed(Vertex.class).dataType(String.class).make(); TitanKey value = tx.makeKey("value").single(TypeMaker.UniquenessConsistency.NO_LOCK).dataType(Object.class).indexed(Vertex.class).make(); TitanVertex v = tx.addVertex(); v.setProperty(id, "v"); clopen(); //Concurrent index addition TitanTransaction tx1 = graph.newTransaction(); TitanTransaction tx2 = graph.newTransaction(); tx1.getVertex(id, "v").setProperty("value", 11); tx2.getVertex(id, "v").setProperty("value", 11); tx1.commit(); tx2.commit(); assertEquals("v", Iterables.getOnlyElement(tx.getVertices("value", 11)).getProperty(id.getName())); } @Test public void testTimestampSetting() { // Transaction 1: Init graph with two vertices, having set "name" and "age" properties TitanTransaction tx1 = graph.buildTransaction().setTimestamp(100).start(); String name = "name"; String age = "age"; String address = "address"; Vertex v1 = tx1.addVertex(); Vertex v2 = tx1.addVertex(); v1.setProperty(name, "a"); v2.setProperty(age, "14"); v2.setProperty(name, "b"); v2.setProperty(age, "42"); tx1.commit(); // Fetch vertex ids Object id1 = v1.getId(); Object id2 = v2.getId(); // Transaction 2: Remove "name" property from v1, set "address" property; create // an edge v2 -> v1 TitanTransaction tx2 = graph.buildTransaction().setTimestamp(1000).start(); v1 = tx2.getVertex(id1); v2 = tx2.getVertex(id2); v1.removeProperty(name); v1.setProperty(address, "xyz"); Edge edge = tx2.addEdge(1, v2, v1, "parent"); tx2.commit(); Object edgeId = edge.getId(); Vertex afterTx2 = graph.getVertex(id1); // Verify that "name" property is gone assertFalse(afterTx2.getPropertyKeys().contains(name)); // Verify that "address" property is set assertEquals("xyz", afterTx2.getProperty(address)); // Verify that the edge is properly registered with the endpoint vertex assertEquals(1, Iterables.size(afterTx2.getEdges(Direction.IN, "parent"))); // Verify that edge is registered under the id assertNotNull(graph.getEdge(edgeId)); graph.commit(); // Transaction 3: Remove "address" property from v1 with earlier timestamp than // when the value was set TitanTransaction tx3 = graph.buildTransaction().setTimestamp(200).start(); v1 = tx3.getVertex(id1); v1.removeProperty(address); tx3.commit(); Vertex afterTx3 = graph.getVertex(id1); graph.commit(); // Verify that "address" is still set assertEquals("xyz", afterTx3.getProperty(address)); // Transaction 4: Modify "age" property on v2, remove edge between v2 and v1 TitanTransaction tx4 = graph.buildTransaction().setTimestamp(2000).start(); v2 = tx4.getVertex(id2); v2.setProperty(age, "15"); tx4.removeEdge(tx4.getEdge(edgeId)); tx4.commit(); Vertex afterTx4 = graph.getVertex(id2); // Verify that "age" property is modified assertEquals("15", afterTx4.getProperty(age)); // Verify that edge is no longer registered with the endpoint vertex assertEquals(0, Iterables.size(afterTx4.getEdges(Direction.OUT, "parent"))); // Verify that edge entry disappeared from id registry assertNull(graph.getEdge(edgeId)); // Transaction 5: Modify "age" property on v2 with earlier timestamp TitanTransaction tx5 = graph.buildTransaction().setTimestamp(1500).start(); v2 = tx5.getVertex(id2); v2.setProperty(age, "16"); tx5.commit(); Vertex afterTx5 = graph.getVertex(id2); // Verify that the property value is unchanged assertEquals("15", afterTx5.getProperty(age)); } @Test public void testBatchLoadingNoLock() { testBatchLoadingLocking(true); } @Test @Ignore public void testLockException() { try { testBatchLoadingLocking(false); fail(); } catch (TitanException e) { Throwable cause = e; while (cause.getCause()!=null) cause=cause.getCause(); assertEquals(UnsupportedOperationException.class,cause.getClass()); } } public void testBatchLoadingLocking(boolean batchloading) { tx.makeKey("uid").dataType(Long.class).indexed(Vertex.class).single(TypeMaker.UniquenessConsistency.LOCK).unique(TypeMaker.UniquenessConsistency.LOCK).make(); tx.makeLabel("knows").oneToOne(TypeMaker.UniquenessConsistency.LOCK).make(); newTx(); TestLockerManager.ERROR_ON_LOCKING=true; updateConfiguration(ImmutableMap.of("storage.batch-loading",batchloading,"storage.lock-backend","test")); int numV = 10000; long start = System.currentTimeMillis(); for (int i=0;i<numV;i++) { TitanVertex v = tx.addVertex(); v.setProperty("uid",i+1); v.addEdge("knows",v); } clopen(); // System.out.println("Time: " + (System.currentTimeMillis()-start)); for (int i=0;i<Math.min(numV,300);i++) { assertEquals(1,Iterables.size(graph.query().has("uid",i+1).vertices())); assertEquals(1,Iterables.size(graph.query().has("uid",i+1).vertices().iterator().next().getEdges(Direction.OUT,"knows"))); } } }
package io.vertx.ext.auth.oauth2.impl.flow; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.oauth2.AccessToken; import io.vertx.ext.auth.oauth2.OAuth2ClientOptions; import io.vertx.ext.auth.oauth2.impl.AccessTokenImpl; import io.vertx.ext.auth.oauth2.impl.OAuth2AuthProviderImpl; import static io.vertx.ext.auth.oauth2.impl.OAuth2API.*; /** * @author Paulo Lopes */ public class AuthCodeImpl implements OAuth2Flow { private final OAuth2AuthProviderImpl provider; public AuthCodeImpl(OAuth2AuthProviderImpl provider) { this.provider = provider; } /** * Redirect the user to the authorization page * @param params - redirectURI: A String that represents the registered application URI where the user is redirected after authorization. * scope: A String that represents the application privileges. * scopes: A array of strings that will encoded as a single string "scope" following the provider requirements * state: A String that represents an optional opaque value used by the client to maintain state between the request and the callback. */ @Override public String authorizeURL(JsonObject params) { final JsonObject query = params.copy(); final OAuth2ClientOptions config = provider.getConfig(); if (query.containsKey("scopes")) { // scopes have been passed as a list so the provider must generate the correct string for it query.put("scope", String.join(config.getScopeSeparator(), query.getJsonArray("scopes").getList())); query.remove("scopes"); } query.put("response_type", "code"); query.put("client_id", config.getClientID()); return config.getSite() + config.getAuthorizationPath() + '?' + stringify(query); } /** * Returns the Access Token object. * * @param params - code: Authorization code (from previous step). * redirectURI: A String that represents the callback uri. * @param handler - The handler returning the results. */ @Override public void getToken(JsonObject params, Handler<AsyncResult<AccessToken>> handler) { final JsonObject query = params.copy(); query.put("grant_type", "authorization_code"); api(provider, HttpMethod.POST, provider.getConfig().getTokenPath(), query, res -> { if (res.succeeded()) { handler.handle(Future.succeededFuture(new AccessTokenImpl(provider, res.result()))); } else { handler.handle(Future.failedFuture(res.cause())); } }); } }
package br.com.caelum.vraptor.core; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import javax.enterprise.context.ApplicationScoped; import net.vidageek.mirror.dsl.Mirror; @ApplicationScoped public class DefaultReflectionProvider implements ReflectionProvider { @Override public List<Method> getMethodsFor(Class<?> clazz) { return new Mirror().on(clazz).reflectAll().methods(); } @Override public Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) { return new Mirror().on(clazz).reflect().method(methodName).withArgs(parameterTypes); } @Override public Object invoke(Object instance, Method method, Object... args) { return new Mirror().on(instance).invoke().method(method).withArgs(args); } @Override public Object invoke(Object instance, String methodName, Object... args) { return new Mirror().on(instance).invoke().method(methodName).withArgs(args); } @Override public Object invokeGetter(Object instance, String fieldName) { return new Mirror().on(instance).invoke().getterFor(fieldName); } @Override public List<Field> getFieldsFor(Class<?> clazz) { return new Mirror().on(clazz).reflectAll().fields(); } @Override public Field getField(Class<?> clazz, String fieldName) { return new Mirror().on(clazz).reflect().field(fieldName); } }
package au.org.plantphenomics.podd; import java.io.IOException; import org.openrdf.OpenRDFException; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.Rio; import org.openrdf.rio.UnsupportedRDFormatException; import org.restlet.Component; import org.restlet.data.LocalReference; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.representation.Representation; import org.restlet.routing.Router; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import com.github.ansell.restletutils.ClassLoaderDirectory; import com.github.ansell.restletutils.CompositeClassLoader; import com.github.podd.restlet.ApplicationUtils; import com.github.podd.restlet.PoddWebServiceApplication; import com.github.podd.restlet.PoddWebServiceApplicationImpl; import com.github.podd.utils.PoddWebConstants; public class PoddCSIRORestletComponent extends Component { static { System.setProperty("org.restlet.engine.loggerFacadeClass", "org.restlet.ext.slf4j.Slf4jLoggerFacade"); // Optionally remove existing handlers attached to j.u.l root logger SLF4JBridgeHandler.removeHandlersForRootLogger(); // (since SLF4J 1.6.5) // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during // the initialization phase of your application SLF4JBridgeHandler.install(); } private static final Logger log = LoggerFactory.getLogger(PoddCSIRORestletComponent.class); public PoddCSIRORestletComponent() { super(); this.getClients().add(Protocol.CLAP); this.getClients().add(Protocol.HTTP); this.initialise(); } /** * @param arg0 */ public PoddCSIRORestletComponent(final Reference arg0) { super(arg0); this.getClients().add(Protocol.CLAP); this.getClients().add(Protocol.HTTP); this.initialise(); } /** * @param xmlConfigRepresentation */ public PoddCSIRORestletComponent(final Representation xmlConfigRepresentation) { super(xmlConfigRepresentation); this.getClients().add(Protocol.CLAP); this.getClients().add(Protocol.HTTP); this.initialise(); } /** * @param xmlConfigurationRef */ public PoddCSIRORestletComponent(final String xmlConfigurationRef) { super(xmlConfigurationRef); this.getClients().add(Protocol.CLAP); this.getClients().add(Protocol.HTTP); this.initialise(); } public void initialise() { // FIXME: Make this configurable final LocalReference localReference = LocalReference.createClapReference(LocalReference.CLAP_THREAD, "static/"); final CompositeClassLoader customClassLoader = new CompositeClassLoader(); customClassLoader.addClassLoader(Thread.currentThread().getContextClassLoader()); customClassLoader.addClassLoader(Router.class.getClassLoader()); final ClassLoaderDirectory directory = new ClassLoaderDirectory(this.getContext().createChildContext(), localReference, customClassLoader); directory.setListingAllowed(true); final String resourcesPath = PoddWebConstants.PATH_RESOURCES; this.log.info("attaching resource handler to path={}", resourcesPath); // attach the resources first this.getDefaultHost().attach(resourcesPath, directory); PoddWebServiceApplication nextApplication; try { nextApplication = new PoddWebServiceApplicationImpl(); // attach the web services application this.getDefaultHost().attach("/", nextApplication); nextApplication.setAliasesConfiguration(Rio.parse(this.getClass().getResourceAsStream("/csiro-alias.ttl"), "", RDFFormat.TURTLE)); // setup the application after attaching it, as it requires Application.getContext() to // not be null during the setup process ApplicationUtils.setupApplication(nextApplication, nextApplication.getContext()); } catch(final OpenRDFException | UnsupportedRDFormatException | IOException e) { throw new RuntimeException("Could not setup application", e); } this.log.info("routes={}", this.getDefaultHost().getRoutes().toString()); } }
// This file is part of PLplot. // PLplot is free software; you can redistribute it and/or modify // PLplot is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with PLplot; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // Implementation of PLplot example 5 in Java. package plplot.examples; import plplot.core.*; import java.lang.Math; class x05 { static final int NPTS = 2047; public static void main( String[] args ) { x05 x = new x05( args ); } public x05( String[] args ) { PLStream pls = new PLStream(); int i; double[] data = new double[NPTS]; double delta; // Parse and process command line arguments. pls.parseopts( args, PLStream.PL_PARSE_FULL | PLStream.PL_PARSE_NOPROGRAM ); // Initialize plplot. pls.init(); // Fill up data points. delta = 2.0 * Math.PI / (double) NPTS; for (i = 0; i < NPTS; i++) data[i] = Math.sin(i * delta); pls.col0(1); pls.hist(data, -1.1, 1.1, 44, PLStream.PL_HIST_DEFAULT); pls.col0(2); pls.lab( "#frValue", "#frFrequency", "#frPLplot Example 5 - Probability function of Oscillator" ); pls.end(); } } // End of x05.java
package ro.isdc.wro.model.group.processor; import static org.apache.commons.lang3.Validate.notNull; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BOMInputStream; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.WroRuntimeException; import ro.isdc.wro.config.Context; import ro.isdc.wro.config.ReadOnlyContext; import ro.isdc.wro.config.support.ContextPropagatingCallable; import ro.isdc.wro.manager.callback.LifecycleCallbackRegistry; import ro.isdc.wro.model.group.Inject; import ro.isdc.wro.model.resource.Resource; import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory; import ro.isdc.wro.model.resource.processor.ResourcePreProcessor; import ro.isdc.wro.model.resource.processor.decorator.DefaultProcessorDecorator; import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory; import ro.isdc.wro.model.resource.processor.support.ProcessingCriteria; import ro.isdc.wro.model.resource.processor.support.ProcessingType; import ro.isdc.wro.util.WroUtil; /** * TODO: refactor this class. Apply all preProcessor on provided {@link Resource} and returns the result of execution as * String. * <p> * This is useful when you want to preProcess a resource which is not a part of the model (css import use-case). * * @author Alex Objelean */ public class PreProcessorExecutor { private static final Logger LOG = LoggerFactory.getLogger(PreProcessorExecutor.class); @Inject private UriLocatorFactory uriLocatorFactory; @Inject private ProcessorsFactory processorsFactory; @Inject private ReadOnlyContext context; @Inject private LifecycleCallbackRegistry callbackRegistry; @Inject private Injector injector; /** * Runs the preProcessing in parallel. */ private ExecutorService executor; /** * Apply preProcessors on resources and merge them after all preProcessors are applied. * * @param resources * what are the resources to merge. * @param minimize * whether minimize aware processors must be applied or not. * @return preProcessed merged content. */ public String processAndMerge(final List<Resource> resources, final boolean minimize) throws IOException { return processAndMerge(resources, ProcessingCriteria.create(ProcessingType.ALL, minimize)); } /** * Apply preProcessors on resources and merge them. * * @param resources * what are the resources to merge. * @param criteria * {@link ProcessingCriteria} used to identify the processors to apply and those to skip. * @return preProcessed merged content. */ public String processAndMerge(final List<Resource> resources, final ProcessingCriteria criteria) throws IOException { notNull(criteria); LOG.debug("criteria: {}", criteria); callbackRegistry.onBeforeMerge(); try { notNull(resources); LOG.debug("process and merge resources: {}", resources); final StringBuffer result = new StringBuffer(); if (shouldRunInParallel(resources)) { result.append(runInParallel(resources, criteria)); } else { for (final Resource resource : resources) { LOG.debug("\tmerging resource: {}", resource); result.append(applyPreProcessors(resource, criteria)); } } return result.toString(); } finally { callbackRegistry.onAfterMerge(); } } private boolean shouldRunInParallel(final List<Resource> resources) { final boolean isParallel = context.getConfig().isParallelPreprocessing(); final int availableProcessors = Runtime.getRuntime().availableProcessors(); return isParallel && resources.size() > 1 && availableProcessors > 1; } /** * runs the pre processors in parallel. * * @return merged and pre processed content. */ private String runInParallel(final List<Resource> resources, final ProcessingCriteria criteria) throws IOException { LOG.debug("Running preProcessing in Parallel"); final StringBuffer result = new StringBuffer(); final List<Callable<String>> callables = new ArrayList<Callable<String>>(); for (final Resource resource : resources) { callables.add(new Callable<String>() { public String call() throws Exception { LOG.debug("Callable started for resource: {} ...", resource); return applyPreProcessors(resource, criteria); } }); } final ExecutorService exec = getExecutorService(); final List<Future<String>> futures = new ArrayList<Future<String>>(); for (final Callable<String> callable : callables) { // decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context final Callable<String> decoratedCallable = new ContextPropagatingCallable<String>(callable); futures.add(exec.submit(decoratedCallable)); } for (final Future<String> future : futures) { try { result.append(future.get()); } catch (final Exception e) { // propagate original cause final Throwable cause = e.getCause(); if (cause instanceof WroRuntimeException) { throw (WroRuntimeException) cause; } else if (cause instanceof IOException) { throw (IOException) cause; } else { throw new WroRuntimeException("Problem during parallel pre processing", e); } } } return result.toString(); } private ExecutorService getExecutorService() { if (executor == null) { // use at most the number of available processors (true parallelism) final int threadPoolSize = Runtime.getRuntime().availableProcessors(); LOG.debug("Parallel thread pool size: {}", threadPoolSize); executor = Executors.newFixedThreadPool(threadPoolSize, WroUtil.createDaemonThreadFactory("parallelPreprocessing")); } return executor; } /** * Apply a list of preprocessors on a resource. * * @param resource * the {@link Resource} on which processors will be applied * @param processors * the list of processor to apply on the resource. */ private String applyPreProcessors(final Resource resource, final ProcessingCriteria criteria) throws IOException { final Collection<ResourcePreProcessor> processors = processorsFactory.getPreProcessors(); LOG.debug("applying preProcessors: {}", processors); String resourceContent = null; try { resourceContent = getResourceContent(resource); } catch (final IOException e) { LOG.debug("Invalid resource found: {}", resource); if (Context.get().getConfig().isIgnoreMissingResources()) { return StringUtils.EMPTY; } else { LOG.error("Cannot ignore missing resource: {}", resource); throw e; } } if (!processors.isEmpty()) { Writer writer = null; for (final ResourcePreProcessor processor : processors) { final ResourcePreProcessor decoratedProcessor = decoratePreProcessor(processor, criteria); writer = new StringWriter(); final Reader reader = new StringReader(resourceContent); // decorate and process decoratedProcessor.process(resource, reader, writer); // use the outcome for next input resourceContent = writer.toString(); } } // following block of code (if-block) provided by Umar Ali Khan 6-Feb-2016 7:00pm PST if (resourceContent.length() <= 2) { resourceContent = ""; } // add explicitly new line at the end to avoid unexpected comment issue return String.format("%s%n", resourceContent); } /** * Decorates preProcessor with mandatory decorators. * This method is synchronized to ensure that processor is injected before it is being used by other thread. */ private synchronized ResourcePreProcessor decoratePreProcessor(final ResourcePreProcessor processor, final ProcessingCriteria criteria) { final ResourcePreProcessor decorated = new DefaultProcessorDecorator(processor, criteria) { @Override public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { callbackRegistry.onBeforePreProcess(); super.process(resource, reader, writer); } finally { callbackRegistry.onAfterPreProcess(); } } }; injector.inject(decorated); return decorated; } /** * @return a Reader for the provided resource. * @param resource * {@link Resource} which content to return. * @param resources * the list of all resources processed in this context, used for duplicate resource detection. */ private String getResourceContent(final Resource resource) throws IOException { InputStream is = null; try { is = new BOMInputStream(uriLocatorFactory.locate(resource.getUri())); final String result = IOUtils.toString(is, context.getConfig().getEncoding()); if (StringUtils.isEmpty(result)) { LOG.debug("Empty resource detected: {}", resource.getUri()); } return result; } finally { IOUtils.closeQuietly(is); } } /** * Perform cleanUp on service shut down. */ public void destroy() { getExecutorService().shutdownNow(); } }
package org.knowm.xchange.kraken.service; import java.io.IOException; import java.util.Arrays; import java.util.Set; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.IOrderFlags; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.FrequencyLimitExceededException; import org.knowm.xchange.exceptions.FundsExceededException; import org.knowm.xchange.exceptions.NonceException; import org.knowm.xchange.exceptions.RateLimitExceededException; import org.knowm.xchange.kraken.KrakenAuthenticated; import org.knowm.xchange.kraken.KrakenUtils; import org.knowm.xchange.kraken.dto.KrakenResult; import org.knowm.xchange.kraken.dto.marketdata.KrakenAssets; import org.knowm.xchange.kraken.dto.marketdata.KrakenServerTime; import org.knowm.xchange.kraken.dto.marketdata.results.KrakenAssetsResult; import org.knowm.xchange.kraken.dto.marketdata.results.KrakenServerTimeResult; import org.knowm.xchange.kraken.dto.trade.KrakenOrderFlags; import org.knowm.xchange.service.BaseExchangeService; import org.knowm.xchange.service.BaseService; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.RestProxyFactory; public class KrakenBaseService extends BaseExchangeService implements BaseService { protected KrakenAuthenticated kraken; protected ParamsDigest signatureCreator; /** * Constructor * * @param exchange */ public KrakenBaseService(Exchange exchange) { super(exchange); kraken = RestProxyFactory.createProxy( KrakenAuthenticated.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig()); signatureCreator = KrakenDigest.createInstance(exchange.getExchangeSpecification().getSecretKey()); } public KrakenServerTime getServerTime() throws IOException { KrakenServerTimeResult timeResult = kraken.getServerTime(); return checkResult(timeResult); } public KrakenAssets getKrakenAssets(Currency... assets) throws IOException { KrakenAssetsResult assetPairsResult = kraken.getAssets(null, delimitAssets(assets)); return new KrakenAssets(checkResult(assetPairsResult)); } protected <R> R checkResult(KrakenResult<R> krakenResult) { if (!krakenResult.isSuccess()) { String[] errors = krakenResult.getError(); if (errors.length == 0) { throw new ExchangeException("Missing error message"); } String error = errors[0]; if ("EAPI:Invalid nonce".equals(error)) { throw new NonceException(error); } else if ("EGeneral:Temporary lockout".equals(error)) { throw new FrequencyLimitExceededException(error); } else if ("EOrder:Insufficient funds".equals(error)) { throw new FundsExceededException(error); } if ("EAPI:Rate limit exceeded".equals(error)) { throw new RateLimitExceededException(error); } throw new ExchangeException(Arrays.toString(errors)); } return krakenResult.getResult(); } protected String createDelimitedString(String[] items) { StringBuilder commaDelimitedString = null; if (items != null) { for (String item : items) { if (commaDelimitedString == null) { commaDelimitedString = new StringBuilder(item); } else { commaDelimitedString.append(",").append(item); } } } return (commaDelimitedString == null) ? null : commaDelimitedString.toString(); } protected String delimitAssets(Currency[] assets) throws IOException { StringBuilder commaDelimitedAssets = new StringBuilder(); if (assets != null && assets.length > 0) { boolean started = false; for (Currency asset : assets) { commaDelimitedAssets .append((started) ? "," : "") .append(KrakenUtils.getKrakenCurrencyCode(asset)); started = true; } return commaDelimitedAssets.toString(); } return null; } protected String delimitAssetPairs(CurrencyPair[] currencyPairs) throws IOException { String assetPairsString = null; if (currencyPairs != null && currencyPairs.length > 0) { StringBuilder delimitStringBuilder = null; for (CurrencyPair currencyPair : currencyPairs) { String krakenAssetPair = KrakenUtils.createKrakenCurrencyPair(currencyPair); if (delimitStringBuilder == null) { delimitStringBuilder = new StringBuilder(krakenAssetPair); } else { delimitStringBuilder.append(",").append(krakenAssetPair); } } assetPairsString = delimitStringBuilder.toString(); } return assetPairsString; } protected String delimitSet(Set<IOrderFlags> items) { String delimitedSetString = null; if (items != null && !items.isEmpty()) { StringBuilder delimitStringBuilder = null; for (Object item : items) { if (item instanceof KrakenOrderFlags) { if (delimitStringBuilder == null) { delimitStringBuilder = new StringBuilder(item.toString()); } else { delimitStringBuilder.append(",").append(item.toString()); } } } if (delimitStringBuilder != null) { delimitedSetString = delimitStringBuilder.toString(); } } return delimitedSetString; } }
package org.yamcs.web.rest.archive; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.api.MediaType; import org.yamcs.parameter.ParameterValueWithId; import org.yamcs.protobuf.Pvalue.ParameterData; import org.yamcs.protobuf.Pvalue.ParameterValue; import org.yamcs.protobuf.Pvalue.TimeSeries; import org.yamcs.protobuf.SchemaPvalue; import org.yamcs.protobuf.Yamcs.EndAction; import org.yamcs.protobuf.Yamcs.NamedObjectId; import org.yamcs.protobuf.Yamcs.ParameterReplayRequest; import org.yamcs.protobuf.Yamcs.ReplayRequest; import org.yamcs.protobuf.Yamcs.ReplaySpeed; import org.yamcs.protobuf.Yamcs.ReplaySpeed.ReplaySpeedType; import org.yamcs.utils.ParameterFormatter; import org.yamcs.utils.TimeEncoding; import org.yamcs.web.BadRequestException; import org.yamcs.web.HttpException; import org.yamcs.web.InternalServerErrorException; import org.yamcs.web.rest.RestHandler; import org.yamcs.web.rest.RestParameterReplayListener; import org.yamcs.web.rest.RestReplayListener; import org.yamcs.web.rest.RestRequest; import org.yamcs.web.rest.Route; import org.yamcs.web.rest.archive.RestDownsampler.Sample; import org.yamcs.xtce.FloatParameterType; import org.yamcs.xtce.IntegerParameterType; import org.yamcs.xtce.Parameter; import org.yamcs.xtce.ParameterType; import org.yamcs.xtce.XtceDb; import org.yamcs.xtceproc.XtceDbFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufOutputStream; public class ArchiveParameterRestHandler extends RestHandler { private static final Logger log = LoggerFactory.getLogger(ArchiveParameterRestHandler.class); /** * A series is a list of samples that are determined in one-pass while processing a stream result. * Final API unstable. * <p> * If no query parameters are defined, the series covers *all* data. * @param req * rest request * @throws HttpException */ @Route(path = "/api/archive/:instance/parameters/:name*/samples") public void getParameterSamples(RestRequest req) throws HttpException { String instance = verifyInstance(req, req.getRouteParam("instance")); XtceDb mdb = XtceDbFactory.getInstance(instance); Parameter p = verifyParameter(req, mdb, req.getRouteParam("name")); ParameterType ptype = p.getParameterType(); if ((ptype != null) && (!(ptype instanceof FloatParameterType) && !(ptype instanceof IntegerParameterType))) { throw new BadRequestException("Only integer or float parameters can be sampled. Got " + ptype.getTypeAsString()); } ReplayRequest.Builder rr = ReplayRequest.newBuilder().setEndAction(EndAction.QUIT); rr.setSpeed(ReplaySpeed.newBuilder().setType(ReplaySpeedType.AFAP)); NamedObjectId id = NamedObjectId.newBuilder().setName(p.getQualifiedName()).build(); rr.setParameterRequest(ParameterReplayRequest.newBuilder().addNameFilter(id)); if (req.hasQueryParameter("start")) { rr.setStart(req.getQueryParameterAsDate("start")); } rr.setStop(req.getQueryParameterAsDate("stop", TimeEncoding.getWallclockTime())); RestDownsampler sampler = new RestDownsampler(rr.getStop()); RestReplays.replay(instance, req.getAuthToken(), rr.build(), new RestReplayListener() { @Override public void onParameterData(List<ParameterValueWithId> params) { for (ParameterValueWithId pvalid : params) { sampler.process(pvalid.getParameterValue()); } } @Override public void replayFinished() { TimeSeries.Builder series = TimeSeries.newBuilder(); for (Sample s : sampler.collect()) { series.addSample(ArchiveHelper.toGPBSample(s)); } completeOK(req, series.build(), SchemaPvalue.TimeSeries.WRITE); } @Override public void replayFailed(Throwable t) { completeWithError(req, new InternalServerErrorException(t)); } }); } @Route(path = "/api/archive/:instance/parameters/:name*") public void listParameterHistory(RestRequest req) throws HttpException { String instance = verifyInstance(req, req.getRouteParam("instance")); XtceDb mdb = XtceDbFactory.getInstance(instance); String pathName = req.getRouteParam("name"); NameDescriptionWithId<Parameter> p = verifyParameterWithId(req, mdb, pathName); long pos = req.getQueryParameterAsLong("pos", 0); int limit = req.getQueryParameterAsInt("limit", 100); boolean noRepeat = req.getQueryParameterAsBoolean("norepeat", false); ReplayRequest rr = ArchiveHelper.toParameterReplayRequest(req, p.getItem(), true); if (req.asksFor(MediaType.CSV)) { ByteBuf buf = req.getChannelHandlerContext().alloc().buffer(); try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new ByteBufOutputStream(buf)))) { List<NamedObjectId> idList = Arrays.asList(p.getRequestedId()); ParameterFormatter csvFormatter = new ParameterFormatter(bw, idList); limit++; // Allow one extra line for the CSV header RestParameterReplayListener replayListener = new RestParameterReplayListener(pos, limit, req) { @Override public void onParameterData(List<ParameterValueWithId> params) { try { List<ParameterValue> pvlist = new ArrayList<>(); for(ParameterValueWithId pvalid: params) { pvlist.add(pvalid.toGbpParameterValue()); } csvFormatter.writeParameters(pvlist); } catch (IOException e) { log.error("Error while writing parameter line", e); completeWithError(req, new InternalServerErrorException(e)); } } public void replayFinished() { completeOK(req, MediaType.CSV, buf); } }; replayListener.setNoRepeat(noRepeat); RestReplays.replay(instance, req.getAuthToken(), rr, replayListener); } catch (IOException e) { throw new InternalServerErrorException(e); } } else { ParameterData.Builder resultb = ParameterData.newBuilder(); RestParameterReplayListener replayListener = new RestParameterReplayListener(pos, limit, req) { @Override public void onParameterData(List<ParameterValueWithId> params) { for(ParameterValueWithId pvalid: params) { resultb.addParameter(pvalid.toGbpParameterValue()); } } @Override public void replayFinished() { completeOK(req, resultb.build(), SchemaPvalue.ParameterData.WRITE); } }; replayListener.setNoRepeat(noRepeat); RestReplays.replay(instance, req.getAuthToken(), rr, replayListener); } } }
package io.straas.android.sdk.circall.demo; import android.databinding.ViewDataBinding; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.SystemClock; import android.support.v7.widget.ActionMenuView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Tasks; import java.util.List; import io.straas.android.sdk.circall.CircallConfig; import io.straas.android.sdk.circall.CircallManager; import io.straas.android.sdk.circall.CircallPlayerView; import io.straas.android.sdk.circall.CircallPublishConfig; import io.straas.android.sdk.circall.CircallRecordingStreamMetadata; import io.straas.android.sdk.circall.CircallStream; import io.straas.android.sdk.demo.R; import io.straas.android.sdk.demo.databinding.ActivitySingleVideoCallBinding; public class SingleVideoCallActivity extends CircallDemoBaseActivity { private static final String TAG = SingleVideoCallActivity.class.getSimpleName(); private static final int EVENT_UPDATE_RECORDING_TIME = 101; private ActivitySingleVideoCallBinding mBinding; private CircallStream mLocalCircallStream; private String mRecordingId = ""; private long mRecordingStartTimeMillis; private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper()) { public void handleMessage(Message msg) { switch(msg.what) { case EVENT_UPDATE_RECORDING_TIME: mBinding.setSeconds((SystemClock.elapsedRealtime() - mRecordingStartTimeMillis) / 1000); if (mBinding.getIsRecording()) { mMainThreadHandler.removeMessages(EVENT_UPDATE_RECORDING_TIME); mMainThreadHandler.sendEmptyMessageDelayed(EVENT_UPDATE_RECORDING_TIME, 1000); } break; } } }; // Abstract methods @Override protected String getTag() { return TAG; } @Override protected int getContentViewLayoutId() { return R.layout.activity_single_video_call; } @Override protected void setBinding(ViewDataBinding binding) { mBinding = (ActivitySingleVideoCallBinding) binding; } @Override protected void scaleScreenShotView(float scale) { mBinding.screenshot.setScaleX(scale); mBinding.screenshot.setScaleY(scale); } @Override protected void setScreenShotView(Bitmap bitmap) { mBinding.screenshot.setImageBitmap(bitmap); } @Override protected ActionMenuView getActionMenuView() { return mBinding.actionMenuView; } @Override protected Toolbar getToolbar() { return mBinding.toolbar; } @Override protected CircallPlayerView getRemoteStreamView() { return mBinding.fullscreenVideoView; } @Override protected void setShowActionButtons(boolean show) { mBinding.setShowActionButtons(show); } @Override public void onShowActionButtonsToggled(View view) { mBinding.setShowActionButtons(!mBinding.getShowActionButtons()); } @Override protected Task<CircallStream> prepare() { if (mCircallManager != null && mCircallManager.getCircallState() == CircallManager.STATE_IDLE) { return mCircallManager.prepareForCameraCapture(this, getConfig()) .addOnSuccessListener(circallStream -> { circallStream.setRenderer(mBinding.pipVideoView, getPlayConfig()); mLocalCircallStream = circallStream; }); } return Tasks.forException(new IllegalStateException()); } // Optional implementation @Override protected void onConnected() { publish(); } @Override protected void setState(int state) { super.setState(state); mBinding.setState(state); } @Override protected void setIsSubscribing(boolean isSubscribing) { super.setIsSubscribing(isSubscribing); mBinding.setIsSubscribing(isSubscribing); } @Override protected int getMenuRes() { return R.menu.single_video_call_menu_action; } @Override public boolean onMenuItemClick(MenuItem item) { if (super.onMenuItemClick(item)) { return true; } switch (item.getItemId()) { case R.id.action_switch_camera: if (mLocalCircallStream != null) { item.setIcon(R.drawable.ic_switch_camera_focus); mLocalCircallStream.switchCamera().addOnCompleteListener(success -> item.setIcon(R.drawable.ic_switch_camera)); } return true; case R.id.action_toggle_camera: if (mLocalCircallStream != null) { boolean isCameraOn = mLocalCircallStream.toggleCamera(); item.setIcon(isCameraOn ? R.drawable.ic_camera_off : R.drawable.ic_camera_on); mBinding.setIsLocalVideoOff(!isCameraOn); } return true; case R.id.action_toggle_mic: if (mLocalCircallStream != null) { boolean isMicOn = mLocalCircallStream.toggleMic(); item.setIcon(isMicOn ? R.drawable.ic_mic_off : R.drawable.ic_mic_on); } return true; default: break; } return false; } @Override protected List<Task<Void>> tasksBeforeDestroy() { List<Task<Void>> list = super.tasksBeforeDestroy(); list.add(stopRecording()); list.add(unsubscribe()); list.add(unpublish()); return list; } @Override protected String getEndTitle() { return getResources().getString(R.string.end_single_call_confirmation_title); } @Override protected String getEndMessage() { return getResources().getString(R.string.end_single_call_confirmation_message); } // EventListener @Override public void onStreamSubscribed(CircallStream stream) { if (stream == null) { return; } super.onStreamSubscribed(stream); mBinding.setIsRemoteVideoOff(!stream.isVideoEnabled()); mCircallManager.getRecordingStreamMetadata().addOnCompleteListener(this, task -> { if (task.isSuccessful() && task.getResult() != null) { for (CircallRecordingStreamMetadata recordingStream : task.getResult()) { if (TextUtils.equals(recordingStream.getStreamId(), stream.getStreamId())) { mRecordingId = recordingStream.getRecordingId(); showRecordingStartedFlashingUi(); break; } } } }); } @Override public void onStreamUpdated(CircallStream stream) { if (stream == null) { return; } mBinding.setIsRemoteVideoOff(!stream.isVideoEnabled()); } // Internal methods public void onActionRecord(View view) { if (mCircallManager == null || mCircallManager.getCircallState() != CircallManager.STATE_CONNECTED) { return; } if (mRemoteCircallStream == null) { showRecordingFailedDialog(R.string.recording_failed_message_two_way_not_ready); return; } if (!TextUtils.isEmpty(mRecordingId)) { mCircallManager.stopRecording(mRemoteCircallStream, mRecordingId).addOnCompleteListener(this, task -> { if (task.isSuccessful()) { mBinding.setIsRecording(false); mBinding.actionRecord.setImageResource(R.drawable.ic_recording_off); mRecordingId = ""; } }); } else { mCircallManager.startRecording(mRemoteCircallStream).addOnCompleteListener(this, task -> { if (task.isSuccessful()) { mRecordingId = task.getResult(); showRecordingStartedFlashingUi(); } else { showRecordingFailedDialog(R.string.recording_failed_message_not_authorized); } }); } } private void publish() { if (mCircallManager != null && mCircallManager.getCircallState() == CircallManager.STATE_CONNECTED) { mCircallManager.publishWithCameraCapture(getPublishConfig()).addOnCompleteListener(task -> { if (task.isSuccessful()) { setShowActionButtons(true); } else { Log.w(getTag(), "Publish fails: " + task.getException()); finish(); } }); } } private CircallConfig getConfig() { return new CircallConfig.Builder() .videoResolution(1280, 720) .build(); } private CircallPublishConfig getPublishConfig() { return new CircallPublishConfig.Builder() .videoMaxBitrate(780 * 1024) .audioMaxBitrate(100 * 1024) .build(); } private void showRecordingFailedDialog(int messageResId) { showFailedDialog(R.string.recording_failed_title, messageResId); } private void showRecordingStartedFlashingUi() { mBinding.setIsRecording(true); mBinding.actionRecord.setImageResource(R.drawable.ic_recording_on); mRecordingStartTimeMillis =SystemClock.elapsedRealtime(); mMainThreadHandler.removeMessages(EVENT_UPDATE_RECORDING_TIME); mMainThreadHandler.sendEmptyMessage(EVENT_UPDATE_RECORDING_TIME); } private Task<Void> stopRecording() { if (TextUtils.isEmpty(mRecordingId)) { return Tasks.forException(new IllegalStateException()); } return mCircallManager.stopRecording(mRemoteCircallStream, mRecordingId) .addOnCompleteListener(this, task -> mRecordingId = ""); } }
package configurationeditor; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.StringConverter; import javafx.util.converter.NumberStringConverter; import java.io.*; import java.net.URL; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class ReplayEnhancerUIController implements Initializable { private SimpleObjectProperty<File> JSONFile; private Configuration configuration; @FXML private VBox root; @FXML private Tab tabDrivers; @FXML private TextField txtSourceVideo; @FXML private TextField txtSourceTelemetry; @FXML private TextField txtVideoStart; @FXML private TextField txtVideoEnd; @FXML private TextField txtVideoSync; @FXML private TextField txtOutputVideo; @FXML private TextField txtHeadingFont; @FXML private TextField txtHeadingFontSize; @FXML private ColorPicker colorHeadingFontColor; @FXML private TextField txtFont; @FXML private TextField txtFontSize; @FXML private ColorPicker colorFontColor; @FXML private TextField txtMarginWidth; @FXML private TextField txtColumnMarginWidth; @FXML private TextField txtResultLines; @FXML private TextField txtBackdrop; @FXML private TextField txtLogo; @FXML private TextField txtLogoWidth; @FXML private TextField txtLogoHeight; @FXML private ColorPicker colorHeadingColor; @FXML private TextField txtHeadingLogo; @FXML private TextField txtHeadingText; @FXML private TextField txtSubheadingText; @FXML private CheckBox cbShowChampion; @FXML private TextField txtBonusPoints; @FXML private TableView<PointStructureItem> tblPointStructure; @FXML private TableColumn<PointStructureItem, Integer> colFinishPosition; @FXML private TableColumn<PointStructureItem, Integer> colPoints; @FXML private TableView<Driver> tblDrivers; @FXML private TableColumn<Driver, String> colName; @FXML private TableColumn<Driver, String> colDisplayName; @FXML private TableColumn<Driver, String> colShortName; @FXML private TableColumn<Driver, String> colCar; @FXML private TableColumn<Driver, String> colTeam; @FXML private TableColumn<Driver, Integer> colSeriesPoints; @FXML private TableView<Car> tblCars; @FXML private TableColumn<Car, String> colCarName; @FXML private TableColumn<Car, String> colClassName; @FXML private TableColumn<Car, Color> colClassColor; @FXML private Label txtFileName; @FXML private void menuFileNew() { configuration = new Configuration(); addListeners(); JSONFile = new SimpleObjectProperty<>(); } @FXML private void menuFileNewFrom() throws IOException { File file = chooseJSONFile(root); if (file != null && file.isFile()) { menuFileNew(); updateConfiguration(file, configuration); } } @FXML private void menuFileOpen() throws IOException { File file = chooseJSONFile(root); if (file != null && file.isFile()) { menuFileNew(); updateConfiguration(file, configuration); JSONFile.set(file); } } private static void updateConfiguration(File file, Configuration configuration) throws IOException { ObjectMapper mapper = new ObjectMapper(); String data = Files.lines(file.toPath()).collect(Collectors.joining()); mapper.readerForUpdating(configuration).readValue(data); } @FXML private void menuFileSave() throws IOException { if (JSONFile.get() == null) { menuFileSaveAs(); } writeJSONFile(JSONFile.get(), configuration); } private void writeJSONFile(File file, Configuration configuration) throws IOException { if (file != null) { ObjectMapper mapper = new ObjectMapper(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8")); writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(configuration)); writer.close(); } } @FXML private void menuFileSaveAs() throws IOException { Stage stage = (Stage) root.getScene().getWindow(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save Configuration File As"); fileChooser.setInitialDirectory( new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JSON", "*.json"), new FileChooser.ExtensionFilter("All Files", "*.*")); JSONFile.set(fileChooser.showSaveDialog(stage)); writeJSONFile(JSONFile.get(), configuration); } @FXML private void menuFileExit() { Stage stage = (Stage) root.getScene().getWindow(); stage.close(); } private static File chooseJSONFile(Pane root) { Stage stage = (Stage) root.getScene().getWindow(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Configuration File"); fileChooser.setInitialDirectory( new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JSON", "*.json"), new FileChooser.ExtensionFilter("All Files", "*.*")); return fileChooser.showOpenDialog(stage); } private static class ConvertTime extends StringConverter<Number> { @Override public String toString(Number object) { String returnValue = ""; Double inputValue = object.doubleValue(); String fractionalPart = object.toString().substring(object.toString().indexOf('.') + 1); if (fractionalPart.equals("0")) { returnValue = ".00"; } else { returnValue = "." + fractionalPart; } if ((int) (inputValue / 3600) > 0) { returnValue = String.format("%d", (int) (inputValue / 3600)) + ":" + String.format("%02d", (int) ((inputValue % 3600) / 60)) + ":" + String.format("%02d", (int) (inputValue % 60)) + returnValue; } else { if ((int) ((inputValue % 3600) / 60) > 0) { returnValue = String.format("%d", (int) ((inputValue % 3600) / 60)) + ":" + String.format("%02d", (int) (inputValue % 60)) + returnValue; } else { returnValue = "0:" + String.format("%02d", (int) (inputValue % 60)) + returnValue; } } return returnValue; } @Override public Number fromString(String string) { Pattern regex = Pattern.compile("(?:^(\\d*):([0-5]?\\d):([0-5]?\\d(?:\\.\\d*)?)$|^(\\d*):([0-5]?\\d(?:\\.\\d*)?)$|^(\\d*(?:\\.\\d*)?)$)"); Matcher matches = regex.matcher(string); if (!matches.matches() || string.equals("")) { return 0; } Double hours = 0d; Double minutes = 0d; Double seconds = 0d; if (matches.group(1) != null) { hours = Double.valueOf(matches.group(1)) * 60 * 60; minutes = Double.valueOf(matches.group(2)) * 60; seconds = Double.valueOf(matches.group(3)); } else if (matches.group(4) != null) { minutes = Double.valueOf(matches.group(4)) * 60; seconds = Double.valueOf(matches.group(5)); } else if (matches.group(6) != null) { seconds = Double.valueOf(matches.group(6)); } return hours + minutes + seconds; } } @FXML private void validateInteger(KeyEvent event) { Object source = event.getSource(); TextField txtSource = (TextField) source; txtSource.setStyle("-fx-text-inner-color: black"); try { Integer value = Integer.valueOf(txtSource.getText()); } catch (NumberFormatException e) { if (!txtSource.getText().equals("")) { txtSource.setStyle("-fx-text-inner-color: red"); } } } @FXML private void validateTime(KeyEvent event) { Object source = event.getSource(); TextField txtSource = (TextField) source; txtSource.setStyle("-fx-text-inner-color: black"); Pattern regex = Pattern.compile("(?:^(\\d*):([0-5]?\\d):([0-5]?\\d(?:\\.\\d*)?)$|^(\\d*):([0-5]?\\d(?:\\.\\d*)?)$|^(\\d*(?:\\.\\d*)?)$)"); Matcher match = regex.matcher(txtSource.getText()); if (!match.matches()) { txtSource.setStyle("-fx-text-inner-color: red"); } } @FXML private void buttonSourceVideo(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Source Video File"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("MP4", "*.mp4"), new FileChooser.ExtensionFilter("AVI", "*.avi"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showOpenDialog(root.getScene().getWindow()); if (file != null && file.isFile()) { configuration.setSourceVideo(file); } } @FXML private void buttonSourceTelemetry(ActionEvent event) { DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setTitle("Open Source Telemetry Directory"); directoryChooser.setInitialDirectory(new File(System.getProperty("user.home"))); File directory = directoryChooser.showDialog(root.getScene().getWindow()); if (directory != null && directory.isDirectory()) { configuration.setSourceTelemetry(directory); populateDrivers(); } } @FXML private void buttonOutputVideo(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save Output Video File"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("MP4", "*.mp4"), new FileChooser.ExtensionFilter("AVI", "*.avi"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showSaveDialog(root.getScene().getWindow()); if (file != null) { configuration.setOutputVideo(file); } } @FXML private void buttonHeadingFont(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select Heading Font"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("TTF", "*.ttf"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showOpenDialog(root.getScene().getWindow()); if (file != null && file.isFile()) { configuration.setHeadingFont(file); } } @FXML private void buttonHeadingLogo(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select Heading Logo"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("PNG", "*.png"), new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showOpenDialog(root.getScene().getWindow()); if (file != null && file.isFile()) { configuration.setSeriesLogo(file); } } @FXML private void buttonBackdrop(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select Background Image"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showOpenDialog(root.getScene().getWindow()); if (file != null && file.isFile()) { configuration.setBackdrop(file); } } @FXML private void buttonLogo(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select Background Logo"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("PNG", "*.png"), new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showOpenDialog(root.getScene().getWindow()); if (file != null && file.isFile()) { configuration.setLogo(file); } } @FXML private void buttonFont (ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select Font"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("TTF", "*.ttf"), new FileChooser.ExtensionFilter("All Files", "*.*") ); File file = fileChooser.showOpenDialog(root.getScene().getWindow()); if (file != null && file.isFile()) { configuration.setFont(file); } } @FXML private void buttonAddPosition (ActionEvent event) { int next_index = configuration.getPointStructure().size(); configuration.getPointStructure().add(new PointStructureItem(next_index, 0)); } @FXML private void buttonDeletePosition (ActionEvent event) { configuration.getPointStructure().removeAll(tblPointStructure.getSelectionModel().getSelectedItems()); Iterator<PointStructureItem> iterator = configuration.getPointStructure().iterator(); Integer index = 0; List<PointStructureItem> newItems = new ArrayList<>(); while (iterator.hasNext()) { PointStructureItem entry = iterator.next(); if (!(entry.getFinishPosition() == index)) { entry.setFinishPosition(index); newItems.add(entry); iterator.remove(); } index += 1; } configuration.getPointStructure().addAll(newItems); } @Override public void initialize(URL url, ResourceBundle rb) { JSONFile = new SimpleObjectProperty<>(); txtFileName.textProperty().bind(Bindings.convert(JSONFile)); configuration = new Configuration(); addListeners(); colFinishPosition.setCellValueFactory( new PropertyValueFactory<>("finishPosition") ); colPoints.setCellValueFactory( new PropertyValueFactory<>("points") ); colPoints.setCellFactory(param -> CustomCell.createIntegerEditCell()); colPoints.setOnEditCommit( t -> (t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setPoints(t.getNewValue()) ); colName.setCellValueFactory( new PropertyValueFactory<>("name") ); colDisplayName.setCellValueFactory( new PropertyValueFactory<>("displayName") ); colDisplayName.setCellFactory(param -> CustomCell.createStringEditCell()); colDisplayName.setOnEditCommit( t -> (t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setDisplayName(t.getNewValue()) ); colShortName.setCellValueFactory( new PropertyValueFactory<>("shortName") ); colShortName.setCellFactory(param -> CustomCell.createStringEditCell()); colShortName.setOnEditCommit( t -> (t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setShortName(t.getNewValue()) ); colCar.setCellValueFactory( param -> param.getValue().getCar() == null ? new SimpleStringProperty(null) : new SimpleStringProperty(param.getValue().getCar().getCarName()) ); colCar.setCellFactory(param -> CustomCell.createStringEditCell()); colCar.setOnEditCommit( t -> { Driver driver = t.getTableView().getItems().get(t.getTablePosition().getRow()); if (driver.getCar() == null) { driver.setCar(new Car(t.getNewValue(), new CarClass("", Color.rgb(255, 0, 0)))); } else { driver.getCar().setCarName(t.getNewValue()); } } ); colTeam.setCellValueFactory( new PropertyValueFactory<>("team") ); colTeam.setCellFactory(param -> CustomCell.createStringEditCell()); colTeam.setOnEditCommit( t -> (t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setTeam(t.getNewValue()) ); colSeriesPoints.setCellValueFactory( new PropertyValueFactory<>("seriesPoints") ); colSeriesPoints.setCellFactory(param -> CustomCell.createIntegerEditCell()); colSeriesPoints.setOnEditCommit( t -> (t.getTableView().getItems().get( t.getTablePosition().getRow()) ).setSeriesPoints(t.getNewValue()) ); colCarName.setCellValueFactory( new PropertyValueFactory<>("carName") ); colClassName.setCellValueFactory( param -> param.getValue() == null || param.getValue().getCarClass() == null ? new SimpleStringProperty(null) : new SimpleStringProperty(param.getValue().getCarClass().getClassName()) ); colClassName.setCellFactory(param -> CustomCell.createStringEditCell()); colClassName.setOnEditCommit( event -> (event.getTableView().getItems().get( event.getTablePosition().getRow()) ).getCarClass().setClassName(event.getNewValue()) ); colClassColor.setCellValueFactory( param -> param.getValue() == null || param.getValue().getCarClass() == null ? new SimpleObjectProperty<>(null) : new SimpleObjectProperty<>(param.getValue().getCarClass().getClassColor()) ); colClassColor.setCellFactory(ColorTableCell::new); colClassColor.setOnEditCommit( event -> (event.getTableView().getItems().get( event.getTablePosition().getRow()) ).getCarClass().setClassColor(event.getNewValue()) ); } private void addListeners() { // Interface tabDrivers.setDisable(true); configuration.participantConfigurationProperty().sizeProperty().addListener((observable, oldValue, newValue) -> tabDrivers.setDisable(newValue.intValue() < 1)); // Source Data txtSourceVideo.textProperty().bindBidirectional(configuration.sourceVideoProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); txtSourceTelemetry.textProperty().bindBidirectional(configuration.sourceTelemetryProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); // Source Parameters txtVideoStart.textProperty().bindBidirectional(configuration.videoStartTimeProperty(), new ConvertTime()); txtVideoEnd.textProperty().bindBidirectional(configuration.videoEndTimeProperty(), new ConvertTime()); txtVideoSync.textProperty().bindBidirectional(configuration.syncRacestartProperty(), new ConvertTime()); // Output txtOutputVideo.textProperty().bindBidirectional(configuration.outputVideoProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); // Headings txtHeadingText.textProperty().bindBidirectional(configuration.headingTextProperty()); txtSubheadingText.textProperty().bindBidirectional(configuration.subheadingTextProperty()); txtHeadingFont.textProperty().bindBidirectional(configuration.headingFontProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); txtHeadingFontSize.textProperty().bindBidirectional(configuration.headingFontSizeProperty(), new NumberStringConverter()); colorHeadingFontColor.valueProperty().bindBidirectional(configuration.headingFontColorProperty()); colorHeadingColor.valueProperty().bindBidirectional(configuration.headingColorProperty()); txtHeadingLogo.textProperty().bindBidirectional(configuration.seriesLogoProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); // Backgrounds txtBackdrop.textProperty().bindBidirectional(configuration.backdropProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); txtLogo.textProperty().bindBidirectional(configuration.logoProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); txtLogoHeight.textProperty().bindBidirectional(configuration.logoHeightProperty(), new NumberStringConverter()); txtLogoWidth.textProperty().bindBidirectional(configuration.logoWidthProperty(), new NumberStringConverter()); // Font txtFont.textProperty().bindBidirectional(configuration.fontProperty(), new StringConverter<File>() { @Override public String toString(File object) { if (object == null) { return ""; } else { try { return object.getCanonicalPath(); } catch (IOException e) { return ""; } } } @Override public File fromString(String string) { return new File(string); } }); txtFontSize.textProperty().bindBidirectional(configuration.fontSizeProperty(), new NumberStringConverter()); colorFontColor.valueProperty().bindBidirectional(configuration.fontColorProperty()); // Layout txtMarginWidth.textProperty().bindBidirectional(configuration.marginProperty(), new NumberStringConverter()); txtColumnMarginWidth.textProperty().bindBidirectional(configuration.columnMarginProperty(), new NumberStringConverter()); txtResultLines.textProperty().bindBidirectional(configuration.resultLinesProperty(), new NumberStringConverter()); // Options cbShowChampion.selectedProperty().bindBidirectional(configuration.showChampionProperty()); txtBonusPoints.textProperty().bindBidirectional(configuration.pointStructureProperty(), new StringConverter<ObservableList<PointStructureItem>>() { @Override public String toString(ObservableList<PointStructureItem> object) { return Integer.toString(object.get(0).getPoints()); } @Override public ObservableList<PointStructureItem> fromString(String string) { ObservableList<PointStructureItem> list = configuration.getPointStructure(); list.set(0, new PointStructureItem(0, Integer.valueOf(string))); return list; } }); tblPointStructure.setItems(configuration.pointStructureProperty().filtered(pointStructureItem -> pointStructureItem.getFinishPosition() > 0)); // Drivers (and teams, and cars, oh my!) tblDrivers.setItems(configuration.participantConfigurationProperty()); tblCars.setItems(configuration.carsProperty()); } private void populateDrivers() { File[] files = new File(txtSourceTelemetry.getText()).listFiles((dir, name) -> name.matches(".*pdata.*")); if (files == null) return; Arrays.sort(files, (file1, file2) -> { Integer n1 = Integer.valueOf(file1.getName().replaceAll("[^\\d]", "")); Integer n2 = Integer.valueOf(file2.getName().replaceAll("[^\\d]", "")); return Integer.compare(n1, n2); }); Set<String> names = new TreeSet<>(); for (File file : files) { if (file.length() == 1347) { try { ParticipantPacket packet = new ParticipantPacket( ByteBuffer.wrap(Files.readAllBytes(file.toPath()))); for (SimpleStringProperty name : packet.getNames()) { String trimmedName = name.get().trim(); if (trimmedName.length() > 0) { names.add(trimmedName); } } } catch (IOException ex) { ex.printStackTrace(); } } else if (file.length() == 1028) { try { AdditionalParticipantPacket packet = new AdditionalParticipantPacket( ByteBuffer.wrap(Files.readAllBytes(file.toPath()))); for (SimpleStringProperty name : packet.getNames()) { String trimmedName = name.get().trim(); if (trimmedName.length() > 0) { names.add(trimmedName); } } } catch (IOException ex) { ex.printStackTrace(); } } else if (file.length() != 1367) { System.out.println(file.length()); } } ObservableList<Driver> drivers = FXCollections.observableArrayList(param -> new Observable[]{param.getCar().carNameProperty()}); drivers.addAll(names .stream() .filter(name -> name.length() > 0) .map(Driver::new) .collect(Collectors.toList())); configuration.setParticipantConfiguration(drivers); } private class ColorTableCell<T> extends TableCell<T, Color> { private final ColorPicker colorPicker; public ColorTableCell(TableColumn<T, Color> column) { this.colorPicker = new ColorPicker(); this.colorPicker.editableProperty().bind(column.editableProperty()); this.colorPicker.disableProperty().bind(column.editableProperty().not()); this.colorPicker.setOnShowing(event -> { final TableView<T> tableView = getTableView(); tableView.getSelectionModel().select(getTableRow().getIndex()); tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column); }); this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> { if (isEditing()) { commitEdit(newValue); } }); setContentDisplay(ContentDisplay.GRAPHIC_ONLY); } @Override protected void updateItem(Color item, boolean empty) { super.updateItem(item, empty); setText(null); if (empty) { setGraphic(null); } else { this.colorPicker.setValue(item); this.setGraphic(this.colorPicker); } } } }
package fitnesse; import java.io.File; import java.util.Properties; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; public class ConfigurationParameterTest { @Test public void shouldMakePropertiesWithConfigurationParametersAndValues() { Properties properties = ConfigurationParameter.makeProperties(ConfigurationParameter.PORT, 8001, ConfigurationParameter.ROOT_PATH, ".", ConfigurationParameter.ROOT_DIRECTORY, "FitNesseRoot"); assertThat(properties.getProperty(ConfigurationParameter.PORT.getKey()), is("8001")); assertThat(properties.getProperty(ConfigurationParameter.ROOT_PATH.getKey()), is(".")); assertThat(properties.getProperty(ConfigurationParameter.ROOT_DIRECTORY.getKey()), is("FitNesseRoot")); } @Test(expected = IllegalArgumentException.class) public void shouldFailOnOddNumberOfArguments() { ConfigurationParameter.makeProperties(ConfigurationParameter.PORT, 8001, ConfigurationParameter.ROOT_PATH); } @Test public void shouldAcceptStringArgumentsInsteadOfConfigurationParameters() { Properties properties = ConfigurationParameter.makeProperties("Port", 8001); assertThat(properties.getProperty("Port"), is("8001")); } @Test public void shouldAcceptNuArguments() { Properties properties = ConfigurationParameter.makeProperties(); assertThat(properties, is(notNullValue())); } @Test public void canLoadPropertiesFromFile() { Properties properties = ConfigurationParameter.loadProperties(new File("configuration-parameter-test.properties")); assertThat(properties.getProperty("unitTestProperty"), is("found")); } }
package net.robig.stlab; import net.robig.logging.Logger; import net.robig.stlab.util.config.AbstractValue; import net.robig.stlab.util.config.BoolValue; import net.robig.stlab.util.config.DoubleValue; import net.robig.stlab.util.config.IValueChangeListener; import net.robig.stlab.util.config.IntValue; import net.robig.stlab.util.config.LongValue; import net.robig.stlab.util.config.MapValue; import net.robig.stlab.util.config.StringValue; import net.robig.stlab.util.config.ObjectConfig; /** * Easy type save access to all used config parameters * * @author robegroe * */ public class StLabConfig extends ObjectConfig { static final Logger log = new Logger(StLabConfig.class); static String environment = null; public static String getEnvironment() { if(environment==null) environment=getStringValue("environment", "production").getValue(); if(environment.equals("")) environment="production"; return environment; } public static String getEnvironmentString() { String env=getEnvironment(); if(env.equals("production")) return ""; return " ("+env+")"; } public static String getWebUrl(){ if(getEnvironment().equals("DIT")) return "http://robig.net/stlab-dit/"; if(getEnvironment().equals("UAT")) return "http://robig.net/stlab-uat/"; return "http://stlab.robig.net/"; } public static String getTaCUrl(){ return "http://robig.net/redmine/projects/stlab/wiki/StlabWebTaC"; } public static String getFeedbackUrl(){ return "http://sourceforge.net/apps/phpbb/stlab/"; } public static String getAboutUrl(){ return "http://robig.net/wiki/?wiki=EnStLab"; } // System.getProperties().put( "proxySet", "true" ); // System.getProperties().put( "proxyHost", "192.168.100.2" ); // System.getProperties().put( "proxyPort", "8080" ); public static StringValue getWebProxyHost(){ StringValue v=getStringValue("web.proxy.host", ""); IValueChangeListener l = new IValueChangeListener() { @SuppressWarnings("unchecked") @Override public void valueChanged(AbstractValue av) { if(StLabConfig.isWebProxyEnabled().getSimpleValue()){ log.info("Setting proxy host: "+av.toString()); System.getProperties().put( "proxyHost", av.toString() ); } } }; l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static IntValue getWebProxyPort() { IntValue v=getIntValue("web.proxy.port", 8080); IValueChangeListener l = new IValueChangeListener() { @Override public void valueChanged(AbstractValue av) { log.info("Setting proxy port: "+av.toString()); System.getProperties().put( "proxyPort", av.toString() ); } }; l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static BoolValue isWebProxyEnabled(){ final BoolValue v=getBoolValue("web.proxy.enabled", false); IValueChangeListener l = new IValueChangeListener() { @Override public void valueChanged(AbstractValue av) { boolean e=v.getSimpleValue(); log.info((e?"Enabled":"Disabled")+" proxy"); System.getProperties().put( "proxySet", (e?"true":"false") ); if(!e){ System.getProperties().remove( "proxyPort" ); System.getProperties().remove( "proxyHost" ); } } }; l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static boolean isUpdateCheckEnabled() { return getCheckForUpdates().getValue(); } public static BoolValue getCheckForUpdates() { return getBoolValue("startup.checkforupdates", true); } public static IntValue getMouseSensitivity() { return getIntValue("knobs.mouse.sensitivity",150); } public static void setMouseSensitivity(int value) { setIntValue("knobs.mouse.sensitivity",value); } public static DoubleValue getMouseWheelSensitivity() { return getDoubleValue("knobs.mousewheel.sensitivity",1.0); } public static void setMouseWheelSensitivity(double value) { setDoubleValue("knobs.mousewheel.sensitivity",value); } public static MapValue getAuthorInfo() { return (MapValue) getAbstractValue("preset.author", new MapValue("preset.author")); } public static StringValue getAuthor(){ return getStringValue("preset.author.name", System.getProperty("user.name")); } public static BoolValue getPresetListWindowVisible() { return getBoolValue("presetlist.visible", false); } public static IntValue getPresetListWindowWidth(){ return getIntValue("presetlist.width", 650); } public static IntValue getPresetListWindowHeight(){ return getIntValue("presetlist.height", 450); } public static IntValue getPresetListWindowX(){ return getIntValue("presetlist.x", 0); } public static IntValue getPresetListWindowY(){ return getIntValue("presetlist.y", 0); } public static IntValue getLiveWindowX(){ return getIntValue("livewindow.x", 0); } public static IntValue getLiveWindowY(){ return getIntValue("livewindow.y", 0); } /** Get last Directory */ public static StringValue getPresetsDirectory() { return getStringValue("directory.presets", ""); } /** Should the selected preset transfered directly to the device? */ public static BoolValue getOpenDialogActivatePresetOnSelection(){ return getBoolValue("opendialog.activate.presets", true); } public static StringValue getWebUsername() { return getStringValue("stlab-web.username", ""); } public static BoolValue isSpaceSwitchesPresetListEnabled(){ return getBoolValue("presetlist.space.switch", true); } }
package cpw.mods.fml.common; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import com.google.common.base.Joiner; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import cpw.mods.fml.common.LoaderState.ModState; import cpw.mods.fml.common.event.FMLLoadEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLStateEvent; public class LoadController { private Loader loader; private EventBus masterChannel; private ImmutableMap<String,EventBus> eventChannels; private LoaderState state; private Multimap<String, ModState> modStates = ArrayListMultimap.create(); private Multimap<String, Throwable> errors = ArrayListMultimap.create(); private Map<String, ModContainer> modList; private List<ModContainer> activeModList = Lists.newArrayList(); private ModContainer activeContainer; private BiMap<ModContainer, Object> modObjectList; public LoadController(Loader loader) { this.loader = loader; this.masterChannel = new EventBus("FMLMainChannel"); this.masterChannel.register(this); state = LoaderState.NOINIT; } @Subscribe public void buildModList(FMLLoadEvent event) { this.modList = loader.getIndexedModList(); Builder<String, EventBus> eventBus = ImmutableMap.builder(); for (ModContainer mod : loader.getModList()) { EventBus bus = new EventBus(mod.getModId()); boolean isActive = mod.registerBus(bus, this); if (isActive) { FMLLog.fine("Activating mod %s", mod.getModId()); activeModList.add(mod); modStates.put(mod.getModId(), ModState.UNLOADED); eventBus.put(mod.getModId(), bus); } else { FMLLog.warning("Mod %s has been disabled through configuration", mod.getModId()); modStates.put(mod.getModId(), ModState.UNLOADED); modStates.put(mod.getModId(), ModState.DISABLED); } } eventChannels = eventBus.build(); } public void distributeStateMessage(LoaderState state, Object... eventData) { if (state.hasEvent()) { masterChannel.post(state.getEvent(eventData)); } } public void transition(LoaderState desiredState) { LoaderState oldState = state; state = state.transition(!errors.isEmpty()); if (state != desiredState) { FMLLog.severe("Fatal errors were detected during the transition from %s to %s. Loading cannot continue", oldState, desiredState); StringBuilder sb = new StringBuilder(); printModStates(sb); FMLLog.severe(sb.toString()); FMLLog.severe("The following problems were captured during this phase"); for (Entry<String, Throwable> error : errors.entries()) { FMLLog.log(Level.SEVERE, error.getValue(), "Caught exception from %s", error.getKey()); } // Throw embedding the first error (usually the only one) throw new LoaderException(errors.values().iterator().next()); } } public ModContainer activeContainer() { return activeContainer; } @Subscribe public void propogateStateMessage(FMLStateEvent stateEvent) { if (stateEvent instanceof FMLPreInitializationEvent) { modObjectList = buildModObjectList(); } for (ModContainer mc : activeModList) { activeContainer = mc; String modId = mc.getModId(); stateEvent.applyModContainer(activeContainer()); FMLLog.finer("Posting state event %s to mod %s", stateEvent.getEventType(), modId); eventChannels.get(modId).post(stateEvent); FMLLog.finer("State event %s delivered to mod %s", stateEvent.getEventType(), modId); activeContainer = null; if (!errors.containsKey(modId)) { modStates.put(modId, stateEvent.getModState()); } else { modStates.put(modId, ModState.ERRORED); } } } public ImmutableBiMap<ModContainer, Object> buildModObjectList() { ImmutableBiMap.Builder<ModContainer, Object> builder = ImmutableBiMap.<ModContainer, Object>builder(); for (ModContainer mc : activeModList) { if (!mc.isImmutable() && mc.getMod()!=null) { builder.put(mc, mc.getMod()); } if (mc.getMod()==null && !mc.isImmutable() && state!=LoaderState.CONSTRUCTING) { FMLLog.severe("There is a severe problem with %s - it appears not to have constructed correctly", mc.getModId()); if (state != LoaderState.CONSTRUCTING) { this.errorOccurred(mc, new RuntimeException()); } } } return builder.build(); } public void errorOccurred(ModContainer modContainer, Throwable exception) { errors.put(modContainer.getModId(), exception); } public void printModStates(StringBuilder ret) { for (ModContainer mc : loader.getModList()) { ret.append("\n\t").append(mc.getModId()).append(" [").append(mc.getName()).append("] (").append(mc.getSource().getName()).append(") "); Joiner.on("->"). appendTo(ret, modStates.get(mc.getModId())); } } public List<ModContainer> getActiveModList() { return activeModList; } public ModState getModState(ModContainer selectedMod) { return Iterables.getLast(modStates.get(selectedMod.getModId()), ModState.AVAILABLE); } public void distributeStateMessage(Class<?> customEvent) { try { masterChannel.post(customEvent.newInstance()); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "An unexpected exception"); throw new LoaderException(e); } } public BiMap<ModContainer, Object> getModObjectList() { if (modObjectList == null) { FMLLog.severe("Detected an attempt by a mod %s to perform game activity during mod construction. This is a serious programming error.", activeContainer); return buildModObjectList(); } return ImmutableBiMap.copyOf(modObjectList); } public boolean isInState(LoaderState state) { return this.state == state; } }
package oe.block.tile; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.packet.Packet250CustomPayload; import net.minecraft.tileentity.TileEntity; import oe.api.OETileInterface; import oe.api.lib.OEType; import oe.lib.Debug; import oe.lib.util.ConfigUtil; import oe.lib.util.Util; import oe.qmc.QMC; import cpw.mods.fml.common.network.PacketDispatcher; public class TileCondenser extends TileEntity implements IInventory, ISidedInventory, OETileInterface { public ItemStack[] chestContents; public final int size = 28; public double stored; private double prevStored; private int ticks; public boolean hasTarget; public int percent = 0; // CLIENT SIDE public boolean[] isDifferent = new boolean[size]; public boolean shouldEat = false; public TileCondenser() { super(); ConfigUtil.load(); shouldEat = ConfigUtil.other("block", "Condenser turns items other than the target into QMC", false); ConfigUtil.save(); this.chestContents = new ItemStack[getSizeInventory()]; } @Override public void onInventoryChanged() { sendChangeToClients(); } @Override public void updateEntity() { updateDifferent(); if (Util.isServerSide()) { onInventoryChanged(); if (worldObj.getBlockPowerInput(xCoord, yCoord, zCoord) == 0) { if (prevStored != stored) { onInventoryChanged(); } ticks++; if (ticks > 5) { ticks = 1; prevStored = stored; } for (int i = 1; i <= 4; i++) { if (getStackInSlot(0) != null) { ItemStack target = getStackInSlot(0).copy(); target.stackSize = 1; if (QMC.hasQMC(target)) { hasTarget = true; onInventoryChanged(); double V = QMC.getQMC(target); if (stored >= V) { if (incrTarget()) { stored = stored - V; onInventoryChanged(); } } } else { hasTarget = false; onInventoryChanged(); } } updateDifferent(); if (shouldEat) { int slot = ValueSlot(); if (slot == -1) { return; } ItemStack itemstack = getStackInSlot(slot).copy(); if (itemstack == null) { return; } double V = QMC.getQMC(itemstack); stored = stored + V; decrStackSize(slot, 1); sendChangeToClients(); } } } } else { if (getStackInSlot(0) != null) { ItemStack target = getStackInSlot(0).copy(); target.stackSize = 1; if (QMC.hasQMC(target)) { double V = QMC.getQMC(target); double per = stored / V; per = 100 * per; this.percent = (int) per; return; } } } } private void updateDifferent() { boolean state; for (int i = 1; i < size; i++) { state = true; if (chestContents[i] != null && chestContents[0] != null) { if (chestContents[i].itemID == chestContents[0].itemID) { if (chestContents[i].getItemDamage() == chestContents[0].getItemDamage()) { state = false; } } } isDifferent[i] = state; } } public ItemStack[] getContents() { return chestContents; } @Override public int getSizeInventory() { return size; } @Override public String getInvName() { return "container." + this.getClass().getSimpleName().substring(4); } @Override public ItemStack getStackInSlot(int i) { return chestContents[i]; } @Override public void closeChest() { onInventoryChanged(); } @Override public void openChest() { onInventoryChanged(); } @Override public ItemStack decrStackSize(int slotnum, int x) { if (chestContents[slotnum] != null) { if (chestContents[slotnum].stackSize <= x) { ItemStack itemstack = chestContents[slotnum]; chestContents[slotnum] = null; onInventoryChanged(); return itemstack; } ItemStack itemstack1 = chestContents[slotnum].splitStack(x); if (chestContents[slotnum].stackSize == 0) { chestContents[slotnum] = null; } onInventoryChanged(); return itemstack1; } else { return null; } } public boolean incrTarget() { if (chestContents[0] != null) { int slot = -1; for (int i = 1; i < size; i++) { if (chestContents[i] != null) { ItemStack tmp = getStackInSlot(i).copy(); if (!isDifferent[i] && slot == -1 && tmp.getMaxStackSize() > tmp.stackSize && QMC.getQMC(getStackInSlot(i)) + stored <= getMaxQMC()) { slot = i; } } } if (slot != -1) { chestContents[slot].stackSize++; onInventoryChanged(); return true; } int free = freeSlot(); if (free != -1) { ItemStack tmp = chestContents[0].copy(); tmp.stackSize = 0; setInventorySlotContents(free, tmp); } } return false; } public int freeSlot() { for (int i = 1; i < size; i++) { if (chestContents[i] == null) { return i; } } return -1; } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { chestContents[i] = itemstack; if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { itemstack.stackSize = getInventoryStackLimit(); } onInventoryChanged(); } @Override public void readFromNBT(NBTTagCompound TagCompound) { super.readFromNBT(TagCompound); NBTTagList TagList = TagCompound.getTagList("Items"); chestContents = new ItemStack[getSizeInventory()]; for (int i = 0; i < TagList.tagCount(); i++) { NBTTagCompound nbttagcompound1 = (NBTTagCompound) TagList.tagAt(i); int j = nbttagcompound1.getByte("Slot") & 0xff; if (j >= 0 && j < chestContents.length) { chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); } } stored = TagCompound.getDouble("OE_Stored_Value"); } @Override public void writeToNBT(NBTTagCompound TagCompound) { super.writeToNBT(TagCompound); NBTTagList TagList = new NBTTagList(); for (int i = 0; i < chestContents.length; i++) { if (chestContents[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte) i); chestContents[i].writeToNBT(nbttagcompound1); TagList.appendTag(nbttagcompound1); } } TagCompound.setTag("Items", TagList); TagCompound.setDouble("OE_Stored_Value", stored); } @Override public int getInventoryStackLimit() { return 64; } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { if (worldObj == null) { return true; } if (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this) { return false; } return entityplayer.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <= 64D; } private int ValueSlot() { if (getStackInSlot(0) != null) { ItemStack target = getStackInSlot(0).copy(); target.stackSize = 1; for (int slot = 1; slot < size; slot++) { if (getStackInSlot(slot) != null) { if (QMC.hasQMC(getStackInSlot(slot)) && isDifferent[slot]) { return slot; } } } } return -1; } @Override public boolean isItemValidForSlot(int slot, ItemStack itemstack) { return true; } @Override public boolean isInvNameLocalized() { return false; } @Override public ItemStack getStackInSlotOnClosing(int par1) { if (this.chestContents[par1] != null) { ItemStack var2 = this.chestContents[par1]; this.chestContents[par1] = null; return var2; } else { return null; } } public void sendChangeToClients() { ByteArrayOutputStream bos = new ByteArrayOutputStream(8); DataOutputStream outputStream = new DataOutputStream(bos); try { outputStream.writeInt(10); outputStream.writeInt(this.xCoord); outputStream.writeInt(this.yCoord); outputStream.writeInt(this.zCoord); outputStream.writeDouble(this.stored); outputStream.writeBoolean(this.hasTarget); } catch (Exception ex) { Debug.handleException(ex); } Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "oe"; packet.data = bos.toByteArray(); packet.length = bos.size(); PacketDispatcher.sendPacketToAllAround(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, 64, worldObj.provider.dimensionId, packet); } @Override public int[] getAccessibleSlotsFromSide(int side) { if (side == 1) { int[] tmp = { 0 }; return tmp; // } else if (side == 0) { // return targetCopyExtract(); } else { int[] tmp = { 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 }; return tmp; } } @Override public boolean canInsertItem(int slot, ItemStack itemstack, int side) { if (side == 1 && slot == 0) { return true; } else if (side == 0) { boolean s = false; for (int i = 0; i < targetCopyExtract().length; i++) { if (targetCopyExtract()[i] == slot) { s = true; } } return s; } else if (side != 0 && slot > 0 && slot < size) { return true; } return false; } @Override public boolean canExtractItem(int slot, ItemStack itemstack, int side) { if (side == 1 && slot == 0) { return true; } else if (side == 0) { boolean s = false; for (int i = 0; i < targetCopyExtract().length; i++) { if (targetCopyExtract()[i] == slot) { s = true; } } return s; } else if (side != 0 && slot > 0 && slot < size) { return true; } return false; } public int[] targetCopyExtract() { int[] tmp = new int[numTargetCopies()]; if (tmp.length == 0) { return new int[] {}; } int l = 0; for (int i = 1; i < size; i++) { if (!isDifferent[i]) { tmp[l] = i; l++; } } return tmp; } public int numTargetCopies() { int tmp = 0; for (int i = 1; i < size; i++) { if (!isDifferent[i]) { tmp++; } } return tmp; } @Override public double getQMC() { return stored; } @Override public void setQMC(double value) { if (value > getMaxQMC()) { stored = getMaxQMC(); } else if (stored < 0) { stored = 0; } else { stored = value; } onInventoryChanged(); } @Override public void increaseQMC(double value) { stored = stored + value; if (stored > getMaxQMC()) { stored = getMaxQMC(); } else if (stored < 0) { stored = 0; } onInventoryChanged(); } @Override public void decreaseQMC(double value) { stored = stored - value; if (stored < 0) { stored = 0; } onInventoryChanged(); } @Override public double getMaxQMC() { return 10000000; } @Override public int getTier() { return 2; } @Override public OEType getType() { if (chestContents[0] != null) { return OEType.Consumer; } else { return OEType.None; } } }
/* $Log$ Revision 1.20 1998/11/15 23:08:24 rimassa Added a new KillContainerBehaviour to support 'kill-container' AMS action. Revision 1.19 1998/11/09 00:24:29 rimassa Replaced older container ID with newer container name. Added code to send a snapshot of Agent Platform state (active agent containers and agent list on every container) to each newly registered Remote Management Agent. Revision 1.18 1998/11/05 23:36:31 rimassa Added a deregisterRMABehaviour to listen to 'cancel' messages from registered Remote Management Agents. Revision 1.17 1998/11/03 00:37:33 rimassa Added AMS event notification to the Remote Management Agent. Now the AMS picks up AgentPlatform events from synchronized buffers and forwards them to RMA agent for GUI update. Revision 1.16 1998/11/02 02:04:29 rimassa Added two new Behaviours to support AMS <-> RMA interactions. The first Behaviour listens for incoming 'subscribe' messages from RMA agents and adds them to a sequence of listeners. The second one forwards to registered listeners each notification the AgentPlatforrm sends to the AMS (for example, the AgentPlatform informs AMS whenever a new agent container is added or removed to tha AgentPlatform). Revision 1.15 1998/11/01 14:59:56 rimassa Added a new Behaviour to support Remote Management Agent registration. Revision 1.14 1998/10/31 16:43:10 rimassa Implemented 'kill-agent' action through a suitable Behaviour; now both an agent name and a password are recognized in action content. Currently the password is ignored. Revision 1.13 1998/10/26 22:38:44 Giovanni Modified AMS Behaviour for action 'create-agent': now the syntax of the "Proposal for an extension of the Agent Management specifications" is used in 'create-agent' action content. Revision 1.12 1998/10/26 00:08:47 rimassa Added two new Behaviours to support new 'create-agent' and 'kill-agent' actions. Some modifications to AMSBehaviour abstract base class to use it with the two new subclasses, which have different parameters. Now the AMS is just like the DF, which has 'search' action with different parameters. Revision 1.11 1998/10/04 18:01:36 rimassa Added a 'Log:' field to every source file. */ package jade.domain; import java.io.StringReader; import java.io.StringWriter; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.Vector; import jade.core.*; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; public class ams extends Agent { private abstract class AMSBehaviour extends OneShotBehaviour implements BehaviourPrototype { // This Action will be set by crackMessage() private AgentManagementOntology.AMSAction myAction; private String myActionName; private ACLMessage myRequest; private ACLMessage myReply; protected AgentManagementOntology myOntology; protected AMSBehaviour(String name) { super(ams.this); myActionName = name; myRequest = null; myReply = null; myOntology = AgentManagementOntology.instance(); } protected AMSBehaviour(String name, ACLMessage request, ACLMessage reply) { super(ams.this); myActionName = name; myRequest = request; myReply = reply; myOntology = AgentManagementOntology.instance(); } protected void checkMandatory(AgentManagementOntology.AMSAgentDescriptor amsd) throws FIPAException { // Make sure mandatory attributes for the current AMS // action are non-null checkAttribute(AgentManagementOntology.AMSAgentDescriptor.NAME, amsd.getName()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.ADDRESS, amsd.getAddress()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.SIGNATURE, amsd.getSignature()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.APSTATE, amsd.getAPState()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.DELEGATE, amsd.getDelegateAgentName()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.FORWARD, amsd.getForwardAddress()); checkAttribute(AgentManagementOntology.AMSAgentDescriptor.OWNERSHIP, amsd.getOwnership()); } // This method throws a FIPAException if the attribute is // mandatory for the current AMS action but it is a null object // reference private void checkAttribute(String attributeName, String attributeValue) throws FIPAException { if(myOntology.isMandatoryForAMS(myAction.getName(), attributeName) && (attributeValue == null)) throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } // This method parses the message content and puts // 'FIPA-AMS-description' attribute values in instance // variables. If some error is found a FIPA exception is thrown private void crackMessage() throws FIPAException, NoSuchElementException { String content = myRequest.getContent(); // Remove 'action ams' from content string content = content.substring(content.indexOf("ams") + 3); // FIXME: AMS could crash for a bad msg // Obtain an AMS action from message content try { myAction = AgentManagementOntology.AMSAction.fromText(new StringReader(content)); } catch(ParseException pe) { // pe.printStackTrace(); throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } catch(TokenMgrError tme) { // tme.printStackTrace(); throw myOntology.getException(AgentManagementOntology.Exception.UNRECOGNIZEDATTR); } } // Each concrete subclass will implement this deferred method to // do action-specific work protected abstract void processAction(AgentManagementOntology.AMSAction a) throws FIPAException; public void action() { try { // Convert message from untyped keyword/value list to a Java // object throwing a FIPAException in case of errors crackMessage(); // Do real action, deferred to subclasses processAction(myAction); } catch(FIPAException fe) { // FIXME: Sometimes 'unable-to-deregister' in response to deregisterWithAMS() happens // fe.printStackTrace(); sendRefuse(myReply, fe.getMessage()); } catch(NoSuchElementException nsee) { // nsee.printStackTrace(); sendRefuse(myReply, AgentManagementOntology.Exception.UNRECOGNIZEDVALUE); } } // The following methods handle the various possibilities arising in // AMS <-> Agent interaction. They all receive an ACL message as an // argument, most of whose fields have already been set. Only the // message type and message content have to be filled in. // Send a 'not-understood' message back to the requester protected void sendNotUnderstood(ACLMessage msg) { msg.setType("not-understood"); msg.setContent(""); send(msg); } // Send a 'refuse' message back to the requester protected void sendRefuse(ACLMessage msg, String reason) { msg.setType("refuse"); msg.setContent("( action ams " + myActionName + " ) " + reason); send(msg); } // Send a 'failure' message back to the requester protected void sendFailure(ACLMessage msg, String reason) { msg.setType("failure"); msg.setContent("( action ams " + myActionName + " ) " + reason); send(msg); } // Send an 'agree' message back to the requester protected void sendAgree(ACLMessage msg) { msg.setType("agree"); msg.setContent("( action ams " + myActionName + " )"); send(msg); } // Send an 'inform' message back to the requester protected void sendInform(ACLMessage msg) { msg.setType("inform"); msg.setContent("( done ( " + myActionName + " ) )"); send(msg); } } // End of AMSBehaviour class // These four concrete classes serve both as a Prototype and as an // Instance: when seen as BehaviourPrototype they can spawn a new // Behaviour to process a given request, and when seen as // Behaviour they process their request and terminate. private class AuthBehaviour extends AMSBehaviour { public AuthBehaviour() { super(AgentManagementOntology.AMSAction.AUTHENTICATE); } public AuthBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.AUTHENTICATE, request, reply); } public Behaviour instance(ACLMessage msg, ACLMessage reply) { return new AuthBehaviour(msg, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); String agentName = amsd.getName(); if(agentName != null) myPlatform.AMSDumpData(agentName); else myPlatform.AMSDumpData(); throw myOntology.getException(AgentManagementOntology.Exception.UNWILLING); // FIXME: Not Implemented } } // End of AuthBehaviour class private class RegBehaviour extends AMSBehaviour { public RegBehaviour() { super(AgentManagementOntology.AMSAction.REGISTERAGENT); } public RegBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.REGISTERAGENT, request, reply); } public Behaviour instance(ACLMessage msg, ACLMessage reply) { return new RegBehaviour(msg, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); // Write new agent data in Global Agent Descriptor Table try { myPlatform.AMSNewData(amsd.getName(), amsd.getAddress(), amsd.getSignature(),amsd.getAPState(), amsd.getDelegateAgentName(), amsd.getForwardAddress(), amsd.getOwnership()); sendAgree(myReply); sendInform(myReply); } catch(AgentAlreadyRegisteredException aare) { sendAgree(myReply); sendFailure(myReply, aare.getMessage()); } } } // End of RegBehaviour class private class DeregBehaviour extends AMSBehaviour { public DeregBehaviour() { super(AgentManagementOntology.AMSAction.DEREGISTERAGENT); } public DeregBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.DEREGISTERAGENT, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new DeregBehaviour(request, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); // Remove the agent data from Global Descriptor Table myPlatform.AMSRemoveData(amsd.getName(), amsd.getAddress(), amsd.getSignature(), amsd.getAPState(), amsd.getDelegateAgentName(), amsd.getForwardAddress(), amsd.getOwnership()); sendAgree(myReply); sendInform(myReply); } } // End of DeregBehaviour class private class ModBehaviour extends AMSBehaviour { public ModBehaviour() { super(AgentManagementOntology.AMSAction.MODIFYAGENT); } public ModBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.MODIFYAGENT, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new ModBehaviour(request, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); checkMandatory(amsd); // Modify agent data from Global Descriptor Table myPlatform.AMSChangeData(amsd.getName(), amsd.getAddress(), amsd.getSignature(), amsd.getAPState(), amsd.getDelegateAgentName(), amsd.getForwardAddress(), amsd.getOwnership()); sendAgree(myReply); sendInform(myReply); } } // End of ModBehaviour class // These Behaviours handle interactions with Remote Management Agent. private class RegisterRMABehaviour extends CyclicBehaviour { private MessageTemplate subscriptionTemplate; RegisterRMABehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage("SL"); MessageTemplate mt2 = MessageTemplate.MatchOntology("jade-agent-management"); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("RMA-subscription"); mt2 = MessageTemplate.MatchType("subscribe"); subscriptionTemplate = MessageTemplate.and(mt1, mt2); subscriptionTemplate = MessageTemplate.and(subscriptionTemplate, mt12); } public void action() { // Receive 'subscribe' ACL messages. ACLMessage current = receive(subscriptionTemplate); if(current != null) { // FIXME: Should parse 'iota ?x ...' // Get new RMA name from subscription message String newRMA = current.getSource(); // Send back the whole container list. Enumeration e = myPlatform.AMSContainerNames(); while(e.hasMoreElements()) { String containerName = (String)e.nextElement(); AgentManagementOntology.AMSContainerEvent ev = new AgentManagementOntology.AMSContainerEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWCONTAINER); ev.setContainerName(containerName); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setDest(newRMA); RMANotification.setContent(w.toString()); send(RMANotification); } // Send all agent names, along with their container name. e = myPlatform.AMSAgentNames(); while(e.hasMoreElements()) { String agentName = (String)e.nextElement(); String containerName = myPlatform.AMSGetContainerName(agentName); String agentAddress = myPlatform.AMSGetAddress(agentName); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(agentName + '@' + agentAddress); // FIXME: 'agentName' should contain the address, too. amsd.setAddress(agentAddress); amsd.setAPState(Agent.AP_ACTIVE); AgentManagementOntology.AMSAgentEvent ev = new AgentManagementOntology.AMSAgentEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWAGENT); ev.setContainerName(containerName); ev.setAgentDescriptor(amsd); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); RMANotification.setDest(newRMA); send(RMANotification); } // Add the new RMA to RMAs agent group. RMAs.addMember(newRMA); } else block(); } } // End of RegisterRMABehaviour class private class DeregisterRMABehaviour extends CyclicBehaviour { private MessageTemplate cancellationTemplate; DeregisterRMABehaviour() { MessageTemplate mt1 = MessageTemplate.MatchLanguage("SL"); MessageTemplate mt2 = MessageTemplate.MatchOntology("jade-agent-management"); MessageTemplate mt12 = MessageTemplate.and(mt1, mt2); mt1 = MessageTemplate.MatchReplyWith("RMA-cancellation"); mt2 = MessageTemplate.MatchType("cancel"); cancellationTemplate = MessageTemplate.and(mt1, mt2); cancellationTemplate = MessageTemplate.and(cancellationTemplate, mt12); } public void action() { // Receive 'cancel' ACL messages. ACLMessage current = receive(cancellationTemplate); if(current != null) { // FIXME: Should parse 'iota ?x ...' // Remove this RMA to RMAs agent group. RMAs.removeMember(current.getSource()); } else block(); } } // End of DeregisterRMABehaviour class private class NotifyRMAsBehaviour extends CyclicBehaviour { private void processNewContainers() { Enumeration e = newContainersBuffer.elements(); while(e.hasMoreElements()) { String name = (String)e.nextElement(); AgentManagementOntology.AMSContainerEvent ev = new AgentManagementOntology.AMSContainerEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWCONTAINER); ev.setContainerName(name); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); newContainersBuffer.removeElement(name); } } private void processDeadContainers() { Enumeration e = deadContainersBuffer.elements(); while(e.hasMoreElements()) { String name = (String)e.nextElement(); AgentManagementOntology.AMSContainerEvent ev = new AgentManagementOntology.AMSContainerEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.DEADCONTAINER); ev.setContainerName(name); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); deadContainersBuffer.removeElement(name); } } private void processNewAgents() { Enumeration e = newAgentsBuffer.elements(); while(e.hasMoreElements()) { AgDesc ad = (AgDesc)e.nextElement(); AgentManagementOntology.AMSAgentEvent ev = new AgentManagementOntology.AMSAgentEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.NEWAGENT); ev.setContainerName(ad.containerName); ev.setAgentDescriptor(ad.amsd); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); newAgentsBuffer.removeElement(ad); } } private void processDeadAgents() { Enumeration e = deadAgentsBuffer.elements(); while(e.hasMoreElements()) { AgDesc ad = (AgDesc)e.nextElement(); AgentManagementOntology.AMSAgentEvent ev = new AgentManagementOntology.AMSAgentEvent(); ev.setKind(AgentManagementOntology.AMSContainerEvent.DEADAGENT); ev.setContainerName(ad.containerName); ev.setAgentDescriptor(ad.amsd); StringWriter w = new StringWriter(); ev.toText(w); RMANotification.setContent(w.toString()); send(RMANotification, RMAs); deadAgentsBuffer.removeElement(ad); } } public void action() { // Look into the event buffers with AgentPlatform and send // appropriate ACL messages to registered RMAs // Mutual exclusion with postXXX() methods synchronized(ams.this) { processNewContainers(); processDeadContainers(); processNewAgents(); processDeadAgents(); } block(); } } // End of NotifyRMAsBehaviour class private class KillContainerBehaviour extends AMSBehaviour { KillContainerBehaviour() { super(AgentManagementOntology.AMSAction.KILLCONTAINER); } KillContainerBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.KILLCONTAINER, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new KillContainerBehaviour(request, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { // Make sure it is RMA that's calling String peerName = myRequest.getSource(); if(!peerName.equalsIgnoreCase("RMA")) throw myOntology.getException(AgentManagementOntology.Exception.UNAUTHORISED); // Obtain container name and ask AgentPlatform to kill it AgentManagementOntology.KillContainerAction kca = (AgentManagementOntology.KillContainerAction)a; String containerName = kca.getContainerName(); myPlatform.AMSKillContainer(containerName); } } private class CreateBehaviour extends AMSBehaviour { CreateBehaviour() { super(AgentManagementOntology.AMSAction.CREATEAGENT); } CreateBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.CREATEAGENT, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new CreateBehaviour(request, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { // Make sure it is RMA that's calling String peerName = myRequest.getSource(); if(!peerName.equalsIgnoreCase("RMA")) throw myOntology.getException(AgentManagementOntology.Exception.UNAUTHORISED); AgentManagementOntology.CreateAgentAction caa = (AgentManagementOntology.CreateAgentAction)a; String className = caa.getClassName(); String containerName = caa.getProperty(AgentManagementOntology.CreateAgentAction.CONTAINER); // Create a new agent AgentManagementOntology.AMSAgentDescriptor amsd = a.getArg(); myPlatform.AMSCreateAgent(amsd.getName(), className, containerName); sendAgree(myReply); sendInform(myReply); } } // End of CreateBehaviour class private class KillBehaviour extends AMSBehaviour { KillBehaviour() { super(AgentManagementOntology.AMSAction.KILLAGENT); } KillBehaviour(ACLMessage request, ACLMessage reply) { super(AgentManagementOntology.AMSAction.KILLAGENT, request, reply); } public Behaviour instance(ACLMessage request, ACLMessage reply) { return new KillBehaviour(request, reply); } protected void processAction(AgentManagementOntology.AMSAction a) throws FIPAException { // Make sure it is RMA that's calling String peerName = myRequest.getSource(); if(!peerName.equalsIgnoreCase("RMA")) throw myOntology.getException(AgentManagementOntology.Exception.UNAUTHORISED); // Kill an agent AgentManagementOntology.KillAgentAction kaa = (AgentManagementOntology.KillAgentAction)a; String agentName = kaa.getAgentName(); String password = kaa.getPassword(); myPlatform.AMSKillAgent(agentName, password); sendAgree(myReply); sendInform(myReply); } } // End of KillBehaviour class private static class AgDesc { public AgDesc(String s, AgentManagementOntology.AMSAgentDescriptor a) { containerName = s; amsd = a; } public String containerName; public AgentManagementOntology.AMSAgentDescriptor amsd; } // The AgentPlatform where information about agents is stored private AgentPlatformImpl myPlatform; // Maintains an association between action names and behaviours private FipaRequestServerBehaviour dispatcher; // Behaviour to listen to incoming 'subscribe' messages from Remote // Management Agents. private RegisterRMABehaviour registerRMA; // Behaviour to broadcats AgentPlatform notifications to each // registered Remote Management Agent. private NotifyRMAsBehaviour notifyRMAs; // Behaviour to listen to incoming 'cancel' messages from Remote // Management Agents. private DeregisterRMABehaviour deregisterRMA; // Group of Remote Management Agents registered with this AMS private AgentGroup RMAs; // ACL Message to use for RMA notification private ACLMessage RMANotification = new ACLMessage("inform"); // Buffers for AgentPlatform notifications private Vector newContainersBuffer = new Vector(); private Vector deadContainersBuffer = new Vector(); private Vector newAgentsBuffer = new Vector(); private Vector deadAgentsBuffer = new Vector(); public ams(AgentPlatformImpl ap, String name) { myPlatform = ap; myName = name; MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchLanguage("SL0"), MessageTemplate.MatchOntology("fipa-agent-management")); dispatcher = new FipaRequestServerBehaviour(this, mt); registerRMA = new RegisterRMABehaviour(); deregisterRMA = new DeregisterRMABehaviour(); notifyRMAs = new NotifyRMAsBehaviour(); RMAs = new AgentGroup(); RMANotification.setSource(myName); RMANotification.setLanguage("SL"); RMANotification.setOntology("jade-agent-management"); RMANotification.setReplyTo("RMA-subscription"); // Associate each AMS action name with the behaviour to execute // when the action is requested in a 'request' ACL message dispatcher.registerPrototype(AgentManagementOntology.AMSAction.AUTHENTICATE, new AuthBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.AMSAction.REGISTERAGENT, new RegBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.AMSAction.DEREGISTERAGENT, new DeregBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.AMSAction.MODIFYAGENT, new ModBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.AMSAction.CREATEAGENT, new CreateBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.AMSAction.KILLAGENT, new KillBehaviour()); dispatcher.registerPrototype(AgentManagementOntology.AMSAction.KILLCONTAINER, new KillContainerBehaviour()); } protected void setup() { // Add a dispatcher Behaviour for all ams actions following from a // 'fipa-request' interaction addBehaviour(dispatcher); // Add a Behaviour to accept incoming RMA registrations and a // Behaviour to broadcast events to registered RMAs. addBehaviour(registerRMA); addBehaviour(deregisterRMA); addBehaviour(notifyRMAs); } // The AMS must have a special version for this method, or a deadlock will occur... public void registerWithAMS(String signature, int APState, String delegateAgentName, String forwardAddress, String ownership) { // Skip all fipa-request protocol and go straight to the target try { // FIXME: APState parameter is never used myPlatform.AMSNewData(myName + '@' + myAddress, myAddress, signature, "active", delegateAgentName, forwardAddress, ownership); } // No exception should occur since this is a special case ... catch(AgentAlreadyRegisteredException aare) { aare.printStackTrace(); } catch(FIPAException fe) { fe.printStackTrace(); } } // Methods to be called from AgentPlatform to notify AMS of special events public synchronized void postNewContainer(String name) { newContainersBuffer.addElement(name); doWake(); } public synchronized void postDeadContainer(String name) { deadContainersBuffer.addElement(name); doWake(); } public synchronized void postNewAgent(String containerName, AgentManagementOntology.AMSAgentDescriptor amsd) { newAgentsBuffer.addElement(new AgDesc(containerName, amsd)); doWake(); } public synchronized void postDeadAgent(String containerName, AgentManagementOntology.AMSAgentDescriptor amsd) { deadAgentsBuffer.addElement(new AgDesc(containerName, amsd)); doWake(); } } // End of class ams
package com.gravity.player; import java.util.List; import java.util.Map; import java.util.Set; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Transform; import org.newdawn.slick.geom.Vector2f; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.gravity.gameplay.GravityGameController; import com.gravity.map.GameWorld; import com.gravity.physics.Collision; import com.gravity.physics.CollisionEngine; import com.gravity.physics.Entity; public class Player implements Entity { public static enum Movement { LEFT, RIGHT, STOP, MISC } public static int TOP_LEFT = 0, TOP_RIGHT = 1, BOT_RIGHT = 2, BOT_LEFT = 3; // PLAYER STARTING CONSTANTS (Units = pixels, milliseconds) private final float JUMP_POWER = 0.6f; private final float MOVEMENT_INCREMENT = 1f / 8f; private final float MAX_VEL = 75f; @SuppressWarnings("unused") private final float VEL_DAMP = 0.5f; private final float GRAVITY = 1.0f / 750f; private final float MAX_SLING_STRENGTH = 1f; private final float SLING_SPEED = 1f / 500f; private final float FRICTION = 980f / 1000f; private final Shape BASE_SHAPE = new Rectangle(1f, 1f, 15f, 32f); // WORLD KNOWLEDGE private GameWorld map; private GravityGameController controller; // PLAYER CURRENT VALUES // TODO: bring these back into tile widths instead of pixel widths private Vector2f acceleration = new Vector2f(0, 0); private Vector2f position; private Vector2f velocity = new Vector2f(0, 0); private Shape myShape; public float slingshotStrength = 0; // GAME STATE STUFF private boolean onGround = false; public boolean slingshot = false; private final String name; private Movement requested = Movement.STOP; public Player(GameWorld map, String name, Vector2f startpos, GravityGameController c) { position = startpos; this.map = map; this.myShape = BASE_SHAPE; this.name = name; this.controller = c; } public String getName() { return name; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Player [name="); builder.append(name); builder.append("]"); return builder.toString(); } // //////////////////////////GET & SET METHODS/////////////////////////////// public Vector2f getPosition() { return getPosition(0); } public void setPositionX(float x) { position.x = x; } @Override public Vector2f getPosition(int ticks) { return new Vector2f(position.x + (velocity.x * ticks), position.y + (velocity.y * ticks)); } @Override public Shape getShape(int ticks) { return BASE_SHAPE.transform(Transform.createTranslateTransform(position.x + (velocity.x * ticks), position.y + (velocity.y * ticks))); } @Override public Vector2f getVelocity(int ticks) { return velocity.copy(); } // //////////////////////////KEY-PRESS METHODS/////////////////////////////// /** * @param jumping * true if keydown, false if keyup */ public void jump(boolean jumping) { if (jumping && onGround) { velocity.y -= JUMP_POWER; } } /** * * @param direction */ public void move(Movement direction) { switch (direction) { case LEFT: { if (Math.abs(velocity.x) < MOVEMENT_INCREMENT) { velocity.x = -MOVEMENT_INCREMENT; } break; } case RIGHT: { if (Math.abs(velocity.x) < MOVEMENT_INCREMENT) { velocity.x = MOVEMENT_INCREMENT; } break; } case STOP: { velocity.x = 0; break; } } } /** * * @param pressed * true if keydown, false if keyup */ public void specialKey(boolean pressed) { if (pressed) { slingshot = true; } else { slingshot = false; controller.specialMoveSlingshot(this, slingshotStrength); } } // ///////////////////////////RESULTING ACTIONS////////////////////////////// public void slingshotMe(float strength, Vector2f direction) { velocity = direction.copy().normalise().scale(strength); } // //////////////////////////COLLISION METHODS/////////////////////////////// @Override public Shape handleCollisions(int millis, List<Collision> collisions) { for (Collision c : collisions) { Entity them = c.getOtherEntity(this); // HACK: assumes that a 4-sided Polygon will be a Rectangle if ((them.getShape(millis).getPointCount() == 4)) { resolveTerrainCollisions(getCollisionPoints(collisions), millis); } else { throw new RuntimeException("Cannot resolve non-Rectangle collision."); } } return myShape; } @Override public Shape rehandleCollisions(int ticks, List<Collision> collisions) { for (Collision c : collisions) { Entity them = c.getOtherEntity(this); // HACK: assumes that a 4-sided Polygon will be a Rectangle if ((them.getShape(ticks).getPointCount() == 4)) { resolveTerrainCollisions(getCollisionPoints(collisions), ticks); } else { throw new RuntimeException("Cannot resolve non-Rectangle collision."); } } return myShape; } /** * Get all collision points with terrain */ private Entity[] getCollisionPoints(List<Collision> collisions) { Entity[] points = { null, null, null, null }; for (Collision collision : collisions) { Set<Integer> colPoints = collision.getMyCollisions(this); for (int point : colPoints) { points[point] = collision.getOtherEntity(this); } } return points; } /** * Handles collision with terrain */ private void resolveTerrainCollisions(Entity[] points, int millis) { Entity etl = points[0]; Entity etr = points[1]; Entity ebr = points[2]; Entity ebl = points[3]; boolean tl = (etl != null); boolean tr = (etr != null); boolean br = (ebr != null); boolean bl = (ebl != null); int count = 0; // Count the # of contact points for (Entity point : points) { if (point != null) { count++; } } // Decide what to do based on the # of contact points switch (count) { case 0: // No collisions throw new RuntimeException("handleCollisions should NOT be called with empty collision list"); case 1: // If you only hit one corner, we will cancel velocity in the direction of the corner if (tl) { // Hit top left velocity.x = Math.max(velocity.x, 0); velocity.y = Math.max(velocity.y, 0); } else if (tr) { // Hit top right velocity.x = Math.min(velocity.x, 0); velocity.y = Math.max(velocity.y, 0); } else if (br) { // Hit bottom right velocity.x = Math.min(velocity.x, 0); velocity.y = Math.min(velocity.y, 0); } else if (bl) { // Hit bottom left velocity.x = Math.max(velocity.x, 0); velocity.y = Math.min(velocity.y, 0); } else { throw new RuntimeException("Should never hit this line: case 1"); } break; case 2: if (tl && tr) { // if you hit the ceiling velocity.y = 0; onGround = false; } else if (bl && br) { // if you hit the floor velocity.y = 0; onGround = true; } else if (tr && br) { // if you hit the right wall velocity.x = 0; } else if (tl && bl) { // if you hit the left wall velocity.x = 0; } else { // if you hit opposite corners if ((points[0] == points[2] && points[0] != null) || (points[1] == points[3] && points[1] != null)) { System.out.println("check opening size!!!"); } velocity.x = 0; velocity.y = 0; } break; default: // Collision on 2 or more sides velocity.x = 0; velocity.y = 0; break; } } // //////////////////////////ON-TICK METHODS///////////////////////////////// @Override public void tick(int millis) { updatePosition(millis); updateAcceleration(millis); updateVelocity(millis); updateSlingshot(millis); Shape hitbox = myShape.transform(Transform.createTranslateTransform(0, 5)); List<Entity> collisions = map.getTouching(hitbox); onGround = false; for (Entity ent : collisions) { Map<Integer, List<Integer>> aCollisions = Maps.newHashMap(), bCollisions = Maps.newHashMap(); Shape e = ent.getShape(0); CollisionEngine.getShapeIntersections(hitbox, e, aCollisions, bCollisions); Set<Integer> aPoints = Sets.newHashSet(); Set<Integer> bPoints = Sets.newHashSet(); CollisionEngine.getIntersectPoints(hitbox, e, aCollisions, aPoints, bPoints); CollisionEngine.getIntersectPoints(e, hitbox, bCollisions, bPoints, aPoints); if (!onGround && aPoints.contains(BOT_LEFT) && aPoints.contains(BOT_RIGHT) || (aPoints.size() == 1 && (aPoints.contains(BOT_LEFT) || aPoints.contains(BOT_RIGHT)))) { onGround = true; } // terrain doesn't move so this is safe to be called. necessary for detecting when running over spikes ent.handleCollisions(millis, Lists.newArrayList(new Collision(ent, this, millis, bPoints, aPoints))); } isDead(millis); } public void updateAcceleration(float millis) { if (onGround) { acceleration.y = 0; } else { acceleration.y = GRAVITY; } } public void updateVelocity(float millis) { // dv = a velocity.add(acceleration.copy().scale(millis)); // velocity < maxVel if (velocity.length() > MAX_VEL * millis) { velocity.scale(MAX_VEL * millis / velocity.length()); } // implement friction if (onGround) { if (velocity.x > MOVEMENT_INCREMENT) { velocity.x = velocity.x * FRICTION; } } } public void updatePosition(float millis) { position.add(velocity.copy().scale(millis)); updateShape(); } public void updateSlingshot(float millis) { if (slingshot) { slingshotStrength += millis * SLING_SPEED; slingshotStrength = Math.min(slingshotStrength, MAX_SLING_STRENGTH); } else { slingshotStrength = 0; } } * /** CALL THIS EVERY TIME YOU DO ANYTHING TO POSITION OR SHAPE >>>>>>> 578f54515a017ccc7211c613d175bbac8740860c */ private void updateShape() { myShape = BASE_SHAPE.transform(Transform.createTranslateTransform(position.x, position.y)); } public void setRequestedMovement(Movement requested) { this.requested = requested; } /** * Checks to see if the player is dead */ private void isDead(float millis) { // TODO } }
package org.dosomething.android.activities; import java.util.ArrayList; import java.util.List; import org.dosomething.android.DSConstants; import org.dosomething.android.R; import org.dosomething.android.context.UserContext; import org.dosomething.android.tasks.AbstractWebserviceTask; import org.dosomething.android.transfer.Campaign; import org.dosomething.android.transfer.SFGData; import org.dosomething.android.transfer.SFGGalleryItem; import org.dosomething.android.transfer.WebFormSelectOptions; import org.dosomething.android.widget.ActionBarSubMenu; import org.dosomething.android.widget.CustomActionBar; import org.dosomething.android.widget.CustomActionBar.SubMenuAction; import org.dosomething.android.widget.ProgressBarImageLoadingListener; import org.json.JSONArray; import org.json.JSONObject; import roboguice.inject.InjectView; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import com.google.inject.Inject; import com.google.inject.name.Named; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.nostra13.universalimageloader.core.ImageLoader; /** * SFG = Share For Good * Main gallery page for Share for Good campaign types. Displays list of the * sharable gallery items. */ public class SFGGallery extends AbstractActivity { @Inject private LayoutInflater inflater; @Inject private ImageLoader imageLoader; @Inject private UserContext userContext; @Inject @Named("DINComp-CondBold")Typeface dinTypeface; @InjectView(R.id.actionbar) private CustomActionBar actionBar; @InjectView(R.id.list) private PullToRefreshListView pullToRefreshView; private Campaign campaign; private ListView list; private String lastTypeFilter; private String lastLocationFilter; @Override protected String getPageName() { return "SFGGallery"; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sfggallery); list = pullToRefreshView.getRefreshableView(); pullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { fetchItems(); } }); // Setup Custom Action bar with submenu items campaign = (Campaign) getIntent().getExtras().get(DSConstants.EXTRAS_KEY.CAMPAIGN.getValue()); if (campaign != null) { actionBar.setTitle(campaign.getName()); } SubMenuAction subMenuAction = actionBar.addSubMenuAction(this); ActionBarSubMenu subMenuView = subMenuAction.getSubMenuView(); subMenuView.addMenuItem(this, getString(R.string.campaign_sfg_submit_pet), SFGSubmit.getIntent(this, campaign)); // Setup spinners with filter options pulled from campaign data Spinner typeFilterSpinner = (Spinner)findViewById(R.id.type_filter); SFGData sfgData = campaign.getSFGData(); ArrayList<WebFormSelectOptions> typeOptions = sfgData.getTypeOptions(); List<String> types = new ArrayList<String>(); for (int i = 0; i < typeOptions.size(); i++) { WebFormSelectOptions options = typeOptions.get(i); types.add(options.getLabel()); } typeFilterSpinner.setAdapter(new FilterAdapter(SFGGallery.this, types)); Spinner locFilterSpinner = (Spinner)findViewById(R.id.location_filter); ArrayList<WebFormSelectOptions> locOptions = sfgData.getLocationOptions(); List<String> locations = new ArrayList<String>(); for (int i = 0; i < locOptions.size(); i++) { WebFormSelectOptions options = locOptions.get(i); locations.add(options.getLabel()); } locFilterSpinner.setAdapter(new FilterAdapter(SFGGallery.this, locations)); // Style filter button's typeface and setup click listener Button filterSubmit = (Button)findViewById(R.id.filter_execute); filterSubmit.setTypeface(dinTypeface, Typeface.BOLD); filterSubmit.setOnClickListener(new OnFilterClickListener()); } @Override protected void onResume() { super.onResume(); lastTypeFilter = ""; lastLocationFilter = ""; fetchItems(); } private void fetchItems() { // Clear any items that might currently be in the list list.setAdapter(null); if (campaign != null) { new SFGGalleryWebserviceTask(campaign.getSFGData().getGalleryUrl(), lastTypeFilter, lastLocationFilter).execute(); } } /** * Click listener to execute gallery filter */ private class OnFilterClickListener implements OnClickListener { @Override public void onClick(View v) { Spinner typeFilterSpinner = (Spinner)findViewById(R.id.type_filter); int typeIndex = typeFilterSpinner.getSelectedItemPosition(); WebFormSelectOptions typeOpt = campaign.getSFGData().getTypeOptions().get(typeIndex); lastTypeFilter = typeOpt.getValue(); Spinner locFilterSpinner = (Spinner)findViewById(R.id.location_filter); int locIndex = locFilterSpinner.getSelectedItemPosition(); WebFormSelectOptions locOpt = campaign.getSFGData().getLocationOptions().get(locIndex); lastLocationFilter = locOpt.getValue(); fetchItems(); } } public static Intent getIntent(Context context, org.dosomething.android.transfer.Campaign campaign){ Intent answer = new Intent(context, SFGGallery.class); answer.putExtra(DSConstants.EXTRAS_KEY.CAMPAIGN.getValue(), campaign); return answer; } /** * Custom adapter for filter options. Allows us to customize the style of the * list of options */ private class FilterAdapter extends ArrayAdapter<String> { public FilterAdapter(Context context, List<String> items) { super(context, android.R.layout.simple_dropdown_item_1line, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); setDinTypeface(v); return v; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View v = super.getDropDownView(position, convertView, parent); setDinTypeface(v); return v; } private void setDinTypeface(View v) { TextView textView = (TextView)v.findViewById(android.R.id.text1); textView.setTypeface(dinTypeface, Typeface.BOLD); textView.setTextSize(16); } } /** * Task to retrieve list data */ private class SFGGalleryWebserviceTask extends AbstractWebserviceTask { private String url; private List<SFGGalleryItem> galleryItems; public SFGGalleryWebserviceTask(String url) { super(userContext); this.url = url + "posts.json?key=" + DSConstants.PICS_API_KEY; this.galleryItems = new ArrayList<SFGGalleryItem>(); } public SFGGalleryWebserviceTask(String _url, String typeOpt, String locOpt) { super(userContext); this.galleryItems = new ArrayList<SFGGalleryItem>(); String options = ""; if (typeOpt != null && typeOpt.length() > 0) { options = typeOpt; } if (locOpt != null && locOpt.length() > 0) { if (options.length() == 0) options = locOpt; else options += "-" + locOpt; } if (options.length() == 0) { options = "posts"; } this.url = _url + options + ".json?key=" + DSConstants.PICS_API_KEY; } @Override protected void onPreExecute() { actionBar.setProgressBarVisibility(ProgressBar.VISIBLE); } @Override protected void onSuccess() { if (galleryItems != null && galleryItems.size() > 0) { SFGListAdapter adapter = new SFGListAdapter(galleryItems); list.setAdapter(adapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> av, View v, int position, long id) { SFGGalleryItem galleryItem = (SFGGalleryItem)list.getAdapter().getItem(position); startActivity(SFGItem.getIntent(getApplicationContext(), galleryItem, campaign)); } }); } else { // No results were found new AlertDialog.Builder(SFGGallery.this) .setMessage(getString(R.string.campaign_sfg_no_results)) .setCancelable(false) .setPositiveButton(getString(R.string.ok_upper), null) .create() .show(); } } @Override protected void onFinish() { actionBar.setProgressBarVisibility(ProgressBar.GONE); pullToRefreshView.onRefreshComplete(); } @Override protected void onError(Exception e) { new AlertDialog.Builder(SFGGallery.this) .setMessage("Unable to update") .setCancelable(false) .setPositiveButton(getString(R.string.ok_upper), null) .create() .show(); } @Override protected void doWebOperation() throws Exception { WebserviceResponse response = this.doGet(this.url); if (response.getStatusCode() < 400) { JSONArray jsonItems = response.getBodyAsJSONArray(); for (int i = 0; i < jsonItems.length(); i++) { JSONObject item = jsonItems.getJSONObject(i); galleryItems.add(new SFGGalleryItem(item)); } } } } /** * ListAdapter to handle SFG gallery functionality */ private class SFGListAdapter extends ArrayAdapter<SFGGalleryItem> { public SFGListAdapter(List<SFGGalleryItem> items) { super(SFGGallery.this, android.R.layout.simple_expandable_list_item_1, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { v = inflater.inflate(R.layout.sfggallery_row, null); } SFGGalleryItem item = getItem(position); ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.progressBar); TextView name = (TextView)v.findViewById(R.id.name); ImageView image = (ImageView)v.findViewById(R.id.image); TextView shareCount = (TextView)v.findViewById(R.id.share_count); TextView shelter = (TextView)v.findViewById(R.id.shelter); TextView state = (TextView)v.findViewById(R.id.state); if (name != null) { name.setTypeface(dinTypeface, Typeface.BOLD); name.setText(item.getName()); } if (image != null && progressBar != null) { String imageUrl = campaign.getSFGData().getGalleryUrl() + item.getImageURL(); imageLoader.displayImage(imageUrl, image, new ProgressBarImageLoadingListener(progressBar)); } if (shareCount != null) { shareCount.setTypeface(dinTypeface, Typeface.BOLD); shareCount.setText("Share Count: "+item.getShareCount()); } if (shelter != null) { shelter.setTypeface(dinTypeface, Typeface.BOLD); shelter.setText(item.getShelter()); } if (state != null) { state.setTypeface(dinTypeface, Typeface.BOLD); state.setText(item.getState()); } return v; } } }
package org.dspace.app.itemexport; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.DCValue; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.content.MetadataSchema; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.Utils; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; public class ItemExport { private static final int SUBDIR_LIMIT = 0; /** * used for export download */ public static final String COMPRESSED_EXPORT_MIME_TYPE = "application/zip"; public static void main(String[] argv) throws Exception { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("t", "type", true, "type: COLLECTION or ITEM"); options.addOption("i", "id", true, "ID or handle of thing to export"); options.addOption("d", "dest", true, "destination where you want items to go"); options.addOption("n", "number", true, "sequence number to begin exporting items with"); options.addOption("h", "help", false, "help"); CommandLine line = parser.parse(options, argv); String typeString = null; String destDirName = null; String myIDString = null; int seqStart = -1; int myType = -1; Item myItem = null; Collection mycollection = null; if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ItemExport\n", options); System.out .println("\nfull collection: ItemExport -t COLLECTION -i ID -d dest -n number"); System.out .println("singleitem: ItemExport -t ITEM -i ID -d dest -n number"); System.exit(0); } if (line.hasOption('t')) // type { typeString = line.getOptionValue('t'); if (typeString.equals("ITEM")) { myType = Constants.ITEM; } else if (typeString.equals("COLLECTION")) { myType = Constants.COLLECTION; } } if (line.hasOption('i')) { myIDString = line.getOptionValue('i'); } if (line.hasOption('d')) // dest { destDirName = line.getOptionValue('d'); } if (line.hasOption('n')) // number { seqStart = Integer.parseInt(line.getOptionValue('n')); } // now validate the args if (myType == -1) { System.out .println("type must be either COLLECTION or ITEM (-h for help)"); System.exit(1); } if (destDirName == null) { System.out .println("destination directory must be set (-h for help)"); System.exit(1); } if (seqStart == -1) { System.out .println("sequence start number must be set (-h for help)"); System.exit(1); } if (myIDString == null) { System.out .println("ID must be set to either a database ID or a handle (-h for help)"); System.exit(1); } Context c = new Context(); c.setIgnoreAuthorization(true); if (myType == Constants.ITEM) { // first, is myIDString a handle? if (myIDString.indexOf('/') != -1) { myItem = (Item) HandleManager.resolveToObject(c, myIDString); if ((myItem == null) || (myItem.getType() != Constants.ITEM)) { myItem = null; } } else { myItem = Item.find(c, Integer.parseInt(myIDString)); } if (myItem == null) { System.out .println("Error, item cannot be found: " + myIDString); } } else { if (myIDString.indexOf('/') != -1) { // has a / must be a handle mycollection = (Collection) HandleManager.resolveToObject(c, myIDString); // ensure it's a collection if ((mycollection == null) || (mycollection.getType() != Constants.COLLECTION)) { mycollection = null; } } else if (myIDString != null) { mycollection = Collection.find(c, Integer.parseInt(myIDString)); } if (mycollection == null) { System.out.println("Error, collection cannot be found: " + myIDString); System.exit(1); } } if (myItem != null) { // it's only a single item exportItem(c, myItem, destDirName, seqStart); } else { System.out.println("Exporting from collection: " + myIDString); // it's a collection, so do a bunch of items ItemIterator i = mycollection.getItems(); try { exportItem(c, i, destDirName, seqStart); } finally { if (i != null) i.close(); } } c.complete(); } private static void exportItem(Context c, ItemIterator i, String destDirName, int seqStart) throws Exception { int mySequenceNumber = seqStart; int counter = SUBDIR_LIMIT - 1; int subDirSuffix = 0; String fullPath = destDirName; String subdir = ""; File dir; if (SUBDIR_LIMIT > 0) { dir = new File(destDirName); if (!dir.isDirectory()) { throw new IOException(destDirName + " is not a directory."); } } System.out.println("Beginning export"); while (i.hasNext()) { if (SUBDIR_LIMIT > 0 && ++counter == SUBDIR_LIMIT) { subdir = new Integer(subDirSuffix++).toString(); fullPath = destDirName + File.separatorChar + subdir; counter = 0; if (!new File(fullPath).mkdirs()) { throw new IOException("Error, can't make dir " + fullPath); } } System.out.println("Exporting item to " + mySequenceNumber); exportItem(c, i.next(), fullPath, mySequenceNumber); mySequenceNumber++; } } private static void exportItem(Context c, Item myItem, String destDirName, int seqStart) throws Exception { File destDir = new File(destDirName); if (destDir.exists()) { // now create a subdirectory File itemDir = new File(destDir + "/" + seqStart); System.out.println("Exporting Item " + myItem.getID() + " to " + itemDir); if (itemDir.exists()) { throw new Exception("Directory " + destDir + "/" + seqStart + " already exists!"); } if (itemDir.mkdir()) { // make it this far, now start exporting writeMetadata(c, myItem, itemDir); writeBitstreams(c, myItem, itemDir); writeHandle(c, myItem, itemDir); } else { throw new Exception("Error, can't make dir " + itemDir); } } else { throw new Exception("Error, directory " + destDirName + " doesn't exist!"); } } /** * Discover the different schemas in use and output a seperate metadata XML * file for each schema. * * @param c * @param i * @param destDir * @throws Exception */ private static void writeMetadata(Context c, Item i, File destDir) throws Exception { // Build a list of schemas for the item HashMap map = new HashMap(); DCValue[] dcorevalues = i.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY); for (int ii = 0; ii < dcorevalues.length; ii++) { map.put(dcorevalues[ii].schema, null); } // Save each of the schemas into it's own metadata file Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { String schema = (String) iterator.next(); writeMetadata(c, schema, i, destDir); } } // output the item's dublin core into the item directory private static void writeMetadata(Context c, String schema, Item i, File destDir) throws Exception { String filename; if (schema.equals(MetadataSchema.DC_SCHEMA)) { filename = "dublin_core.xml"; } else { filename = "metadata_" + schema + ".xml"; } File outFile = new File(destDir, filename); System.out.println("Attempting to create file " + outFile); if (outFile.createNewFile()) { BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(outFile)); DCValue[] dcorevalues = i.getMetadata(schema, Item.ANY, Item.ANY, Item.ANY); // XML preamble byte[] utf8 = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n" .getBytes("UTF-8"); out.write(utf8, 0, utf8.length); String dcTag = "<dublin_core schema=\"" + schema + "\">\n"; utf8 = dcTag.getBytes("UTF-8"); out.write(utf8, 0, utf8.length); for (int j = 0; j < dcorevalues.length; j++) { DCValue dcv = dcorevalues[j]; String qualifier = dcv.qualifier; if (qualifier == null) { qualifier = "none"; } utf8 = (" <dcvalue element=\"" + dcv.element + "\" " + "qualifier=\"" + qualifier + "\">" + Utils.addEntities(dcv.value) + "</dcvalue>\n") .getBytes("UTF-8"); out.write(utf8, 0, utf8.length); } utf8 = "</dublin_core>\n".getBytes("UTF-8"); out.write(utf8, 0, utf8.length); out.close(); } else { throw new Exception("Cannot create dublin_core.xml in " + destDir); } } // create the file 'handle' which contains the handle assigned to the item private static void writeHandle(Context c, Item i, File destDir) throws Exception { if (i.getHandle() == null) { return; } String filename = "handle"; File outFile = new File(destDir, filename); if (outFile.createNewFile()) { PrintWriter out = new PrintWriter(new FileWriter(outFile)); out.println(i.getHandle()); // close the contents file out.close(); } else { throw new Exception("Cannot create file " + filename + " in " + destDir); } } /** * Create both the bitstreams and the contents file. Any bitstreams that * were originally registered will be marked in the contents file as such. * However, the export directory will contain actual copies of the content * files being exported. * * @param c * the DSpace context * @param i * the item being exported * @param destDir * the item's export directory * @throws Exception * if there is any problem writing to the export directory */ private static void writeBitstreams(Context c, Item i, File destDir) throws Exception { File outFile = new File(destDir, "contents"); if (outFile.createNewFile()) { PrintWriter out = new PrintWriter(new FileWriter(outFile)); Bundle[] bundles = i.getBundles(); for (int j = 0; j < bundles.length; j++) { // bundles can have multiple bitstreams now... Bitstream[] bitstreams = bundles[j].getBitstreams(); String bundleName = bundles[j].getName(); for (int k = 0; k < bitstreams.length; k++) { Bitstream b = bitstreams[k]; String myName = b.getName(); String oldName = myName; int myPrefix = 1; // only used with name conflict InputStream is = b.retrieve(); boolean isDone = false; // done when bitstream is finally // written while (!isDone) { if (myName.contains(File.separator)) { String dirs = myName.substring(0, myName .lastIndexOf(File.separator)); File fdirs = new File(destDir + File.separator + dirs); fdirs.mkdirs(); } File fout = new File(destDir, myName); if (fout.createNewFile()) { FileOutputStream fos = new FileOutputStream(fout); Utils.bufferedCopy(is, fos); // close streams is.close(); fos.close(); // write the manifest file entry if (b.isRegisteredBitstream()) { out.println("-r -s " + b.getStoreNumber() + " -f " + myName + "\tbundle:" + bundleName); } else { out.println(myName + "\tbundle:" + bundleName); } isDone = true; } else { myName = myPrefix + "_" + oldName; // keep // appending // numbers to the // filename until // unique myPrefix++; } } } } // close the contents file out.close(); } else { throw new Exception("Cannot create contents in " + destDir); } } /** * Convenience methot to create export a single Community, Collection, or * Item * * @param dso * - the dspace object to export * @param context * - the dspace context * @throws Exception */ public static void createDownloadableExport(DSpaceObject dso, Context context) throws Exception { EPerson eperson = context.getCurrentUser(); ArrayList<DSpaceObject> list = new ArrayList<DSpaceObject>(1); list.add(dso); processDownloadableExport(list, context, eperson == null ? null : eperson.getEmail()); } /** * Convenience method to export a List of dspace objects (Community, * Collection or Item) * * @param dsObjects * - List containing dspace objects * @param context * - the dspace context * @throws Exception */ public static void createDownloadableExport(List<DSpaceObject> dsObjects, Context context) throws Exception { EPerson eperson = context.getCurrentUser(); processDownloadableExport(dsObjects, context, eperson == null ? null : eperson.getEmail()); } /** * Convenience methot to create export a single Community, Collection, or * Item * * @param dso * - the dspace object to export * @param context * - the dspace context * @param additionalEmail * - cc email to use * @throws Exception */ public static void createDownloadableExport(DSpaceObject dso, Context context, String additionalEmail) throws Exception { ArrayList<DSpaceObject> list = new ArrayList<DSpaceObject>(1); list.add(dso); processDownloadableExport(list, context, additionalEmail); } /** * Convenience method to export a List of dspace objects (Community, * Collection or Item) * * @param dsObjects * - List containing dspace objects * @param context * - the dspace context * @param additionalEmail * - cc email to use * @throws Exception */ public static void createDownloadableExport(List<DSpaceObject> dsObjects, Context context, String additionalEmail) throws Exception { processDownloadableExport(dsObjects, context, additionalEmail); } /** * Does the work creating a List with all the Items in the Community or * Collection It then kicks off a new Thread to export the items, zip the * export directory and send confirmation email * * @param dsObjects * - List of dspace objects to process * @param context * - the dspace context * @param additionalEmail * - email address to cc in addition the the current user email * @throws Exception */ private static void processDownloadableExport(List<DSpaceObject> dsObjects, Context context, final String additionalEmail) throws Exception { final EPerson eperson = context.getCurrentUser(); // before we create a new export archive lets delete the 'expired' // archives deleteOldExportArchives(eperson.getID()); // keep track of the commulative size of all bitstreams in each of the // items // it will be checked against the config file entry float size = 0; final ArrayList<Integer> items = new ArrayList<Integer>(); for (DSpaceObject dso : dsObjects) { if (dso.getType() == Constants.COMMUNITY) { Community community = (Community) dso; // get all the collections in the community Collection[] collections = community.getCollections(); for (Collection collection : collections) { // get all the items in each collection ItemIterator iitems = collection.getItems(); try { while (iitems.hasNext()) { Item item = iitems.next(); // get all the bundles in the item Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { // get all the bitstreams in each bundle Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bit : bitstreams) { // add up the size size += bit.getSize(); } } items.add(item.getID()); } } finally { if (iitems != null) iitems.close(); } } } else if (dso.getType() == Constants.COLLECTION) { Collection collection = (Collection) dso; // get all the items in the collection ItemIterator iitems = collection.getItems(); try { while (iitems.hasNext()) { Item item = iitems.next(); // get all thebundles in the item Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { // get all the bitstreams in the bundle Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bit : bitstreams) { // add up the size size += bit.getSize(); } } items.add(item.getID()); } } finally { if (iitems != null) iitems.close(); } } else if (dso.getType() == Constants.ITEM) { Item item = (Item) dso; // get all the bundles in the item Bundle[] bundles = item.getBundles(); for (Bundle bundle : bundles) { // get all the bitstreams in the bundle Bitstream[] bitstreams = bundle.getBitstreams(); for (Bitstream bit : bitstreams) { // add up the size size += bit.getSize(); } } items.add(item.getID()); } else { // nothing to do just ignore this type of DSPaceObject } } // check the size of all the bitstreams against the configuration file // entry if it exists String megaBytes = ConfigurationManager .getProperty("org.dspace.app.itemexport.max.size"); if (megaBytes != null) { float maxSize = 0; try { maxSize = Float.parseFloat(megaBytes); } catch (Exception e) { // ignore...configuration entry may not be present } if (maxSize > 0) { if (maxSize < (size / 1048576.00)) { // a megabyte throw new Exception( "The overall size of this export is too large. Please contact your administrator for more information."); } } } // if we have any items to process then kick off annonymous thread if (items.size() > 0) { Thread go = new Thread() { public void run() { Context context; ItemIterator iitems = null; try { // create a new dspace context context = new Context(); // ignore auths context.setIgnoreAuthorization(true); iitems = new ItemIterator(context, items); String fileName = assembleFileName("item", eperson, new Date()); String workDir = getExportWorkDirectory() + System.getProperty("file.separator") + fileName; String downloadDir = getExportDownloadDirectory(eperson .getID()); File wkDir = new File(workDir); if (!wkDir.exists()) { wkDir.mkdirs(); } File dnDir = new File(downloadDir); if (!dnDir.exists()) { dnDir.mkdirs(); } // export the items using normal export method exportItem(context, iitems, workDir, 1); // now zip up the export directory created above zip(workDir, downloadDir + System.getProperty("file.separator") + fileName + ".zip"); // email message letting user know the file is ready for // download emailSuccessMessage(eperson.getEmail(), ConfigurationManager .getProperty("mail.from.address"), additionalEmail, fileName + ".zip"); // return to enforcing auths context.setIgnoreAuthorization(false); } catch (Exception e1) { try { emailErrorMessage(eperson.getEmail(), ConfigurationManager .getProperty("mail.from.address"), additionalEmail, e1.getMessage()); } catch (Exception e) { // wont throw here } throw new RuntimeException(e1); } finally { if (iitems != null) iitems.close(); } } }; go.isDaemon(); go.start(); } } /** * Create a file name based on the date and eperson * * @param eperson * - eperson who requested export and will be able to download it * @param date * - the date the export process was created * @return String representing the file name in the form of * 'export_yyy_MMM_dd_count_epersonID' * @throws Exception */ public static String assembleFileName(String type, EPerson eperson, Date date) throws Exception { // to format the date SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MMM_dd"); String downloadDir = getExportDownloadDirectory(eperson.getID()); // used to avoid name collision int count = 1; boolean exists = true; String fileName = null; while (exists) { fileName = type + "_export_" + sdf.format(date) + "_" + count + "_" + eperson.getID(); exists = new File(downloadDir + System.getProperty("file.separator") + fileName + ".zip") .exists(); count++; } return fileName; } /** * Use config file entry for org.dspace.app.itemexport.download.dir and id * of the eperson to create a download directory name * * @param ePersonID * - id of the eperson who requested export archive * @return String representing a directory in the form of * org.dspace.app.itemexport.download.dir/epersonID * @throws Exception */ public static String getExportDownloadDirectory(int ePersonID) throws Exception { String downloadDir = ConfigurationManager .getProperty("org.dspace.app.itemexport.download.dir"); if (downloadDir == null) { throw new Exception( "A dspace.cfg entry for 'org.dspace.app.itemexport.download.dir' does not exist."); } return downloadDir + System.getProperty("file.separator") + ePersonID; } /** * Returns config file entry for org.dspace.app.itemexport.work.dir * * @return String representing config file entry for * org.dspace.app.itemexport.work.dir * @throws Exception */ public static String getExportWorkDirectory() throws Exception { String exportDir = ConfigurationManager .getProperty("org.dspace.app.itemexport.work.dir"); if (exportDir == null) { throw new Exception( "A dspace.cfg entry for 'org.dspace.app.itemexport.work.dir' does not exist."); } return exportDir; } /** * Used to read the export archived. Inteded for download. * * @param fileName * the name of the file to download * @param eperson * the eperson requesting the download * @return an input stream of the file to be downloaded * @throws Exception */ public static InputStream getExportDownloadInputStream(String fileName, EPerson eperson) throws Exception { File file = new File(getExportDownloadDirectory(eperson.getID()) + System.getProperty("file.separator") + fileName); if (file.exists()) { return new FileInputStream(file); } else return null; } /** * Get the file size of the export archive represented by the file name * * @param fileName * name of the file to get the size * @return * @throws Exception */ public static long getExportFileSize(String fileName) throws Exception { String strID = fileName.substring(fileName.lastIndexOf('_') + 1, fileName.lastIndexOf('.')); File file = new File( getExportDownloadDirectory(Integer.parseInt(strID)) + System.getProperty("file.separator") + fileName); if (!file.exists() || !file.isFile()) { throw new FileNotFoundException("The file " + getExportDownloadDirectory(Integer.parseInt(strID)) + System.getProperty("file.separator") + fileName + " does not exist."); } return file.length(); } public static long getExportFileLastModified(String fileName) throws Exception { String strID = fileName.substring(fileName.lastIndexOf('_') + 1, fileName.lastIndexOf('.')); File file = new File( getExportDownloadDirectory(Integer.parseInt(strID)) + System.getProperty("file.separator") + fileName); if (!file.exists() || !file.isFile()) { throw new FileNotFoundException("The file " + getExportDownloadDirectory(Integer.parseInt(strID)) + System.getProperty("file.separator") + fileName + " does not exist."); } return file.lastModified(); } /** * The file name of the export archive contains the eperson id of the person * who created it When requested for download this method can check if the * person requesting it is the same one that created it * * @param context * dspace context * @param fileName * the file name to check auths for * @return true if it is the same person false otherwise */ public static boolean canDownload(Context context, String fileName) { EPerson eperson = context.getCurrentUser(); if (eperson == null) { return false; } String strID = fileName.substring(fileName.lastIndexOf('_') + 1, fileName.lastIndexOf('.')); try { if (Integer.parseInt(strID) == eperson.getID()) { return true; } } catch (Exception e) { return false; } return false; } /** * Reads the download directory for the eperson to see if any export * archives are available * * @param eperson * @return a list of file names representing export archives that have been * processed * @throws Exception */ public static List<String> getExportsAvailable(EPerson eperson) throws Exception { File downloadDir = new File(getExportDownloadDirectory(eperson.getID())); if (!downloadDir.exists() || !downloadDir.isDirectory()) { return null; } List<String> fileNames = new ArrayList<String>(); for (String fileName : downloadDir.list()) { if (fileName.contains("export") && fileName.endsWith(".zip")) { fileNames.add(fileName); } } if (fileNames.size() > 0) { return fileNames; } return null; } /** * A clean up method that is ran before a new export archive is created. It * uses the config file entry 'org.dspace.app.itemexport.life.span.hours' to * determine if the current exports are too old and need pruging * * @param epersonID * - the id of the eperson to clean up * @throws Exception */ public static void deleteOldExportArchives(int epersonID) throws Exception { int hours = ConfigurationManager .getIntProperty("org.dspace.app.itemexport.life.span.hours"); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.add(Calendar.HOUR, (-hours)); File downloadDir = new File(getExportDownloadDirectory(epersonID)); if (downloadDir.exists()) { File[] files = downloadDir.listFiles(); for (File file : files) { if (file.lastModified() < now.getTimeInMillis()) { file.delete(); } } } } /** * Since the archive is created in a new thread we are unable to communicate * with calling method about success or failure. We accomplis this * communication with email instead. Send a success email once the export * archive is complete and ready for download * * @param toMail * - email to send message to * @param fromMail * - email for the from field * @param ccMail * - carbon copy email * @param fileName * - the file name to be downloaded. It is added to the url in * the email * @throws MessagingException */ public static void emailSuccessMessage(String toMail, String fromMail, String ccMail, String fileName) throws MessagingException { StringBuffer content = new StringBuffer(); content .append("The item export you requested from the repository is now ready for download."); content.append(System.getProperty("line.separator")); content.append(System.getProperty("line.separator")); content .append("You may download the compressed file using the following web address:"); content.append(System.getProperty("line.separator")); content.append(ConfigurationManager.getProperty("dspace.url")); content.append("/exportdownload/"); content.append(fileName); content.append(System.getProperty("line.separator")); content.append(System.getProperty("line.separator")); content.append("Tis file will remain available for at least "); content.append(ConfigurationManager .getProperty("org.dspace.app.itemexport.life.span.hours")); content.append(" hours."); content.append(System.getProperty("line.separator")); content.append(System.getProperty("line.separator")); content.append("Thank you"); sendMessage(toMail, fromMail, ccMail, "Item export requested is ready for download", content); } /** * Since the archive is created in a new thread we are unable to communicate * with calling method about success or failure. We accomplis this * communication with email instead. Send an error email if the export * archive fails * * @param toMail * - email to send message to * @param fromMail * - email for the from field * @param ccMail * - carbon copy email * @param error * - the error message * @throws MessagingException */ public static void emailErrorMessage(String toMail, String fromMail, String ccMail, String error) throws MessagingException { StringBuffer content = new StringBuffer(); content.append("The item export you requested was not completed."); content.append(System.getProperty("line.separator")); content.append(System.getProperty("line.separator")); content .append("For more infrmation you may contact your system administrator."); content.append(System.getProperty("line.separator")); content.append(System.getProperty("line.separator")); content.append("Error message received: "); content.append(error); content.append(System.getProperty("line.separator")); content.append(System.getProperty("line.separator")); content.append("Thank you"); sendMessage(toMail, fromMail, ccMail, "Item export requested was not completed", content); } private static void sendMessage(String toMail, String fromMail, String ccMail, String subject, StringBuffer content) throws MessagingException { try { if (toMail == null || !toMail.contains("@")) { return; } // Get the mail configuration properties String server = ConfigurationManager.getProperty("mail.server"); // Set up properties for mail session Properties props = System.getProperties(); props.put("mail.smtp.host", server); // Get session Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); // create the first part of the email BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(content.toString()); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); msg.setFrom(new InternetAddress(fromMail)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress( toMail)); if (ccMail != null && ccMail.contains("@")) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress( ccMail)); } msg.setSentDate(new Date()); msg.setSubject(subject); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); throw e; } } public static void zip(String strSource, String target) throws Exception { ZipOutputStream cpZipOutputStream = null; String tempFileName = target + "_tmp"; try { File cpFile = new File(strSource); if (!cpFile.isFile() && !cpFile.isDirectory()) { return; } File targetFile = new File(tempFileName); if (!targetFile.exists()) { targetFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(tempFileName); cpZipOutputStream = new ZipOutputStream(fos); cpZipOutputStream.setLevel(9); zipFiles(cpFile, strSource, tempFileName, cpZipOutputStream); cpZipOutputStream.finish(); cpZipOutputStream.close(); deleteDirectory(cpFile); targetFile.renameTo(new File(target)); } catch (Exception e) { throw e; } } private static void zipFiles(File cpFile, String strSource, String strTarget, ZipOutputStream cpZipOutputStream) throws Exception { int byteCount; final int DATA_BLOCK_SIZE = 2048; FileInputStream cpFileInputStream; if (cpFile.isDirectory()) { File[] fList = cpFile.listFiles(); for (int i = 0; i < fList.length; i++) { zipFiles(fList[i], strSource, strTarget, cpZipOutputStream); } } else { try { if (cpFile.getAbsolutePath().equalsIgnoreCase(strTarget)) { return; } String strAbsPath = cpFile.getPath(); String strZipEntryName = strAbsPath.substring(strSource .length() + 1, strAbsPath.length()); // byte[] b = new byte[ (int)(cpFile.length()) ]; cpFileInputStream = new FileInputStream(cpFile); ZipEntry cpZipEntry = new ZipEntry(strZipEntryName); cpZipOutputStream.putNextEntry(cpZipEntry); byte[] b = new byte[DATA_BLOCK_SIZE]; while ((byteCount = cpFileInputStream.read(b, 0, DATA_BLOCK_SIZE)) != -1) { cpZipOutputStream.write(b, 0, byteCount); } // cpZipOutputStream.write(b, 0, (int)cpFile.length()); cpZipOutputStream.closeEntry(); } catch (Exception e) { throw e; } } } private static boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } boolean pathDeleted = path.delete(); return (pathDeleted); } }
package ca.ualberta.lard.model; import java.text.DecimalFormat; import java.util.ArrayList; import com.google.gson.Gson; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; /** * A GeoLocation is composed of a latitude and a longitude, and as the name * suggests it represents a location in the world. It can be set * using specific coordinates or it can be set by getting the position of * the users device in the world. */ public class GeoLocation { private double lon; private double lat; public ArrayList<GeoLocation> locations; /** * Creates a GeoLocation using the position of the device. * @param context */ public GeoLocation(Context context) { LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = lm.getBestProvider(criteria, true); Location location = lm.getLastKnownLocation(provider); if (location == null) { location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } // Can't find location. They're in compsci if (location == null) { this.lat = 53.526808 ; this.lon = -113.527127; } else { this.lon = location.getLongitude(); this.lat = location.getLatitude(); } } /** * Creates a GeoLocation using a input latitude and longitude. * @param lat the latitude of the location * @param lon the longitude of the location */ public GeoLocation (double lat, double lon) { this.lon = lon; this.lat = lat; } /** * Gets the latitude of the GeoLocation * @return the Latitude of the GeoLocation */ public double getLatitude() { return this.lat; } /** * Gets the longitude of the GeoLocation * @return the longitude of the GeoLocation */ public double getLongitude() { return this.lon; } /** * Sets the GeoLocation's latitude * @param lat the latitude of the location */ public void setLatitude(double lat) { this.lat = lat; } /** * Sets the GeoLocation's longitude * @param lon the longitude of the location */ public void setLongitude(double lon) { this.lon = lon; } public double distanceFrom(GeoLocation loc1) { int earthRadius = 6371; // earth's radius in KM - constant in source code because we don't expect this to change - ever. double dLat = Math.toRadians(this.getLatitude() - loc1.getLatitude()); double dLon = Math.toRadians(this.getLongitude() - loc1.getLongitude()); double lat1 = Math.toRadians(loc1.getLatitude()); double lat2 = Math.toRadians(this.getLatitude()); double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); double returnValue = earthRadius * c * 1000; System.out.println("Distance: " + Double.toString(returnValue)); return returnValue; } /** * Returns GeoLocation model as a json object. * @return The GeoLocation as a json object. */ public String toJSON() { Gson gson = new Gson(); String json = gson.toJson(this); return json; } /** * Returns a GeoLocation model from a Json object. * @param text The JSON string of a GeoLocation object * @return GeoLocation model */ public static GeoLocation fromJSON(String text) { Gson gson = new Gson(); GeoLocation new_model = gson.fromJson(text, GeoLocation.class); return new_model; } /** * Auto-generated by eclipse * (Source -> generate hashCode and equals) */ @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(lat); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(lon); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } /** * Returns the distance between two GeoLocations rounded to two * decimal places as a string. * @param loc The GeoLocation to calculate distance from * @return String of distance rounded to 2 decimal places */ public String roundedDistanceFrom(GeoLocation loc) { Double unrounded = this.distanceFrom(loc); DecimalFormat rounded = new DecimalFormat(" return rounded.format(unrounded); } /** * Auto-generated by eclipse * (Source -> generate hashCode and equals) * Used for comparing if two GeoLocations are equal. */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GeoLocation other = (GeoLocation) obj; if (Double.doubleToLongBits(lat) != Double.doubleToLongBits(other.lat)) return false; if (Double.doubleToLongBits(lon) != Double.doubleToLongBits(other.lon)) return false; return true; } }
package eu.ydp.empiria.player.client.util; public class PathUtil { public static String resolvePath(String path, String base){ if (path.contains("://") || path.startsWith("/")){ return path; } else { return base + path; } } }
package org.ethereum.manager; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.db.DbFlushManager; import org.ethereum.util.*; import org.ethereum.validator.BlockHeaderValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.*; @Component public class BlockLoader { private static final Logger logger = LoggerFactory.getLogger("blockqueue"); @Autowired private BlockHeaderValidator headerValidator; @Autowired SystemProperties config; @Autowired private BlockchainImpl blockchain; @Autowired DbFlushManager dbFlushManager; Scanner scanner = null; DateFormat df = new SimpleDateFormat("HH:mm:ss.SSSS"); private void blockWork(Block block) { if (block.getNumber() >= blockchain.getBestBlock().getNumber() || blockchain.getBlockByHash(block.getHash()) == null) { if (block.getNumber() > 0 && !isValid(block.getHeader())) { throw new RuntimeException(); } ImportResult result = blockchain.tryToConnect(block); if (block.getNumber() % 10 == 0) { System.out.println(df.format(new Date()) + " Imported block " + block.getShortDescr() + ": " + result + " (prework: " + exec1.getQueue().size() + ", work: " + exec2.getQueue().size() + ", blocks: " + exec1.getOrderMap().size() + ")"); } } else { if (block.getNumber() % 10000 == 0) System.out.println("Skipping block #" + block.getNumber()); } } ExecutorPipeline<Block, Block> exec1; ExecutorPipeline<Block, ?> exec2; public void loadBlocks() { exec1 = new ExecutorPipeline(8, 1000, true, new Functional.Function<Block, Block>() { @Override public Block apply(Block b) { if (b.getNumber() >= blockchain.getBestBlock().getNumber()) { for (Transaction tx : b.getTransactionsList()) { tx.getSender(); } } return b; } }, new Functional.Consumer<Throwable>() { @Override public void accept(Throwable throwable) { logger.error("Unhandled exception: ", throwable); } }); exec2 = exec1.add(1, 1000, new Functional.Consumer<Block>() { @Override public void accept(Block block) { try { blockWork(block); } catch (Exception e) { e.printStackTrace(); } } }); String fileSrc = config.blocksLoader(); try { System.out.println("Loading blocks: " + fileSrc); String blocksFormat = config.getConfig().hasPath("blocks.format") ? config.getConfig().getString("blocks.format") : null; if ("rlp".equalsIgnoreCase(blocksFormat)) { Path path = Paths.get(fileSrc); // NOT OPTIMAL, but fine for tests byte[] data = Files.readAllBytes(path); RLPList list = RLP.decode2(data); for (RLPElement item : list) { Block block = new Block(item.getRLPData()); exec1.push(block); } } else { FileInputStream inputStream = new FileInputStream(fileSrc); scanner = new Scanner(inputStream, "UTF-8"); while (scanner.hasNextLine()) { byte[] blockRLPBytes = Hex.decode(scanner.nextLine()); Block block = new Block(blockRLPBytes); exec1.push(block); } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } try { exec1.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } dbFlushManager.flush(); System.out.println(" * Done * "); System.exit(0); } private boolean isValid(BlockHeader header) { if (!headerValidator.validate(header)) { if (logger.isErrorEnabled()) headerValidator.logErrors(logger); return false; } return true; } }
package com.nostra13.universalimageloader.core.download.handlers; import android.content.Context; import android.text.TextUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import com.nostra13.universalimageloader.core.helper.FlickrServiceHelper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; /** * // TODO Class doc * * @author Matt Allen * @project UniversalImageLoader */ public class FlickrSchemeDownloader extends SchemeHandler { private static final String FORMAT = "json"; private static final String METHOD = "flickr.photos.search"; @Override public InputStream getStreamForPath(Context context, String path, Object optionForDownloader, int connectTimeout, int readTimeout) { if (TextUtils.isEmpty(path)) { return null; } else if (TextUtils.isEmpty(FlickrServiceHelper.getApiKey())) { System.err.println("The API key for Flickr must first be set by calling FlickrServiceHelper.setApiKey(String)"); return null; } else if (TextUtils.isEmpty(FlickrServiceHelper.getGroupId())) { System.err.println("The Group Id for Flickr must be set by calling FlickrServiceHelper.setGroupId(String)"); return null; } else { try { String[] splitString = path.split("/"); String getUrl = createUrl(Double.parseDouble(splitString[splitString.length - 2]), Double.parseDouble(splitString[splitString.length - 1])); BufferedReader in = new BufferedReader(new InputStreamReader(getStreamFromNetwork(getUrl, connectTimeout, readTimeout, optionForDownloader))); StringBuilder stringBuilder = new StringBuilder(); String response; try { while ((response = in.readLine()) != null) { stringBuilder.append(response); } } finally { in.close(); } Gson builder = new GsonBuilder().create(); JsonElement json = new JsonParser().parse(stringBuilder.toString()).getAsJsonObject().get("photos").getAsJsonObject().get("photo"); String imageUrl; ArrayList<Photo> photos = builder.fromJson(json, new TypeToken<ArrayList<Photo>>() { }.getType()); if (photos.size() > 0) { imageUrl = photos.get(0).getUrl(); } else { return null; } return getStreamFromNetwork(imageUrl, connectTimeout, readTimeout, optionForDownloader); } catch (IOException e) { e.printStackTrace(); return null; } } } private String createUrl(double latitude, double longitude) { return String.format("https://api.flickr.com/services/rest/?method=%s&api_key=%s&group_id=%s&lat=%s&lon=%s&format=%s&nojsoncallback=1", METHOD, FlickrServiceHelper.getApiKey(), FlickrServiceHelper.getGroupId(), String.valueOf(latitude), String.valueOf(longitude), FORMAT); } public class Photo { private String id; private String owner; private String secret; private String server; private String farm; private String title; private String isPublic; private String isFriend; private String isFamily; public String getUrl() { return String.format("https://farm%s.staticflickr.com/%s/%s_%s.jpg", farm, server, id, secret); } } }
package org.geotools.filter; import org.geotools.data.complex.XmlMappingFeatureIterator; import org.geotools.data.complex.xml.XmlXpathFilterData; import org.geotools.filter.FunctionExpressionImpl; import org.geotools.filter.capability.FunctionNameImpl; import org.geotools.util.XmlXpathUtilites; import org.jdom.Document; import org.opengis.filter.capability.FunctionName; import org.xml.sax.helpers.NamespaceSupport; public class AsXpathFunctionExpression extends FunctionExpressionImpl { /** * Make the instance of FunctionName available in a consistent spot. */ public static final FunctionName NAME = new FunctionNameImpl("asXpath", "XPATH"); public AsXpathFunctionExpression() { super(NAME.getName()); functionName = NAME; } public Object evaluate(Object object) { if (object == null || !(object instanceof XmlXpathFilterData)) { return null; } XmlXpathFilterData data = (XmlXpathFilterData) object; Document doc = data.getDoc(); String xpath = data.getItemXpath(); NamespaceSupport ns = data.getNamespaces(); // append the parameter from AsXpath() to the prefix xpath += XmlMappingFeatureIterator.XPATH_SEPARATOR + (params.get(0) == null ? "" : params.get(0).toString()); // then evaluate xpath from the xmlResponse return XmlXpathUtilites.getSingleXPathValue(ns, xpath, doc); } }
package org.eclipse.mylyn.internal.provisional.commons.ui; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IMemento; import org.eclipse.ui.XMLMemento; /** * @author Frank Becker * @author Steffen Pingel */ public class TableViewerSupport { private class TableColumnState { int width; } private int[] defaultOrder; private TableColumnState[] defaults; private final File stateFile; private final Table table; private final TableViewer viewer; private int defaultSortDirection; private int defaultSortColumnIndex; public TableViewerSupport(TableViewer viewer, File stateFile) { Assert.isNotNull(viewer); Assert.isNotNull(stateFile); this.viewer = viewer; this.table = viewer.getTable(); this.stateFile = stateFile; initialize(); restore(); } private void initialize() { TableColumn[] columns = table.getColumns(); defaults = new TableColumnState[columns.length]; defaultSortColumnIndex = -1; for (int i = 0; i < columns.length; i++) { final TableColumn column = columns[i]; column.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int direction = table.getSortDirection(); if (table.getSortColumn() == column) { direction = direction == SWT.UP ? SWT.DOWN : SWT.UP; } else { direction = SWT.DOWN; } table.setSortDirection(direction); table.setSortColumn(column); viewer.refresh(); } }); defaults[i] = new TableColumnState(); defaults[i].width = column.getWidth(); if (column == table.getSortColumn()) { defaultSortColumnIndex = i; } } defaultOrder = table.getColumnOrder(); defaultSortDirection = table.getSortDirection(); table.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { save(); } }); } public void restore() { if (stateFile.exists()) { try { FileReader reader = new FileReader(stateFile); try { XMLMemento memento = XMLMemento.createReadRoot(reader); IMemento[] children = memento.getChildren("Column"); //$NON-NLS-1$ int[] order = new int[children.length]; for (int i = 0; i < children.length; i++) { TableColumn column = table.getColumn(i); column.setWidth(children[i].getInteger("width")); //$NON-NLS-1$ order[i] = children[i].getInteger("order"); //$NON-NLS-1$ } try { table.setColumnOrder(order); } catch (IllegalArgumentException e) { // ignore } IMemento child = memento.getChild("Sort"); //$NON-NLS-1$ if (child != null) { int columnIndex = child.getInteger("column"); //$NON-NLS-1$ TableColumn column = table.getColumn(columnIndex); table.setSortColumn(column); table.setSortDirection(child.getInteger("direction")); //$NON-NLS-1$ } } catch (Exception e) { // ignore } finally { reader.close(); } } catch (IOException e) { // ignore } viewer.refresh(); } } public void restoreDefaults() { for (int index = 0; index < defaults.length; index++) { TableColumn column = table.getColumn(index); column.setWidth(defaults[index].width); } table.setColumnOrder(defaultOrder); if (defaultSortColumnIndex != -1) { table.setSortColumn(table.getColumn(defaultSortColumnIndex)); table.setSortDirection(defaultSortDirection); } else { table.setSortColumn(null); } viewer.refresh(); } public void save() { XMLMemento memento = XMLMemento.createWriteRoot("Table"); //$NON-NLS-1$ int[] order = table.getColumnOrder(); TableColumn[] columns = table.getColumns(); for (int i = 0; i < columns.length; i++) { TableColumn column = columns[i]; IMemento child = memento.createChild("Column"); //$NON-NLS-1$ child.putInteger("width", column.getWidth()); //$NON-NLS-1$ child.putInteger("order", order[i]); //$NON-NLS-1$ } TableColumn sortColumn = table.getSortColumn(); if (sortColumn != null) { IMemento child = memento.createChild("Sort"); //$NON-NLS-1$ child.putInteger("column", table.indexOf(sortColumn)); //$NON-NLS-1$ child.putInteger("direction", table.getSortDirection()); //$NON-NLS-1$ } try { FileWriter writer = new FileWriter(stateFile); try { memento.save(writer); } finally { writer.close(); } } catch (IOException e) { // ignore } } }
package org.lamport.tla.toolbox.tool.tlc.ui.editor.page; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Vector; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.HyperlinkGroup; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.IMessageManager; import org.eclipse.ui.forms.SectionPart; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormText; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.ImageHyperlink; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.forms.widgets.TableWrapData; import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationConstants; import org.lamport.tla.toolbox.tool.tlc.launch.IConfigurationDefaults; import org.lamport.tla.toolbox.tool.tlc.model.Assignment; import org.lamport.tla.toolbox.tool.tlc.model.TypedSet; import org.lamport.tla.toolbox.tool.tlc.ui.TLCUIActivator; import org.lamport.tla.toolbox.tool.tlc.ui.editor.DataBindingManager; import org.lamport.tla.toolbox.tool.tlc.ui.editor.ModelEditor; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableConstantSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.editor.part.ValidateableTableSectionPart; import org.lamport.tla.toolbox.tool.tlc.ui.preference.ITLCPreferenceConstants; import org.lamport.tla.toolbox.tool.tlc.ui.preference.TLCPreferenceInitializer; import org.lamport.tla.toolbox.tool.tlc.ui.util.DirtyMarkingListener; import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper; import org.lamport.tla.toolbox.tool.tlc.ui.util.SemanticHelper; import org.lamport.tla.toolbox.tool.tlc.util.ModelHelper; import org.lamport.tla.toolbox.util.HelpButton; import org.lamport.tla.toolbox.util.IHelpConstants; import org.lamport.tla.toolbox.util.ResourceHelper; import org.lamport.tla.toolbox.util.UIHelper; import tla2sany.semantic.ModuleNode; import util.TLCRuntime; /** * Main model page represents information for most users * <br> * This class is a a sub-class of the BasicFormPage and is used to represent the first tab of the * multi-page-editor which is used to edit the model files. * * * @author Simon Zambrovski * @version $Id$ * This is the FormPage class for the Model Overview tabbed page of * the model editor. */ public class MainModelPage extends BasicFormPage implements IConfigurationConstants, IConfigurationDefaults { public static final String ID = "MainModelPage"; public static final String TITLE = "Model Overview"; private Button noSpecRadio; // re-added on 10 Sep 2009 private Button closedFormulaRadio; private Button initNextFairnessRadio; private SourceViewer initFormulaSource; private SourceViewer nextFormulaSource; // private SourceViewer fairnessFormulaSource; private SourceViewer specSource; private Button checkDeadlockButton; private Spinner workers; private Scale maxHeapSize; private TableViewer invariantsTable; private TableViewer propertiesTable; private TableViewer constantTable; private ModifyListener widgetActivatingListener = new ModifyListener() { // select the section (radio button) the text field belong to public void modifyText(ModifyEvent e) { if (e.widget == specSource.getControl()) { noSpecRadio.setSelection(false); closedFormulaRadio.setSelection(true); initNextFairnessRadio.setSelection(false); } else if (e.widget == initFormulaSource.getControl() || e.widget == nextFormulaSource.getControl() /* || e.widget == fairnessFormulaSource.getControl() */) { noSpecRadio.setSelection(false); closedFormulaRadio.setSelection(false); initNextFairnessRadio.setSelection(true); } } }; private ImageHyperlink runLink; private ImageHyperlink generateLink; /** * section expanding adapter * {@link Hyperlink#getHref()} must deliver the section id as described in {@link DataBindingManager#bindSection(ExpandableComposite, String, String)} */ protected HyperlinkAdapter sectionExpandingAdapter = new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { String sectionId = (String) e.getHref(); // first switch to the page (and construct it if not yet // constructed) getEditor().setActivePage(AdvancedModelPage.ID); // then expand the section expandSection(sectionId); } }; private Button checkpointButton; private Text checkpointIdText; /* * Checkbox and input box for distributed model checking * * button: activate distribution * text: additional vm arguments (e.g. -Djava.rmi...) * text: pre-flight script */ private Button distributedButton; private Text distributedScriptText; private Button browseDistributedScriptButton; // The widgets to display the checkpoint size and // the delete button. private FormText chkpointSizeLabel; private Text checkpointSizeText; private Button chkptDeleteButton; /** * Used to interpolate y-values for memory scale */ private final Interpolator linearInterpolator; /** * constructs the main model page * @param editor */ public MainModelPage(FormEditor editor) { super(editor, MainModelPage.ID, MainModelPage.TITLE); this.helpId = IHelpConstants.MAIN_MODEL_PAGE; this.imagePath = "icons/full/choice_sc_obj.gif"; // available system memory final long phySysMem = TLCRuntime.getInstance().getAbsolutePhysicalSystemMemory(1.0d); // 0.) Create LinearInterpolator with two additional points 0,0 and 1,0 which int s = 0; double[] x = new double[6]; double[] y = new double[x.length]; // base point y[s] = 0d; x[s++] = 0d; // 1.) Minumum TLC requirements // Use hard-coded minfpmemsize value * 4 * 10 regardless of how big the // model is. *4 because .25 mem is used for FPs double lowerLimit = ( (TLCRuntime.MinFpMemSize / 1024 / 1024 * 4d) / phySysMem) / 2; x[s] = lowerLimit; y[s++] = 0d; // Current bloat in software is assumed to grow according to Moore's law => // 2^((Year-1993)/ 2)+2) // (1993 as base results from a statistic of windows OS memory requirements) final int currentYear = Calendar.getInstance().get(Calendar.YEAR); double estimateSoftwareBloatInMBytes = Math.pow(2, ((currentYear - 1993) / 2) + 2); // 2.) Optimal range x[s] = lowerLimit * 2d; y[s++] = 1.0d; x[s] = 1.0d - (estimateSoftwareBloatInMBytes / phySysMem); y[s++] = 1.0d; // 3.) Calculate OS reserve double upperLimit = 1.0d - (estimateSoftwareBloatInMBytes / phySysMem) / 2; x[s] = upperLimit; y[s++] = 0d; // base point x[s] = 1d; y[s] = 0d; linearInterpolator = new Interpolator(x, y); } /** * @see BasicFormPage#loadData() */ protected void loadData() throws CoreException { int specType = getConfig().getAttribute(MODEL_BEHAVIOR_SPEC_TYPE, MODEL_BEHAVIOR_TYPE_DEFAULT); // set up the radio buttons setSpecSelection(specType); // closed spec String modelSpecification = getConfig().getAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, EMPTY_STRING); Document closedDoc = new Document(modelSpecification); this.specSource.setDocument(closedDoc); // init String modelInit = getConfig().getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, EMPTY_STRING); Document initDoc = new Document(modelInit); this.initFormulaSource.setDocument(initDoc); // next String modelNext = getConfig().getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, EMPTY_STRING); Document nextDoc = new Document(modelNext); this.nextFormulaSource.setDocument(nextDoc); // fairness // String modelFairness = // getConfig().getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS, // EMPTY_STRING); // Document fairnessDoc = new Document(modelFairness); // this.fairnessFormulaSource.setDocument(fairnessDoc); // number of workers workers.setSelection(getConfig().getAttribute(LAUNCH_NUMBER_OF_WORKERS, LAUNCH_NUMBER_OF_WORKERS_DEFAULT)); // max JVM heap size final int defaultMaxHeapSize = TLCUIActivator.getDefault().getPreferenceStore().getInt( ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT); final int maxHeapSizeValue = getConfig().getAttribute(LAUNCH_MAX_HEAP_SIZE, defaultMaxHeapSize); maxHeapSize.setSelection(maxHeapSizeValue); // check deadlock boolean checkDeadlock = getConfig().getAttribute(MODEL_CORRECTNESS_CHECK_DEADLOCK, MODEL_CORRECTNESS_CHECK_DEADLOCK_DEFAULT); this.checkDeadlockButton.setSelection(checkDeadlock); // invariants List<String> serializedList = getConfig().getAttribute(MODEL_CORRECTNESS_INVARIANTS, new Vector<String>()); FormHelper.setSerializedInput(invariantsTable, serializedList); // properties serializedList = getConfig().getAttribute(MODEL_CORRECTNESS_PROPERTIES, new Vector<String>()); FormHelper.setSerializedInput(propertiesTable, serializedList); // constants from the model List<String> savedConstants = getConfig().getAttribute(MODEL_PARAMETER_CONSTANTS, new Vector<String>()); FormHelper.setSerializedInput(constantTable, savedConstants); // recover from the checkpoint boolean recover = getConfig().getAttribute(LAUNCH_RECOVER, LAUNCH_RECOVER_DEFAULT); this.checkpointButton.setSelection(recover); /* * Distributed mode */ final boolean distributed = getConfig().getAttribute(LAUNCH_DISTRIBUTED, LAUNCH_DISTRIBUTED_DEFAULT); this.distributedButton.setSelection(distributed); final String distributedScript = getConfig().getAttribute(LAUNCH_DISTRIBUTED_SCRIPT, LAUNCH_DISTRIBUTED_SCRIPT_DEFAULT); this.distributedScriptText.setText(distributedScript); } public void validatePage(boolean switchToErrorPage) { if (getManagedForm() == null) { return; } DataBindingManager dm = getDataBindingManager(); IMessageManager mm = getManagedForm().getMessageManager(); ModelEditor modelEditor = (ModelEditor) getEditor(); // The following comment was apparently written by Simon: // delete the messages // this is now done in validateRunnable // in ModelEditor // resetAllMessages(false); // validateRunnable is in ModelEditor. I believe it is executed only when // the user executes the Run or Validate Model command. // Errors that the validatePage method checks for should be cleared // whenever the method is called. I am putting this call of resetAllMessages // back. It causes the correct number of errors to be reported after // page validation. It doesn't erase the red error "X" icons that it // should, but it's better than nothing. LL 14 Mar 2013 // Note added on 19 Mar 2013: This change causes the correct number of errors // to be reported only on the Main Model Page. If I make the corresponding // change to the validatePage method of AdvancedModelPage, no errors are // shown on that page even when there are errors on the Main Model Page-- // in particular, when a new model is created and needs values for CONSTANTS. // Making the corresponding change to the validatePage method of BasicFormPage, // which is used by the subclass ResultPage, seems to do nothing. // But of course, since there is no specification for any of these methods // or for any of the Eclipse methods they call, why should I be surprised by // anything they do? resetAllMessages(false); // getting the root module node of the spec // this can be null! ModuleNode rootModuleNode = SemanticHelper.getRootModuleNode(); // setup the names from the current page getLookupHelper().resetModelNames(this); // constants in the table List<Assignment> constants = (List<Assignment>) constantTable.getInput(); // merge constants with currently defined in the specobj, if any if (rootModuleNode != null) { List<Assignment> toDelete = ModelHelper.mergeConstantLists(constants, ModelHelper.createConstantsList(rootModuleNode)); if (!toDelete.isEmpty()) { // if constants have been removed, these should be deleted from // the model too SectionPart constantSection = dm.getSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS)); if (constantSection != null) { // mark the constants dirty constantSection.markDirty(); } } constantTable.setInput(constants); } // The following string is used to test whether two differently-typed model // values appear in symmetry sets (sets of model values declared to be symmetric). // It is set to the type of the first typed model value found in a symmetry set. String symmetryType = null; // boolean symmetryUsed = false; // iterate over the constants for (int i = 0; i < constants.size(); i++) { Assignment constant = (Assignment) constants.get(i); List<String> values = Arrays.asList(constant.getParams()); // check parameters validateId(MODEL_PARAMETER_CONSTANTS, values, "param1_", "A parameter name"); // the constant is still in the list if (constant.getRight() == null || EMPTY_STRING.equals(constant.getRight())) { // right side of assignment undefined modelEditor.addErrorMessage(constant.getLabel(), "Provide a value for constant " + constant.getLabel(), this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm .getAttributeControl(MODEL_PARAMETER_CONSTANTS))); setComplete(false); expandSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS)); } else { if (constant.isSetOfModelValues()) { TypedSet modelValuesSet = TypedSet.parseSet(constant.getRight()); if (constant.isSymmetricalSet()) { boolean hasTwoTypes = false; // set true if this symmetry set has two differently-typed model // values. String typeString = null; // set to the type of the first typed model value in this symmetry // set. if (modelValuesSet.hasType()) { typeString = modelValuesSet.getType(); } else { for (int j = 0; j < modelValuesSet.getValues().length; j++) { String thisTypeString = TypedSet.getTypeOfId(modelValuesSet.getValues()[j]); if (thisTypeString != null) { if (typeString != null && !typeString.equals(thisTypeString)) { hasTwoTypes = true; } else { typeString = thisTypeString; } } } } if (hasTwoTypes || (symmetryType != null && typeString != null && !typeString.equals(symmetryType))) { modelEditor.addErrorMessage(constant.getLabel(), "Two differently typed model values used in symmetry sets.", this.getId()/*constant*/, IMessageProvider.ERROR, UIHelper.getWidget(dm .getAttributeControl(MODEL_PARAMETER_CONSTANTS))); setComplete(false); expandSection(dm.getSectionForAttribute(MODEL_PARAMETER_CONSTANTS)); } else { if (typeString != null) { symmetryType = typeString; } } // symmetry can be used for only one set of model values } if (modelValuesSet.getValueCount() > 0) { // there were values defined // check if those are numbers? /* * if (modelValuesSet.hasANumberOnlyValue()) { * mm.addMessage("modelValues1", * "A model value can not be an number", modelValuesSet, * IMessageProvider.ERROR, constantTable.getTable()); * setComplete(false); } */ List<String> mvList = modelValuesSet.getValuesAsList(); // check list of model values validateUsage(MODEL_PARAMETER_CONSTANTS, mvList, "modelValues2_", "A model value", "Constant Assignment", true); // check if the values are correct ids validateId(MODEL_PARAMETER_CONSTANTS, mvList, "modelValues2_", "A model value"); // get widget for model values assigned to constant Control widget = UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_CONSTANTS)); // check if model values are config file keywords for (int j = 0; j < mvList.size(); j++) { String value = (String) mvList.get(j); if (SemanticHelper.isConfigFileKeyword(value)) { modelEditor.addErrorMessage(value, "The toolbox cannot handle the model value " + value + ".", this.getId(), IMessageProvider.ERROR, widget); setComplete(false); } } } else { // This made an error by LL on 15 Nov 2009 modelEditor.addErrorMessage(constant.getLabel(), "The set of model values should not be empty.", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm.getAttributeControl(MODEL_PARAMETER_CONSTANTS))); setComplete(false); } } } // the constant identifier is a config file keyword if (SemanticHelper.isConfigFileKeyword(constant.getLabel())) { modelEditor.addErrorMessage(constant.getLabel(), "The toolbox cannot handle the constant identifier " + constant.getLabel() + ".", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm .getAttributeControl(MODEL_PARAMETER_CONSTANTS))); setComplete(false); } } // iterate over the constants again, and check if the parameters are used as Model Values for (int i = 0; i < constants.size(); i++) { Assignment constant = (Assignment) constants.get(i); List<String> values = Arrays.asList(constant.getParams()); // check list of parameters validateUsage(MODEL_PARAMETER_CONSTANTS, values, "param1_", "A parameter name", "Constant Assignment", false); } // number of workers int number = workers.getSelection(); if (number > Runtime.getRuntime().availableProcessors()) { modelEditor.addErrorMessage("strangeNumber1", "Specified number of workers is " + number + ". The number of processors available on the system is " + Runtime.getRuntime().availableProcessors() + ".\n The number of workers should not exceed the number of processors.", this.getId(), IMessageProvider.WARNING, UIHelper.getWidget(dm .getAttributeControl(LAUNCH_NUMBER_OF_WORKERS))); expandSection(SEC_HOW_TO_RUN); } // legacy value? // better handle legacy models try { final int defaultMaxHeapSize = TLCUIActivator .getDefault() .getPreferenceStore() .getInt(ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT); final int legacyValue = getConfig().getAttribute( LAUNCH_MAX_HEAP_SIZE, defaultMaxHeapSize); // old default, silently convert to new default if (legacyValue == 500) { getConfig().setAttribute( LAUNCH_MAX_HEAP_SIZE, TLCPreferenceInitializer.MAX_HEAP_SIZE_DEFAULT); maxHeapSize.setSelection(TLCPreferenceInitializer.MAX_HEAP_SIZE_DEFAULT); } else if (legacyValue >= 100) { modelEditor .addErrorMessage( "strangeNumber1", "Found legacy value for physically memory of (" + legacyValue + "mb) that needs manual conversion. 25% is a safe setting on most computers.", this.getId(), IMessageProvider.WARNING, maxHeapSize); setComplete(false); expandSection(SEC_HOW_TO_RUN); } } catch (CoreException e) { TLCUIActivator.getDefault().logWarning("Faild to read heap value", e); } // max heap size // color the scale according to OS and TLC requirements int maxHeapSizeValue = maxHeapSize.getSelection(); double x = maxHeapSizeValue / 100d; float y = (float) linearInterpolator.interpolate(x); maxHeapSize.setBackground(new Color(Display.getDefault(), new RGB( 120 * y, 1 - y, 1f))); // fill the checkpoints updateCheckpoints(); // recover from checkpoint if (checkpointButton.getSelection()) { if (EMPTY_STRING.equals(checkpointIdText.getText())) { modelEditor.addErrorMessage("noChckpoint", "No checkpoint data found", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm.getAttributeControl(LAUNCH_RECOVER))); setComplete(false); expandSection(SEC_HOW_TO_RUN); } } // The following code added by LL and DR on 10 Sep 2009. // Reset the enabling and selection of spec type depending on the number number // of variables in the spec. // This code needs to be modified when we modify the model launcher // to allow the No Spec option to be selected when there are variables. if (rootModuleNode != null) { if (rootModuleNode.getVariableDecls().length == 0) { setHasVariables(false); // set selection to the NO SPEC field if (!noSpecRadio.getSelection()) { // mark dirty so that changes must be written to config file setSpecSelection(MODEL_BEHAVIOR_TYPE_NO_SPEC); dm.getSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_NO_SPEC)).markDirty(); } } else { setHasVariables(true); // if there are variables, the user // may still want to choose no spec // so the selection is not changed // if (noSpecRadio.getSelection()) // // mark dirty so that changes must be written to config file // dm.getSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION)).markDirty(); // // set selection to the default // setSpecSelection(MODEL_BEHAVIOR_TYPE_DEFAULT); } } // This code disables or enables sections // depending on whether whether no spec is selected // or not. // This must occur after the preceeding code in case // that code changes the selection. Section whatToCheckSection = dm.getSection(SEC_WHAT_TO_CHECK).getSection(); if (noSpecRadio.getSelection()) { whatToCheckSection.setExpanded(false); whatToCheckSection.setEnabled(false); } else { whatToCheckSection.setExpanded(true); whatToCheckSection.setEnabled(true); } // The following code is not needed now because we automatically change // the selection to No Spec if there are no variables. // if (selectedAttribute != null) { // // the user selected to use a spec // // check if there are variables declared // if (rootModuleNode != null // && rootModuleNode.getVariableDecls().length == 0) { // // no variables => install an error // mm.addMessage("noVariables", // "There were no variables declared in the root module", // null, IMessageProvider.ERROR, UIHelper.getWidget(dm // .getAttributeControl(selectedAttribute))); // setComplete(false); // expandSection(dm.getSectionForAttribute(selectedAttribute)); // check if the selected fields are filled if (closedFormulaRadio.getSelection() && specSource.getDocument().get().trim().equals("")) { modelEditor.addErrorMessage("noSpec", "The formula must be provided", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm.getAttributeControl(MODEL_BEHAVIOR_CLOSED_SPECIFICATION))); setComplete(false); expandSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION)); } else if (initNextFairnessRadio.getSelection()) { String init = initFormulaSource.getDocument().get().trim(); String next = nextFormulaSource.getDocument().get().trim(); if (init.equals("")) { modelEditor.addErrorMessage("noInit", "The Init formula must be provided", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm .getAttributeControl(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT))); setComplete(false); expandSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT)); } if (next.equals("")) { modelEditor.addErrorMessage("noNext", "The Next formula must be provided", this.getId(), IMessageProvider.ERROR, UIHelper.getWidget(dm .getAttributeControl(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT))); setComplete(false); expandSection(dm.getSectionForAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT)); } } // enablement for distributed input text boxes depends on button boolean distributed = this.distributedButton.getSelection(); this.distributedScriptText.setEnabled(distributed); // verify existence of pre-flight script // if(distributed) { // final String scriptPath = distributedScriptText.getText(); // if(scriptPath != null && !"".equals(scriptPath)) { // final File f = new File(scriptPath); // if(!f.exists()) { // modelEditor.addErrorMessage("noScript", "No script file found", this.getId(), // IMessageProvider.ERROR, UIHelper.getWidget(dm.getAttributeControl(LAUNCH_DISTRIBUTED_SCRIPT))); // setComplete(false); // expandSection(SEC_HOW_TO_RUN); mm.setAutoUpdate(true); super.validatePage(switchToErrorPage); } /** * This method is used to enable and disable UI widgets depending on the fact if the specification * has variables. * @param hasVariables true if the spec contains variables */ private void setHasVariables(boolean hasVariables) { // the no spec option can be selected if there // are variables or no variables // this.noSpecRadio.setEnabled(!hasVariables); this.closedFormulaRadio.setEnabled(hasVariables); this.initNextFairnessRadio.setEnabled(hasVariables); // the input fields are enabled only if there are variables this.initFormulaSource.getControl().setEnabled(hasVariables); this.nextFormulaSource.getControl().setEnabled(hasVariables); this.specSource.getControl().setEnabled(hasVariables); } /** * This method sets the selection on the * @param selectedFormula */ private void setSpecSelection(int specType) { switch (specType) { case MODEL_BEHAVIOR_TYPE_NO_SPEC: this.noSpecRadio.setSelection(true); this.initNextFairnessRadio.setSelection(false); this.closedFormulaRadio.setSelection(false); break; case MODEL_BEHAVIOR_TYPE_SPEC_CLOSED: this.noSpecRadio.setSelection(false); this.initNextFairnessRadio.setSelection(false); this.closedFormulaRadio.setSelection(true); break; case MODEL_BEHAVIOR_TYPE_SPEC_INIT_NEXT: this.noSpecRadio.setSelection(false); this.initNextFairnessRadio.setSelection(true); this.closedFormulaRadio.setSelection(false); break; default: throw new IllegalArgumentException("Wrong spec type, this is a bug"); } } /** * Save data back to model */ public void commit(boolean onSave) { // TLCUIActivator.getDefault().logDebug("Main page commit"); // closed formula String closedFormula = FormHelper.trimTrailingSpaces(this.specSource.getDocument().get()); getConfig().setAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, closedFormula); // init formula String initFormula = FormHelper.trimTrailingSpaces(this.initFormulaSource.getDocument().get()); getConfig().setAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, initFormula); // next formula String nextFormula = FormHelper.trimTrailingSpaces(this.nextFormulaSource.getDocument().get()); getConfig().setAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, nextFormula); // fairness formula // String fairnessFormula = // FormHelper.trimTrailingSpaces(this.fairnessFormulaSource.getDocument().get()); // getConfig().setAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS, // fairnessFormula); // mode int specType; if (this.closedFormulaRadio.getSelection()) { specType = MODEL_BEHAVIOR_TYPE_SPEC_CLOSED; } else if (this.initNextFairnessRadio.getSelection()) { specType = MODEL_BEHAVIOR_TYPE_SPEC_INIT_NEXT; } else if (this.noSpecRadio.getSelection()) { specType = MODEL_BEHAVIOR_TYPE_NO_SPEC; } else { specType = MODEL_BEHAVIOR_TYPE_DEFAULT; } getConfig().setAttribute(MODEL_BEHAVIOR_SPEC_TYPE, specType); // number of workers getConfig().setAttribute(LAUNCH_NUMBER_OF_WORKERS, workers.getSelection()); int maxHeapSizeValue = TLCUIActivator.getDefault().getPreferenceStore().getInt( ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT); maxHeapSizeValue = maxHeapSize.getSelection(); getConfig().setAttribute(LAUNCH_MAX_HEAP_SIZE, maxHeapSizeValue); // recover from deadlock boolean recover = this.checkpointButton.getSelection(); getConfig().setAttribute(LAUNCH_RECOVER, recover); // check deadlock boolean checkDeadlock = this.checkDeadlockButton.getSelection(); getConfig().setAttribute(MODEL_CORRECTNESS_CHECK_DEADLOCK, checkDeadlock); // run in distributed mode boolean distributed = this.distributedButton.getSelection(); getConfig().setAttribute(LAUNCH_DISTRIBUTED, distributed); final String distributedScript = this.distributedScriptText.getText(); getConfig().setAttribute(LAUNCH_DISTRIBUTED_SCRIPT, distributedScript); // invariants List<String> serializedList = FormHelper.getSerializedInput(invariantsTable); getConfig().setAttribute(MODEL_CORRECTNESS_INVARIANTS, serializedList); // properties serializedList = FormHelper.getSerializedInput(propertiesTable); getConfig().setAttribute(MODEL_CORRECTNESS_PROPERTIES, serializedList); // constants List<String> constants = FormHelper.getSerializedInput(constantTable); getConfig().setAttribute(MODEL_PARAMETER_CONSTANTS, constants); // variables String variables = ModelHelper.createVariableList(SemanticHelper.getRootModuleNode()); getConfig().setAttribute(MODEL_BEHAVIOR_VARS, variables); super.commit(onSave); } /** * Checks if checkpoint information changed */ private void updateCheckpoints() { IResource[] checkpoints = null; try { // checkpoint id checkpoints = ModelHelper.getCheckpoints(getConfig(), false); } catch (CoreException e) { TLCUIActivator.getDefault().logError("Error checking chekpoint data", e); } if (checkpoints != null && checkpoints.length > 0) { this.checkpointIdText.setText(checkpoints[0].getName()); } else { this.checkpointIdText.setText(EMPTY_STRING); } if ((checkpoints == null) || (checkpoints.length == 0)) { checkpointSizeText.setVisible(false); chkpointSizeLabel.setVisible(false); chkptDeleteButton.setVisible(false); } else { checkpointSizeText.setText(String.valueOf(ResourceHelper.getSizeOfJavaFileResource(checkpoints[0]) / 1000)); checkpointSizeText.setVisible(true); chkpointSizeLabel.setVisible(true); chkptDeleteButton.setVisible(true); } } protected void createBodyContent(IManagedForm managedForm) { DataBindingManager dm = getDataBindingManager(); int sectionFlags = Section.TITLE_BAR | Section.DESCRIPTION | Section.TREE_NODE; FormToolkit toolkit = managedForm.getToolkit(); Composite body = managedForm.getForm().getBody(); GridData gd; TableWrapData twd; /* * Because the two Composite objects `left' and `right' are added to the * object `body' in this order, `left' is displayed to the left of `right'. */ // left Composite left = toolkit.createComposite(body); twd = new TableWrapData(TableWrapData.FILL_GRAB); twd.grabHorizontal = true; left.setLayout(new GridLayout(1, false)); left.setLayoutData(twd); // right Composite right = toolkit.createComposite(body); twd = new TableWrapData(TableWrapData.FILL_GRAB); twd.grabHorizontal = true; right.setLayoutData(twd); right.setLayout(new GridLayout(1, false)); Section section; GridLayout layout; // what is the spec section = FormHelper.createSectionComposite(left, "What is the behavior spec?", "", toolkit, sectionFlags | Section.EXPANDED, getExpansionListener()); // only grab horizontal space gd = new GridData(GridData.FILL_HORIZONTAL); section.setLayoutData(gd); Composite behaviorArea = (Composite) section.getClient(); layout = new GridLayout(); layout.numColumns = 2; behaviorArea.setLayout(layout); ValidateableSectionPart behaviorPart = new ValidateableSectionPart(section, this, SEC_WHAT_IS_THE_SPEC); managedForm.addPart(behaviorPart); DirtyMarkingListener whatIsTheSpecListener = new DirtyMarkingListener(behaviorPart, true); // split formula option initNextFairnessRadio = toolkit.createButton(behaviorArea, "Initial predicate and next-state relation", SWT.RADIO); initNextFairnessRadio.addFocusListener(focusListener); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; initNextFairnessRadio.setLayoutData(gd); initNextFairnessRadio.addSelectionListener(whatIsTheSpecListener); initNextFairnessRadio.addFocusListener(focusListener); // init toolkit.createLabel(behaviorArea, "Init:"); initFormulaSource = FormHelper.createFormsSourceViewer(toolkit, behaviorArea, SWT.NONE | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); gd.heightHint = 18; initFormulaSource.getTextWidget().setLayoutData(gd); initFormulaSource.getTextWidget().addModifyListener(whatIsTheSpecListener); initFormulaSource.getTextWidget().addModifyListener(widgetActivatingListener); initFormulaSource.getTextWidget().addFocusListener(focusListener); dm.bindAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, initFormulaSource, behaviorPart); // next toolkit.createLabel(behaviorArea, "Next:"); nextFormulaSource = FormHelper.createFormsSourceViewer(toolkit, behaviorArea, SWT.NONE | SWT.SINGLE); gd = new GridData(GridData.FILL_HORIZONTAL); gd.heightHint = 18; nextFormulaSource.getTextWidget().setLayoutData(gd); nextFormulaSource.getTextWidget().addModifyListener(whatIsTheSpecListener); nextFormulaSource.getTextWidget().addModifyListener(widgetActivatingListener); nextFormulaSource.getTextWidget().addFocusListener(focusListener); dm.bindAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, nextFormulaSource, behaviorPart); // fairness // toolkit.createLabel(behaviorArea, "Fairness:"); // fairnessFormulaSource = FormHelper.createSourceViewer(toolkit, // behaviorArea, SWT.NONE | SWT.SINGLE); // gd = new GridData(GridData.FILL_HORIZONTAL); // gd.heightHint = 18; // fairnessFormulaSource.getTextWidget().setLayoutData(gd); // fairnessFormulaSource.getTextWidget().addModifyListener(whatIsTheSpecListener); // fairnessFormulaSource.getTextWidget().addModifyListener(widgetActivatingListener); // dm.bindAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS, // fairnessFormulaSource, behaviorPart); // closed formula option closedFormulaRadio = toolkit.createButton(behaviorArea, "Temporal formula", SWT.RADIO); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; closedFormulaRadio.setLayoutData(gd); closedFormulaRadio.addSelectionListener(whatIsTheSpecListener); // spec Label specLabel = toolkit.createLabel(behaviorArea, ""); // changed from "Spec:" 10 Sep 09 gd = new GridData(); gd.verticalAlignment = SWT.TOP; specLabel.setLayoutData(gd); specSource = FormHelper.createFormsSourceViewer(toolkit, behaviorArea, SWT.V_SCROLL); gd = new GridData(GridData.FILL_HORIZONTAL); gd.heightHint = 55; specSource.getTextWidget().setLayoutData(gd); specSource.getTextWidget().addModifyListener(whatIsTheSpecListener); specSource.getTextWidget().addModifyListener(widgetActivatingListener); dm.bindAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, specSource, behaviorPart); noSpecRadio = toolkit.createButton(behaviorArea, "No Behavior Spec", SWT.RADIO); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; noSpecRadio.setLayoutData(gd); noSpecRadio.addSelectionListener(whatIsTheSpecListener); dm.bindAttribute(MODEL_BEHAVIOR_NO_SPEC, noSpecRadio, behaviorPart); // what to check section = FormHelper.createSectionComposite(left, "What to check?", "", toolkit, sectionFlags | Section.EXPANDED, getExpansionListener()); // only grab horizontal space gd = new GridData(GridData.FILL_HORIZONTAL); section.setLayoutData(gd); Composite toBeCheckedArea = (Composite) section.getClient(); layout = new GridLayout(); layout.numColumns = 1; toBeCheckedArea.setLayout(layout); checkDeadlockButton = toolkit.createButton(toBeCheckedArea, "Deadlock", SWT.CHECK); ValidateableSectionPart toBeCheckedPart = new ValidateableSectionPart(section, this, SEC_WHAT_TO_CHECK); managedForm.addPart(toBeCheckedPart); DirtyMarkingListener whatToCheckListener = new DirtyMarkingListener(toBeCheckedPart, true); checkDeadlockButton.addSelectionListener(whatToCheckListener); // Invariants ValidateableTableSectionPart invariantsPart = new ValidateableTableSectionPart(toBeCheckedArea, "Invariants", "Formulas true in every reachable state.", toolkit, sectionFlags, this, SEC_WHAT_TO_CHECK_INVARIANTS); managedForm.addPart(invariantsPart); invariantsTable = invariantsPart.getTableViewer(); dm.bindAttribute(MODEL_CORRECTNESS_INVARIANTS, invariantsTable, invariantsPart); // Properties // The following code added by LL on 29 May 2010 to expand the Property section // and reset the MODEL_PROPERTIES_EXPAND property to "" if that property has // been set to a non-"" value. int propFlags = sectionFlags; try { if (!((String) getConfig().getAttribute(MODEL_PROPERTIES_EXPAND, "")).equals("")) { propFlags = propFlags | Section.EXPANDED; getConfig().setAttribute(MODEL_PROPERTIES_EXPAND, ""); } } catch (CoreException e) { // I don't know why such an exception might occur, but there's no // great harm if it does. LL e.printStackTrace(); } ValidateableTableSectionPart propertiesPart = new ValidateableTableSectionPart(toBeCheckedArea, "Properties", "Temporal formulas true for every possible behavior.", toolkit, propFlags, this, SEC_WHAT_TO_CHECK_PROPERTIES); managedForm.addPart(propertiesPart); propertiesTable = propertiesPart.getTableViewer(); dm.bindAttribute(MODEL_CORRECTNESS_PROPERTIES, propertiesTable, propertiesPart); // what is the model // Constants ValidateableConstantSectionPart constantsPart = new ValidateableConstantSectionPart(right, "What is the model?", "Specify the values of declared constants.", toolkit, sectionFlags | Section.EXPANDED, this, SEC_WHAT_IS_THE_MODEL); managedForm.addPart(constantsPart); constantTable = constantsPart.getTableViewer(); dm.bindAttribute(MODEL_PARAMETER_CONSTANTS, constantTable, constantsPart); Composite parametersArea = (Composite) constantsPart.getSection().getClient(); HyperlinkGroup group = new HyperlinkGroup(parametersArea.getDisplay()); // TESTING XXXXXX // managedForm.removePart(constantsPart); // Control saved = right.getChildren()[0] ; // constantTable.getTable().setSize(1000, 1000); // constantTable.getTable().setVisible(false); // System.out.println("GetSize returns " + // constantTable.getTable().getSize().x); // right.getChildren()[0].setVisible(false); // parametersArea.setVisible(false); // create a composite to put the text into Composite linksPanelToAdvancedPage = toolkit.createComposite(parametersArea); gd = new GridData(); gd.horizontalSpan = 2; linksPanelToAdvancedPage.setLayoutData(gd); linksPanelToAdvancedPage.setLayout(new FillLayout(SWT.VERTICAL)); // first line with hyperlinks Composite elementLine = toolkit.createComposite(linksPanelToAdvancedPage); elementLine.setLayout(new FillLayout(SWT.HORIZONTAL)); // the text FormText labelText = toolkit.createFormText(elementLine, false); labelText.setText("Advanced parts of the model:", false, false); // the hyperlinks Hyperlink hyper; hyper = toolkit.createHyperlink(elementLine, "Additional definitions,", SWT.NONE); hyper.setHref(SEC_NEW_DEFINITION); hyper.addHyperlinkListener(sectionExpandingAdapter); hyper = toolkit.createHyperlink(elementLine, "Definition override,", SWT.NONE); hyper.setHref(SEC_DEFINITION_OVERRIDE); hyper.addHyperlinkListener(sectionExpandingAdapter); // second line with hyperlinks Composite elementLine2 = toolkit.createComposite(linksPanelToAdvancedPage); elementLine2.setLayout(new FillLayout(SWT.HORIZONTAL)); hyper = toolkit.createHyperlink(elementLine2, "State constraints,", SWT.NONE); hyper.setHref(SEC_STATE_CONSTRAINT); hyper.addHyperlinkListener(sectionExpandingAdapter); hyper = toolkit.createHyperlink(elementLine2, "Action constraints,", SWT.NONE); hyper.setHref(SEC_ACTION_CONSTRAINT); hyper.addHyperlinkListener(sectionExpandingAdapter); hyper = toolkit.createHyperlink(elementLine2, "Additional model values.", SWT.NONE); hyper.setHref(SEC_MODEL_VALUES); hyper.addHyperlinkListener(sectionExpandingAdapter); // run tab section = FormHelper.createSectionComposite(right, "How to run?", "TLC Parameters", toolkit, sectionFlags, getExpansionListener()); gd = new GridData(GridData.FILL_HORIZONTAL); section.setLayoutData(gd); final Composite howToRunArea = (Composite) section.getClient(); group = new HyperlinkGroup(howToRunArea.getDisplay()); layout = new GridLayout(2, true); howToRunArea.setLayout(layout); ValidateableSectionPart howToRunPart = new ValidateableSectionPart(section, this, SEC_HOW_TO_RUN); managedForm.addPart(howToRunPart); DirtyMarkingListener howToRunListener = new DirtyMarkingListener(howToRunPart, true); /* * Workers Spinner */ // label workers FormText workersLabel = toolkit.createFormText(howToRunArea, true); workersLabel.setText("Number of worker threads:", false, false); // field workers workers = new Spinner(howToRunArea, SWT.NONE); workers.addSelectionListener(howToRunListener); workers.addFocusListener(focusListener); gd = new GridData(); gd.horizontalIndent = 10; gd.widthHint = 40; workers.setLayoutData(gd); workers.setMinimum(1); workers.setPageIncrement(1); workers.setToolTipText("Determines how many threads will be spawned working on the next state relation."); workers.setSelection(IConfigurationDefaults.LAUNCH_NUMBER_OF_WORKERS_DEFAULT); dm.bindAttribute(LAUNCH_NUMBER_OF_WORKERS, workers, howToRunPart); /* * MapHeap Scale */ // max heap size label FormText maxHeapLabel = toolkit.createFormText(howToRunArea, true); maxHeapLabel.setText("Fraction of physical memory allocated to TLC:", false, false); // Create a composite inside the right "cell" of the "how to run" // section grid layout to fit the scale and the maxHeapSizeFraction // label into a single row. final Composite maxHeapScale = new Composite(howToRunArea, SWT.NONE); layout = new GridLayout(2, false); maxHeapScale.setLayout(layout); // field max heap size int defaultMaxHeapSize = TLCUIActivator.getDefault().getPreferenceStore().getInt( ITLCPreferenceConstants.I_TLC_MAXIMUM_HEAP_SIZE_DEFAULT); maxHeapSize = new Scale(maxHeapScale, SWT.NONE); maxHeapSize.addSelectionListener(howToRunListener); maxHeapSize.addFocusListener(focusListener); gd = new GridData(); gd.horizontalIndent = 0; gd.widthHint = 250; maxHeapSize.setLayoutData(gd); maxHeapSize.setMaximum(99); maxHeapSize.setMinimum(1); maxHeapSize.setPageIncrement(5); maxHeapSize.setSelection(defaultMaxHeapSize); maxHeapSize.setToolTipText("Specifies the heap size of the Java VM that runs TLC."); dm.bindAttribute(LAUNCH_MAX_HEAP_SIZE, maxHeapSize, howToRunPart); // label next to the scale showing the current fraction selected final FormText maxHeapSizeFraction = toolkit.createFormText(maxHeapScale, false); final TLCRuntime instance = TLCRuntime.getInstance(); long memory = instance.getAbsolutePhysicalSystemMemory(defaultMaxHeapSize / 100d); maxHeapSizeFraction.setText(defaultMaxHeapSize + "%" + " (" + memory + " mb)", false, false); maxHeapSize.addPaintListener(new PaintListener() { /* (non-Javadoc) * @see org.eclipse.swt.events.PaintListener#paintControl(org.eclipse.swt.events.PaintEvent) */ public void paintControl(PaintEvent e) { // update the label int value = ((Scale) e.getSource()).getSelection(); final TLCRuntime instance = TLCRuntime.getInstance(); long memory = instance.getAbsolutePhysicalSystemMemory(value / 100d); maxHeapSizeFraction.setText(value + "%" + " (" + memory + " mb)" , false, false); } }); // // label workers // FormText workersLabel = toolkit.createFormText(howToRunArea, true); // workersLabel.setText("Number of worker threads:", false, false); // // field workers // workers = toolkit.createText(howToRunArea, "1"); // workers.addModifyListener(howToRunListener); // workers.addFocusListener(focusListener); // gd = new GridData(); // gd.horizontalIndent = 10; // gd.widthHint = 40; // workers.setLayoutData(gd); // dm.bindAttribute(LAUNCH_NUMBER_OF_WORKERS, workers, howToRunPart); /* * run from the checkpoint. Checkpoint help button added by LL on 17 Jan 2013 */ Composite ckptComp = new Composite(howToRunArea, SWT.NONE) ; layout = new GridLayout(2, true); ckptComp.setLayout(layout); gd = new GridData(); gd.horizontalSpan = 2; gd.verticalIndent = 20; ckptComp.setLayoutData(gd); checkpointButton = toolkit.createButton(ckptComp, "Recover from checkpoint", SWT.CHECK); checkpointButton.addSelectionListener(howToRunListener); checkpointButton.addFocusListener(focusListener); Button ckptHelpButton = HelpButton.helpButton(ckptComp, "model/overview-page.html#checkpoint") ; FormText chkpointIdLabel = toolkit.createFormText(howToRunArea, true); chkpointIdLabel.setText("Checkpoint ID:", false, false); checkpointIdText = toolkit.createText(howToRunArea, ""); checkpointIdText.setEditable(false); gd = new GridData(); gd.horizontalIndent = 10; gd.widthHint = 100; checkpointIdText.setLayoutData(gd); dm.bindAttribute(LAUNCH_RECOVER, checkpointButton, howToRunPart); chkpointSizeLabel = toolkit.createFormText(howToRunArea, true); chkpointSizeLabel.setText("Checkpoint size (kbytes):", false, false); checkpointSizeText = toolkit.createText(howToRunArea, ""); gd = new GridData(); gd.horizontalIndent = 10; gd.widthHint = 100; checkpointSizeText.setLayoutData(gd); chkptDeleteButton = toolkit.createButton(howToRunArea, "Delete Checkpoint", SWT.PUSH); chkptDeleteButton.addSelectionListener(new SelectionListener() { /* (non-Javadoc) * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { final IResource[] checkpoints; try { checkpoints = ModelHelper.getCheckpoints(getConfig(), false); if ((checkpoints != null) && checkpoints.length > 0) { ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { checkpoints[0].delete(true, new SubProgressMonitor(monitor, 1)); } }, null); } } catch (CoreException e1) { return; } } /* (non-Javadoc) * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetDefaultSelected(SelectionEvent e) { } }); chkptDeleteButton.addFocusListener(focusListener); /* * Distribution. Help button added by LL on 17 Jan 2013 */ Composite distComp = new Composite(howToRunArea, SWT.NONE) ; layout = new GridLayout(2, true); distComp.setLayout(layout); gd = new GridData(); gd.horizontalSpan = 2; distComp.setLayoutData(gd); distributedButton = toolkit.createButton(distComp, "Run in distributed mode", SWT.CHECK); Button distHelpButton = HelpButton.helpButton(distComp, "model/distributed-mode.html") ; distributedButton.addSelectionListener(howToRunListener); distributedButton.setToolTipText("If checked, state computation will be performed by (remote) workers."); distributedButton.addFocusListener(focusListener); /* * pre-flight script executed prior to distributed TLC (e.g. to start remote workers) */ FormText distributedLabel = toolkit.createFormText(howToRunArea, true); distributedLabel.setText("Pre Flight Script:", false, false); // non-editable text input distributedScriptText = toolkit.createText(howToRunArea, ""); distributedScriptText.setEditable(true); distributedScriptText .setToolTipText("Optionally pass a pre-flight script to be run prior to the TLC process (e.g. to start remote workers)"); distributedScriptText.addModifyListener(howToRunListener); gd = new GridData(); gd.horizontalIndent = 10; gd.widthHint = 300; distributedScriptText.setLayoutData(gd); dm.bindAttribute(LAUNCH_DISTRIBUTED_SCRIPT, distributedScriptText, howToRunPart); // skip the left cell in the grid layout final Text invisibleText = toolkit.createText(howToRunArea, ""); invisibleText.setEditable(false); invisibleText.setVisible(false); invisibleText.setEnabled(false); // browse button right-aligned browseDistributedScriptButton = toolkit.createButton(howToRunArea, "Browse", SWT.PUSH); gd = new GridData(GridData.HORIZONTAL_ALIGN_END); browseDistributedScriptButton.setLayoutData(gd); browseDistributedScriptButton.addSelectionListener(new SelectionListener() { /* (non-Javadoc) * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { // prompt user for a file final FileDialog fd = new FileDialog(getSite().getShell(), SWT.OPEN); final String oldPath = distributedScriptText.getText(); fd.setFileName(oldPath); // use user-provided path as input for script input text box final String path = fd.open(); distributedScriptText.setText((path != null) ? path : oldPath); } /* (non-Javadoc) * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetDefaultSelected(SelectionEvent e) { //nop } }); // deactivate because domain logic is not done yet distributedLabel.setVisible(false); distributedScriptText.setVisible(false); browseDistributedScriptButton.setVisible(false); /* * run link */ runLink = toolkit.createImageHyperlink(howToRunArea, SWT.NONE); runLink.setImage(createRegisteredImage("icons/full/lrun_obj.gif")); runLink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { doRun(); } }); runLink.setText("Run TLC"); gd = new GridData(); gd.horizontalSpan = 2; gd.widthHint = 200; gd.verticalIndent = 20; runLink.setLayoutData(gd); group.add(runLink); generateLink = toolkit.createImageHyperlink(howToRunArea, SWT.NONE); generateLink.setImage(createRegisteredImage("icons/full/debugt_obj.gif")); generateLink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { doGenerate(); } }); generateLink.setText("Validate model"); gd = new GridData(); gd.horizontalSpan = 2; gd.widthHint = 200; generateLink.setLayoutData(gd); group.add(generateLink); // add listeners propagating the changes of the elements to the changes // of the // parts to the list to be activated after the values has been loaded dirtyPartListeners.add(whatIsTheSpecListener); dirtyPartListeners.add(whatToCheckListener); dirtyPartListeners.add(howToRunListener); } /** * On a refresh, the checkpoint information is re-read */ public void refresh() { super.refresh(); updateCheckpoints(); } /** * Interpolates based on LinearInterpolation */ private class Interpolator { private final double[] yCoords, xCoords; public Interpolator(double[] x, double[] y) { this.xCoords = x; this.yCoords = y; } public double interpolate(double x) { for (int i = 1; i < xCoords.length; i++) { if (x < xCoords[i]) { return yCoords[i] - (yCoords[i] - yCoords[i - 1]) * (xCoords[i] - x) / (xCoords[i] - xCoords[i - 1]); } } return 0d; } } }
package sk.henrichg.phoneprofilesplus; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.preference.DialogPreference; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import com.afollestad.materialdialogs.MaterialDialog; import java.util.List; public class ApplicationsMultiSelectDialogPreference extends DialogPreference { Context _context = null; String value = ""; // Layout widgets. private ListView listView = null; private LinearLayout linlaProgress; private LinearLayout linlaListView; ImageView packageIcon; RelativeLayout packageIcons; ImageView packageIcon1; ImageView packageIcon2; ImageView packageIcon3; ImageView packageIcon4; private ApplicationsMultiselectPreferenceAdapter listAdapter; public ApplicationsMultiSelectDialogPreference(Context context, AttributeSet attrs) { super(context, attrs); _context = context; setWidgetLayoutResource(R.layout.applications_preference); // resource na layout custom preference - TextView-ImageView if (EditorProfilesActivity.getApplicationsCache() == null) EditorProfilesActivity.createApplicationsCache(); } //@Override protected void onBindView(View view) { super.onBindView(view); packageIcon = (ImageView)view.findViewById(R.id.applications_pref_icon); packageIcons = (RelativeLayout)view.findViewById(R.id.applications_pref_icons); packageIcon1 = (ImageView)view.findViewById(R.id.applications_pref_icon1); packageIcon2 = (ImageView)view.findViewById(R.id.applications_pref_icon2); packageIcon3 = (ImageView)view.findViewById(R.id.applications_pref_icon3); packageIcon4 = (ImageView)view.findViewById(R.id.applications_pref_icon4); setIcons(); } protected void showDialog(Bundle state) { MaterialDialog.Builder mBuilder = new MaterialDialog.Builder(getContext()) .title(getDialogTitle()) .icon(getDialogIcon()) //.disableDefaultFonts() .positiveText(getPositiveButtonText()) .negativeText(getNegativeButtonText()) .callback(callback) .content(getDialogMessage()); View layout = LayoutInflater.from(getContext()).inflate(R.layout.activity_applications_multiselect_pref_dialog, null); onBindDialogView(layout); linlaProgress = (LinearLayout)layout.findViewById(R.id.applications_multiselect_pref_dlg_linla_progress); linlaListView = (LinearLayout)layout.findViewById(R.id.applications_multiselect_pref_dlg_linla_listview); listView = (ListView)layout.findViewById(R.id.applications_multiselect_pref_dlg_listview); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View item, int position, long id) { Application application = (Application)listAdapter.getItem(position); application.toggleChecked(); ApplicationViewHolder viewHolder = (ApplicationViewHolder) item.getTag(); viewHolder.checkBox.setChecked(application.checked); } }); listAdapter = new ApplicationsMultiselectPreferenceAdapter(_context); mBuilder.customView(layout, false); mBuilder.showListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { ApplicationsMultiSelectDialogPreference.this.onShow(dialog); } }); MaterialDialog mDialog = mBuilder.build(); if (state != null) mDialog.onRestoreInstanceState(state); mDialog.setOnDismissListener(this); mDialog.show(); } public void onShow(DialogInterface dialog) { new AsyncTask<Void, Integer, Void>() { @Override protected void onPreExecute() { super.onPreExecute(); linlaListView.setVisibility(View.GONE); linlaProgress.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... params) { if (!EditorProfilesActivity.getApplicationsCache().isCached()) EditorProfilesActivity.getApplicationsCache().getApplicationsList(_context); getValueAMSDP(); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (!EditorProfilesActivity.getApplicationsCache().isCached()) EditorProfilesActivity.getApplicationsCache().clearCache(false); listView.setAdapter(listAdapter); linlaListView.setVisibility(View.VISIBLE); linlaProgress.setVisibility(View.GONE); } }.execute(); } private final MaterialDialog.ButtonCallback callback = new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { if (shouldPersist()) { // sem narvi stringy kontatkov oddelenych | value = ""; List<Application> applicationList = EditorProfilesActivity.getApplicationsCache().getList(); if (applicationList != null) { for (Application application : applicationList) { if (application.checked) { if (!value.isEmpty()) value = value + "|"; value = value + application.packageName; } } } persistString(value); setIcons(); setSummaryAMSDP(); } } }; public void onDismiss (DialogInterface dialog) { EditorProfilesActivity.getApplicationsCache().cancelCaching(); if (!EditorProfilesActivity.getApplicationsCache().isCached()) EditorProfilesActivity.getApplicationsCache().clearCache(false); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if (restoreValue) { // restore state getValueAMSDP(); } else { // set state // sem narvi default string kontaktov oddeleny | value = ""; persistString(""); } setSummaryAMSDP(); } private void getValueAMSDP() { // Get the persistent value value = getPersistedString(value); // change checked state by value List<Application> applicationList = EditorProfilesActivity.getApplicationsCache().getList(); if (applicationList != null) { String[] splits = value.split("\\|"); for (Application application : applicationList) { application.checked = false; for (int i = 0; i < splits.length; i++) { String packageName = splits[i]; if (packageName.equals(application.packageName)) application.checked = true; } } // move checked on top int i = 0; int ich = 0; while (i < applicationList.size()) { Application application = applicationList.get(i); if (application.checked) { applicationList.remove(i); applicationList.add(ich, application); ich++; } i++; } } } private void setSummaryAMSDP() { String prefVolumeDataSummary = _context.getString(R.string.applications_multiselect_summary_text_not_selected); if (!value.isEmpty()) { String[] splits = value.split("\\|"); if (splits.length == 1) { PackageManager packageManager = _context.getPackageManager(); ApplicationInfo app; try { app = packageManager.getApplicationInfo(splits[0], 0); if (app != null) prefVolumeDataSummary = packageManager.getApplicationLabel(app).toString(); } catch (PackageManager.NameNotFoundException e) { //e.printStackTrace(); prefVolumeDataSummary = _context.getString(R.string.applications_multiselect_summary_text_selected) + ": " + splits.length; } } else prefVolumeDataSummary = _context.getString(R.string.applications_multiselect_summary_text_selected) + ": " + splits.length; } setSummary(prefVolumeDataSummary); } private void setIcons() { PackageManager packageManager = _context.getPackageManager(); ApplicationInfo app; try { String[] splits = value.split("\\|"); if (splits.length == 1) { packageIcon.setVisibility(View.VISIBLE); packageIcons.setVisibility(View.GONE); app = packageManager.getApplicationInfo(splits[0], 0); if (app != null) { Drawable icon = packageManager.getApplicationIcon(app); //CharSequence name = packageManager.getApplicationLabel(app); packageIcon.setImageDrawable(icon); } else { packageIcon.setImageResource(R.drawable.ic_empty); } } else { packageIcon.setVisibility(View.GONE); packageIcons.setVisibility(View.VISIBLE); packageIcon.setImageResource(R.drawable.ic_empty); ImageView packIcon = packageIcon1; for (int i = 0; i < 4; i++) { if (i == 0) packIcon = packageIcon1; if (i == 1) packIcon = packageIcon2; if (i == 2) packIcon = packageIcon3; if (i == 3) packIcon = packageIcon4; if (i < splits.length) { app = packageManager.getApplicationInfo(splits[i], 0); if (app != null) { Drawable icon = packageManager.getApplicationIcon(app); //CharSequence name = packageManager.getApplicationLabel(app); packIcon.setImageDrawable(icon); } else { packIcon.setImageResource(R.drawable.ic_empty); } } else packIcon.setImageResource(R.drawable.ic_empty); } } } catch (PackageManager.NameNotFoundException e) { //e.printStackTrace(); packageIcon.setVisibility(View.VISIBLE); packageIcons.setVisibility(View.GONE); packageIcon.setImageResource(R.drawable.ic_empty); } } }
package com.redhat.ceylon.eclipse.core.typechecker; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.WeakHashMap; import org.antlr.runtime.CommonToken; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper.ModuleDependencyAnalysisError; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.context.TypecheckerUnit; import com.redhat.ceylon.compiler.typechecker.tree.Message; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.core.model.JDTModule; import com.redhat.ceylon.eclipse.core.model.ProjectSourceFile; import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile; import com.redhat.ceylon.model.loader.AbstractModelLoader; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Package; import com.redhat.ceylon.model.typechecker.util.ModuleManager; public class ProjectPhasedUnit extends IdePhasedUnit { private IFolder sourceFolderResource; private WeakHashMap<EditedPhasedUnit, String> workingCopies = new WeakHashMap<EditedPhasedUnit, String>(); public ProjectPhasedUnit(ResourceVirtualFile unitFile, ResourceVirtualFile srcDir, CompilationUnit cu, Package p, ModuleManager moduleManager, ModuleSourceMapper moduleSourceMapper, TypeChecker typeChecker, List<CommonToken> tokenStream) { super(unitFile, srcDir, cu, p, moduleManager, moduleSourceMapper, typeChecker, tokenStream); sourceFolderResource = (IFolder) srcDir.getResource(); srcDir.getResource().getProject(); } public ProjectPhasedUnit(PhasedUnit other) { super(other); } public IFile getSourceFileResource() { return (IFile) ((ResourceVirtualFile) getUnitFile()).getResource(); } public IFolder getSourceFolderResource() { return sourceFolderResource; } public IProject getProjectResource() { return sourceFolderResource.getProject(); } @Override protected TypecheckerUnit newUnit() { return new ProjectSourceFile(this); } public void addWorkingCopy(EditedPhasedUnit workingCopy) { synchronized (workingCopies) { String fullPath = workingCopy.getUnit() != null ? workingCopy.getUnit().getFullPath() : null; Iterator<String> itr = workingCopies.values().iterator(); while (itr.hasNext()) { String workingCopyPath = itr.next(); if (workingCopyPath.equals(fullPath)) { itr.remove(); } } workingCopies.put(workingCopy, fullPath); } } public Iterator<EditedPhasedUnit> getWorkingCopies() { return workingCopies.keySet().iterator(); } public void install() { TypeChecker typechecker = getTypeChecker(); if (typechecker == null) { return; } PhasedUnits phasedUnits = typechecker.getPhasedUnits(); ProjectPhasedUnit oldPhasedUnit = (ProjectPhasedUnit) phasedUnits.getPhasedUnitFromRelativePath(getPathRelativeToSrcDir()); if (oldPhasedUnit == this) { return; // Nothing to do : the PhasedUnit is already installed in the typechecker } if (oldPhasedUnit != null) { ProjectSourceFile oldSourceFile = (ProjectSourceFile) oldPhasedUnit.getUnit(); getUnit().getDependentsOf().addAll(oldSourceFile.getDependentsOf()); Iterator<EditedPhasedUnit> workingCopies = oldPhasedUnit.getWorkingCopies(); while (workingCopies.hasNext()) { addWorkingCopy(workingCopies.next()); } final Tree.CompilationUnit newCompilationUnit = getCompilationUnit(); new Visitor() { @Override public void visitAny(Node node) { super.visitAny(node); for (Message error: node.getErrors()) { if (error instanceof ModuleDependencyAnalysisError) { newCompilationUnit.addError(error); } } } }.visit(oldPhasedUnit.getCompilationUnit()); oldPhasedUnit.remove(); // pour les ICrossProjectReference, le but c'est d'enlever ce qu'il y avait (binaires ou source) } phasedUnits.addPhasedUnit(getUnitFile(), this); JDTModule module = (JDTModule) getPackage().getModule(); for (JDTModule moduleInReferencingProject : module.getModuleInReferencingProjects()) { moduleInReferencingProject.addedOriginalUnit(getPathRelativeToSrcDir()); } } public void remove() { TypeChecker typechecker = getTypeChecker(); if (typechecker == null) { return; } List<Declaration> declarationsToClean = new ArrayList<>(); for (Declaration packageDeclaration : getPackage().getMembers()) { if (packageDeclaration.isNative()) { List<Declaration> packageDeclarationOverloads = AbstractModelLoader.getOverloads(packageDeclaration); for (Declaration packageDeclarationOverload : packageDeclarationOverloads) { if (packageDeclarationOverload.getUnit() == getUnit()) { declarationsToClean.add(packageDeclarationOverload); } } } } for (Declaration declarationToClean : declarationsToClean) { List<Declaration> overloadsToClean = AbstractModelLoader.getOverloads(declarationToClean); for (Declaration overloadToClean : overloadsToClean) { if (overloadToClean == declarationToClean) { continue; } List<Declaration> overloadOverloads = AbstractModelLoader.getOverloads(overloadToClean); List<Declaration> newOverloadOverloads = new ArrayList<>(3); for (Declaration overloadOverload : overloadOverloads) { if (overloadOverload == declarationToClean) { continue; } newOverloadOverloads.add(overloadOverload); } AbstractModelLoader.setOverloads(overloadToClean, newOverloadOverloads); } } PhasedUnits phasedUnits = typechecker.getPhasedUnits(); phasedUnits.removePhasedUnitForRelativePath(getPathRelativeToSrcDir()); // remove also the ProjectSourceFile (unit) from the Package JDTModule module = (JDTModule) getPackage().getModule(); for (JDTModule moduleInReferencingProject : module.getModuleInReferencingProjects()) { moduleInReferencingProject.removedOriginalUnit(getPathRelativeToSrcDir()); } } }
package com.redhat.ceylon.eclipse.core.typechecker; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.WeakHashMap; import org.antlr.runtime.CommonToken; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.context.TypecheckerUnit; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.eclipse.core.model.JDTModule; import com.redhat.ceylon.eclipse.core.model.ProjectSourceFile; import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile; import com.redhat.ceylon.model.loader.AbstractModelLoader; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Package; import com.redhat.ceylon.model.typechecker.util.ModuleManager; public class ProjectPhasedUnit extends IdePhasedUnit { private IFolder sourceFolderResource; private WeakHashMap<EditedPhasedUnit, String> workingCopies = new WeakHashMap<EditedPhasedUnit, String>(); public ProjectPhasedUnit(ResourceVirtualFile unitFile, ResourceVirtualFile srcDir, CompilationUnit cu, Package p, ModuleManager moduleManager, ModuleSourceMapper moduleSourceMapper, TypeChecker typeChecker, List<CommonToken> tokenStream) { super(unitFile, srcDir, cu, p, moduleManager, moduleSourceMapper, typeChecker, tokenStream); sourceFolderResource = (IFolder) srcDir.getResource(); srcDir.getResource().getProject(); } public ProjectPhasedUnit(PhasedUnit other) { super(other); } public IFile getSourceFileResource() { return (IFile) ((ResourceVirtualFile) getUnitFile()).getResource(); } public IFolder getSourceFolderResource() { return sourceFolderResource; } public IProject getProjectResource() { return sourceFolderResource.getProject(); } @Override protected TypecheckerUnit newUnit() { return new ProjectSourceFile(this); } public void addWorkingCopy(EditedPhasedUnit workingCopy) { synchronized (workingCopies) { String fullPath = workingCopy.getUnit() != null ? workingCopy.getUnit().getFullPath() : null; Iterator<String> itr = workingCopies.values().iterator(); while (itr.hasNext()) { String workingCopyPath = itr.next(); if (workingCopyPath.equals(fullPath)) { itr.remove(); } } workingCopies.put(workingCopy, fullPath); } } public Iterator<EditedPhasedUnit> getWorkingCopies() { return workingCopies.keySet().iterator(); } public void install() { TypeChecker typechecker = getTypeChecker(); if (typechecker == null) { return; } PhasedUnits phasedUnits = typechecker.getPhasedUnits(); ProjectPhasedUnit oldPhasedUnit = (ProjectPhasedUnit) phasedUnits.getPhasedUnitFromRelativePath(getPathRelativeToSrcDir()); if (oldPhasedUnit == this) { return; // Nothing to do : the PhasedUnit is already installed in the typechecker } if (oldPhasedUnit != null) { ProjectSourceFile oldSourceFile = (ProjectSourceFile) oldPhasedUnit.getUnit(); getUnit().getDependentsOf().addAll(oldSourceFile.getDependentsOf()); Iterator<EditedPhasedUnit> workingCopies = oldPhasedUnit.getWorkingCopies(); while (workingCopies.hasNext()) { addWorkingCopy(workingCopies.next()); } oldPhasedUnit.remove(); // pour les ICrossProjectReference, le but c'est d'enlever ce qu'il y avait (binaires ou source) } phasedUnits.addPhasedUnit(getUnitFile(), this); JDTModule module = (JDTModule) getPackage().getModule(); for (JDTModule moduleInReferencingProject : module.getModuleInReferencingProjects()) { moduleInReferencingProject.addedOriginalUnit(getPathRelativeToSrcDir()); } } public void remove() { TypeChecker typechecker = getTypeChecker(); if (typechecker == null) { return; } List<Declaration> declarationsToClean = new ArrayList<>(); for (Declaration packageDeclaration : getPackage().getMembers()) { if (packageDeclaration.isNative()) { List<Declaration> packageDeclarationOverloads = AbstractModelLoader.getOverloads(packageDeclaration); for (Declaration packageDeclarationOverload : packageDeclarationOverloads) { if (packageDeclarationOverload.getUnit() == getUnit()) { declarationsToClean.add(packageDeclarationOverload); } } } } for (Declaration declarationToClean : declarationsToClean) { List<Declaration> overloadsToClean = AbstractModelLoader.getOverloads(declarationToClean); for (Declaration overloadToClean : overloadsToClean) { if (overloadToClean == declarationToClean) { continue; } List<Declaration> overloadOverloads = AbstractModelLoader.getOverloads(overloadToClean); List<Declaration> newOverloadOverloads = new ArrayList<>(3); for (Declaration overloadOverload : overloadOverloads) { if (overloadOverload == declarationToClean) { continue; } newOverloadOverloads.add(overloadOverload); } AbstractModelLoader.setOverloads(overloadToClean, newOverloadOverloads); } } PhasedUnits phasedUnits = typechecker.getPhasedUnits(); phasedUnits.removePhasedUnitForRelativePath(getPathRelativeToSrcDir()); // remove also the ProjectSourceFile (unit) from the Package JDTModule module = (JDTModule) getPackage().getModule(); for (JDTModule moduleInReferencingProject : module.getModuleInReferencingProjects()) { moduleInReferencingProject.removedOriginalUnit(getPathRelativeToSrcDir()); } } }
package org.eclipse.thym.core.engine.internal.cordova; import java.io.File; import java.io.FileFilter; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProduct; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.ecf.filetransfer.IncomingFileTransferException; import org.eclipse.ecf.filetransfer.identity.FileCreateException; import org.eclipse.ecf.filetransfer.identity.FileIDFactory; import org.eclipse.ecf.filetransfer.identity.IFileID; import org.eclipse.ecf.filetransfer.service.IRetrieveFileTransfer; import org.eclipse.osgi.util.NLS; import org.eclipse.thym.core.HybridCore; import org.eclipse.thym.core.engine.AbstractEngineRepoProvider; import org.eclipse.thym.core.engine.HybridMobileEngine; import org.eclipse.thym.core.engine.HybridMobileEngineLocator; import org.eclipse.thym.core.engine.HybridMobileEngineLocator.EngineSearchListener; import org.eclipse.thym.core.engine.HybridMobileLibraryResolver; import org.eclipse.thym.core.extensions.CordovaEngineRepoProvider; import org.eclipse.thym.core.extensions.PlatformSupport; public class CordovaEngineProvider implements HybridMobileEngineLocator, EngineSearchListener { /** * Engine id for the engine provided by the Apache cordova project. */ public static final String CORDOVA_ENGINE_ID = "cordova"; public static final String CUSTOM_CORDOVA_ENGINE_ID = "custom_cordova"; private volatile static ArrayList<HybridMobileEngine> engineList; /** * List of engines that are locally available. This is the list of engines that * can be used by the projects. * * @return */ public List<HybridMobileEngine> getAvailableEngines() { initEngineList(); return engineList; } private void resetEngineList(){ engineList = null; } private void initEngineList() { if(engineList != null ) return; engineList = new ArrayList<HybridMobileEngine>(); File libFolder = getLibFolder().toFile(); if( !libFolder.isDirectory()){ //engine folder does not exist return; } //search for engines on default location. searchForRuntimes(new Path(libFolder.toString()), this, new NullProgressMonitor()); //Now the custom locations String[] locs = HybridCore.getDefault().getCustomLibraryLocations(); if(locs != null ){ for (int i = 0; i < locs.length; i++) { searchForRuntimes(new Path(locs[i]), this, new NullProgressMonitor()); } } } /** * User friendly name of the engine * * @return */ public String getName(){ return "Apache Cordova"; } public HybridMobileEngine getEngine(String id, String version){ initEngineList(); for (HybridMobileEngine engine : engineList) { if(engine.getVersion().equals(version) && engine.getId().equals(id)){ return engine; } } return null; } /** * Helper method for creating engines.. Clients should not * use this method but use {@link #getAvailableEngines()} or * {@link #getEngine(String)}. This method is left public * mainly to help with testing. * * @param version * @param platforms * @param resolver * @return */ public HybridMobileEngine createEngine(String id, String version, HybridMobileLibraryResolver resolver, IPath location){ HybridMobileEngine engine = new HybridMobileEngine(); engine.setId(id); engine.setName(NLS.bind("{0}-{1}", new String[]{CORDOVA_ENGINE_ID,id})); engine.setResolver(resolver); engine.setVersion(version); engine.setLocation(location); return engine; } public static IPath getLibFolder(){ IPath path = new Path(FileUtils.getUserDirectory().toString()); path = path.append(".cordova").append("lib"); return path; } public List<DownloadableCordovaEngine> getDownloadableVersions() throws CoreException { AbstractEngineRepoProvider provider = new NpmBasedEngineRepoProvider(); IProduct product = Platform.getProduct(); if (product != null) { String productId = Platform.getProduct().getId(); List<CordovaEngineRepoProvider> providerProxies = HybridCore .getCordovaEngineRepoProviders(); for (CordovaEngineRepoProvider providerProxy : providerProxies) { if (productId.equals(providerProxy.getProductId())) { provider = providerProxy.createProvider(); } } } return provider.getEngines(); } public void downloadEngine(DownloadableCordovaEngine[] engines, IProgressMonitor monitor) { if(monitor == null ){ monitor = new NullProgressMonitor(); } IRetrieveFileTransfer transfer = HybridCore.getDefault().getFileTransferService(); IFileID remoteFileID; int platformSize = engines.length; Object lock = new Object(); int incompleteCount = platformSize; SubMonitor sm = SubMonitor.convert(monitor,platformSize ); for (int i = 0; i < platformSize; i++) { sm.setTaskName("Download Cordova Engine "+engines[i].getVersion()); try { URI uri = URI.create(engines[i].getDownloadURL()); remoteFileID = FileIDFactory.getDefault().createFileID(transfer.getRetrieveNamespace(), uri); if(sm.isCanceled()){ return; } transfer.sendRetrieveRequest(remoteFileID, new EngineDownloadReceiver(engines[i].getVersion(), engines[i].getPlatformId(), lock, sm), null); } catch (FileCreateException e) { HybridCore.log(IStatus.ERROR, "Engine download file create error", e); } catch (IncomingFileTransferException e) { HybridCore.log(IStatus.ERROR, "Engine download file transfer error", e); } } synchronized (lock) { while(incompleteCount >0){ try { lock.wait(); } catch (InterruptedException e) { HybridCore.log(IStatus.INFO, "interrupted while waiting for all engines to download", e); } incompleteCount sm.worked(1); } } resetEngineList(); } /** * Check if the platform is supported by this provider. * * @param platformId * @return */ public boolean isSupportedPlatform(String version, String platformId){ Assert.isNotNull(platformId); Assert.isNotNull( version); List<DownloadableCordovaEngine> engines = null; try { engines = getDownloadableVersions(); } catch (CoreException e) { HybridCore.log(IStatus.ERROR, "Error retrieving downloadable engines", e); } if(engines == null ){ return false; } for (DownloadableCordovaEngine downloadable : engines) { if(downloadable.getVersion().equals(version) && downloadable.getPlatformId().equals(platformId) ){ return true; } } return false; } @Override public void searchForRuntimes(IPath path, EngineSearchListener listener, IProgressMonitor monitor) { if( path == null ) return; File root = path.toFile(); if(!root.isDirectory()) return; searchDir(root, listener, monitor); } private void searchDir(File dir, EngineSearchListener listener, IProgressMonitor monitor){ if("bin".equals(dir.getName())){ File createScript = new File(dir,"create"); if(createScript.exists()){ Path libraryRoot = new Path(dir.getParent()); List<PlatformSupport> platforms = HybridCore.getPlatformSupports(); for (PlatformSupport platformSupport : platforms) { try { HybridMobileLibraryResolver resolver = platformSupport.getLibraryResolver(); resolver.init(libraryRoot); if(resolver.isLibraryConsistent().isOK()){ HybridMobileEngine engine = createEngine(platformSupport.getPlatformId(),resolver.detectVersion(), resolver,libraryRoot); listener.engineFound(engine); return; } } catch (CoreException e) { HybridCore.log(IStatus.WARNING, "Error on engine search", e); } } } } //search the sub-directories File[] dirs = dir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } }); if(dirs != null ){ for (int i = 0; i < dirs.length; i++) { if(!monitor.isCanceled()){ String name = dirs[i].getName(); if(name.equals("npm_cache") || name.equals("tmp")){ continue; } searchDir(dirs[i], listener, monitor); } } } } @Override public void engineFound(HybridMobileEngine engine) { engineList.add(engine); } public void deleteEngineLibraries(HybridMobileEngine selectedEngine) { IPath path = selectedEngine.getLocation(); FileUtils.deleteQuietly(path.toFile()); resetEngineList(); } }
package org.jkiss.dbeaver.ui.dialogs.connection; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.runtime.AbstractJob; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.registry.DataSourceDescriptor; import org.jkiss.dbeaver.registry.driver.DriverDescriptor; import org.jkiss.dbeaver.runtime.properties.PropertySourceCustom; /** * DriverPropertiesDialogPage */ public class DriverPropertiesDialogPage extends ConnectionPageAbstract { private ConnectionPageAbstract hostPage; private ConnectionPropertiesControl propsControl; private PropertySourceCustom propertySource; private DBPConnectionConfiguration prevConnectionInfo = null; public DriverPropertiesDialogPage(ConnectionPageAbstract hostPage) { this.hostPage = hostPage; setTitle("Driver properties"); setDescription("JDBC driver properties"); } @Override public boolean isComplete() { return true; } @Override public void loadSettings() { // Set props model if (propsControl != null) { final DBPDataSourceContainer activeDataSource = site.getActiveDataSource(); if (prevConnectionInfo == activeDataSource.getConnectionConfiguration()) { return; } final DBPConnectionConfiguration tmpConnectionInfo = new DBPConnectionConfiguration(); final DataSourceDescriptor tempDataSource = new DataSourceDescriptor( site.getDataSourceRegistry(), activeDataSource.getId(), (DriverDescriptor) activeDataSource.getDriver(), tmpConnectionInfo); hostPage.saveSettings(tempDataSource); tmpConnectionInfo.getProperties().putAll(activeDataSource.getConnectionConfiguration().getProperties()); // Load properties in job AbstractJob propsLoadJob = new AbstractJob("Refresh driver properties") { @Override protected IStatus run(DBRProgressMonitor monitor) { propertySource = propsControl.makeProperties( site.getRunnableContext(), site.getDriver(), tmpConnectionInfo); return Status.OK_STATUS; } }; propsLoadJob.schedule(); propsLoadJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { DBeaverUI.syncExec(new Runnable() { @Override public void run() { if (propsControl.getControl() == null || propsControl.getControl().isDisposed()) { return; } propsControl.loadProperties(propertySource); prevConnectionInfo = activeDataSource.getConnectionConfiguration(); tempDataSource.dispose(); } }); } }); } } @Override public void saveSettings(DBPDataSourceContainer dataSource) { if (propertySource != null) { dataSource.getConnectionConfiguration().getProperties().putAll(propertySource.getProperties()); } } @Override public void createControl(Composite parent) { propsControl = new ConnectionPropertiesControl(parent, SWT.NONE); setControl(propsControl.getControl()); } }
package com.opengamma.financial.convention; import java.util.ArrayList; import java.util.Collection; import org.threeten.bp.Period; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.financial.convention.businessday.BusinessDayConvention; import com.opengamma.financial.convention.businessday.BusinessDayConventions; import com.opengamma.financial.convention.daycount.DayCount; import com.opengamma.financial.convention.daycount.DayCounts; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ExternalScheme; import com.opengamma.id.UniqueId; import com.opengamma.util.ArgumentChecker; /** * An in-memory, statically initialized master for convention bundles and their meta-data. */ public class InMemoryConventionBundleMaster implements ConventionBundleMaster { /** * Scheme to use when specifying rates with simple descriptions e.g. 'LIBOR O/N', 'LIBOR 1w' etc. */ public static final ExternalScheme SIMPLE_NAME_SCHEME = ExternalScheme.of("Reference Rate Simple Name"); /** * Scheme to use when specifying rates using the OpenGamma Synthetic Ticker system */ public static final ExternalScheme OG_SYNTHETIC_TICKER = ExternalSchemes.OG_SYNTHETIC_TICKER; /** * Scheme of the unique identifiers generated by this repository. */ public static final ExternalScheme IN_MEMORY_UNIQUE_SCHEME = ExternalScheme.of("In-memory Reference Rate unique"); /** * Scheme to use when specifying exchange names with simple descriptions e.g. "CME" */ public static final ExternalScheme SIMPLE_EXCHANGE_NAME_SCHEME = ExternalScheme.of("Exchange Simple Name"); /** * Data store for the conventions. */ private final ExternalIdBundleMapper<ConventionBundle> _mapper = new ExternalIdBundleMapper<>(IN_MEMORY_UNIQUE_SCHEME.getName()); private ConventionBundleMasterUtils _utils; /** * Creates an instance. */ public InMemoryConventionBundleMaster() { init(); } protected void init() { _utils = new ConventionBundleMasterUtils(this); AUConventions.addFixedIncomeInstrumentConventions(this); BRConventions.addFixedIncomeInstrumentConventions(this); CAConventions.addFixedIncomeInstrumentConventions(this); CAConventions.addCorporateBondConvention(this); CHConventions.addFixedIncomeInstrumentConventions(this); CHConventions.addTreasuryBondConvention(this); CHConventions.addCorporateBondConvention(this); CLConventions.addFixedIncomeInstrumentConventions(this); CNConventions.addFixedIncomeInstrumentConventions(this); DKConventions.addFixedIncomeInstrumentConventions(this); EUConventions.addFixedIncomeInstrumentConventions(this); GBConventions.addFixedIncomeInstrumentConventions(this); GBConventions.addTreasuryBondConvention(this); GBConventions.addCorporateBondConvention(this); GBConventions.addBondFutureConvention(this); HKConventions.addFixedIncomeInstrumentConventions(this); HUConventions.addFixedIncomeInstrumentConventions(this); INConventions.addFixedIncomeInstrumentConventions(this); JPConventions.addFixedIncomeInstrumentConventions(this); KRConventions.addFixedIncomeInstrumentConventions(this); MXConventions.addFixedIncomeInstrumentConventions(this); NZConventions.addFixedIncomeInstrumentConventions(this); RUConventions.addFixedIncomeInstrumentConventions(this); SEConventions.addFixedIncomeInstrumentConventions(this); TWConventions.addFixedIncomeInstrumentConventions(this); USConventions.addFixedIncomeInstrumentConventions(this); USConventions.addCAPMConvention(this); USConventions.addTreasuryBondConvention(this); USConventions.addCorporateBondConvention(this); USConventions.addBondFutureConvention(this); addHUFixedIncomeInstruments(); addITFixedIncomeInstruments(); addDEFixedIncomeInstruments(); addFRFixedIncomeInstruments(); addSEFixedIncomeInstruments(); addATTreasuryBondConvention(); addBETreasuryBondConvention(); addIETreasuryBondConvention(); addLUTreasuryBondConvention(); addLUCorporateBondConvention(); addBHTreasuryBondConvention(); addBHCorporateBondConvention(); addSETreasuryBondConvention(); addSECorporateBondConvention(); addFRTreasuryBondConvention(); addFRCorporateBondConvention(); addPLTreasuryBondConvention(); addPLCorporateBondConvention(); addESTreasuryBondConvention(); addESCorporateBondConvention(); addNLTreasuryBondConvention(); addNLCorporateBondConvention(); addDETreasuryBondConvention(); addDECorporateBondConvention(); addITTreasuryBondConvention(); addITCorporateBondConvention(); addHUTreasuryBondConvention(); addHUCorporateBondConvention(); addDummyTreasuryBondConvention("MX"); addDummyTreasuryBondConvention("JE"); // Jersey!! addDummyCorporateBondConvention("DK"); addDummyCorporateBondConvention("KY"); addDummyCorporateBondConvention("AU"); addDummyCorporateBondConvention("BM"); addDummyCorporateBondConvention("NO"); addDummyCorporateBondConvention("SNAT"); addDummyCorporateBondConvention("MX"); addDummyCorporateBondConvention("IE"); addDummyCorporateBondConvention("SG"); addDummyCorporateBondConvention("BE"); addDummyCorporateBondConvention("NZ"); ExchangeConventions.addExchangeFutureOptionConventions(this); } @Override public UniqueId add(final ExternalIdBundle bundle, final ConventionBundleImpl convention) { final UniqueId uid = _mapper.add(bundle, convention); // REVIEW Andrew 2013-11-27 -- should we be setting the identifier bundle into the convention here - convention.setIdentifiers(bundle); - ? convention.setUniqueId(uid); return uid; } @Override public ConventionBundleDocument getConventionBundle(final UniqueId uniqueId) { return new ConventionBundleDocument(_mapper.get(uniqueId)); } @Override public ConventionBundleSearchResult searchConventionBundle(final ConventionBundleSearchRequest request) { final Collection<ConventionBundle> collection = _mapper.get(request.getIdentifiers()); return new ConventionBundleSearchResult(wrapReferenceRatesWithDocuments(collection)); } @Override public ConventionBundleSearchResult searchHistoricConventionBundle(final ConventionBundleSearchHistoricRequest request) { final Collection<ConventionBundle> collection = _mapper.get(request.getIdentifiers()); return new ConventionBundleSearchResult(wrapReferenceRatesWithDocuments(collection)); } /*package*/Collection<ConventionBundle> getAll() { return _mapper.getAll(); } private Collection<ConventionBundleDocument> wrapReferenceRatesWithDocuments(final Collection<ConventionBundle> referenceRates) { final Collection<ConventionBundleDocument> results = new ArrayList<>(referenceRates.size()); for (final ConventionBundle referenceRate : referenceRates) { results.add(new ConventionBundleDocument(referenceRate)); } return results; } private void addHUFixedIncomeInstruments() { final BusinessDayConvention modified = BusinessDayConventions.MODIFIED_FOLLOWING; final BusinessDayConvention following = BusinessDayConventions.FOLLOWING; final DayCount act360 = DayCounts.ACT_360; final DayCount act365 = DayCounts.ACT_365; //Identifiers for external data _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP1D")), "HUFCASHP1D", act360, following, Period.ofDays(1), 0, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP1M")), "HUFCASHP1M", act360, modified, Period.ofMonths(1), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP2M")), "HUFCASHP2M", act360, modified, Period.ofMonths(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP3M")), "HUFCASHP3M", act360, modified, Period.ofMonths(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP4M")), "HUFCASHP4M", act360, modified, Period.ofMonths(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP5M")), "HUFCASHP5M", act360, modified, Period.ofMonths(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP6M")), "HUFCASHP6M", act360, modified, Period.ofMonths(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP7M")), "HUFCASHP7M", act360, modified, Period.ofMonths(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP8M")), "HUFCASHP8M", act360, modified, Period.ofMonths(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP9M")), "HUFCASHP9M", act360, modified, Period.ofMonths(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP10M")), "HUFCASHP10M", act360, modified, Period.ofMonths(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP11M")), "HUFCASHP11M", act360, modified, Period.ofMonths(11), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFCASHP12M")), "HUFCASHP12M", act360, modified, Period.ofMonths(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP2Y")), "HUFSWAPP2Y", act365, modified, Period.ofYears(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP3Y")), "HUFSWAPP3Y", act365, modified, Period.ofYears(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP4Y")), "HUFSWAPP4Y", act365, modified, Period.ofYears(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP5Y")), "HUFSWAPP5Y", act365, modified, Period.ofYears(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP6Y")), "HUFSWAPP6Y", act365, modified, Period.ofYears(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP7Y")), "HUFSWAPP7Y", act365, modified, Period.ofYears(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP8Y")), "HUFSWAPP8Y", act365, modified, Period.ofYears(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP9Y")), "HUFSWAPP9Y", act365, modified, Period.ofYears(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HUFSWAPP10Y")), "HUFSWAPP10Y", act365, modified, Period.ofYears(10), 2, false, null); } private void addITFixedIncomeInstruments() { final BusinessDayConvention modified = BusinessDayConventions.MODIFIED_FOLLOWING; final BusinessDayConvention following = BusinessDayConventions.FOLLOWING; final DayCount act360 = DayCounts.ACT_360; final DayCount thirty360 = DayCounts.THIRTY_U_360; //Identifiers for external data _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP1D")), "ITLCASHP1D", act360, following, Period.ofDays(1), 0, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP1M")), "ITLCASHP1M", act360, modified, Period.ofMonths(1), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP2M")), "ITLCASHP2M", act360, modified, Period.ofMonths(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP3M")), "ITLCASHP3M", act360, modified, Period.ofMonths(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP4M")), "ITLCASHP4M", act360, modified, Period.ofMonths(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP5M")), "ITLCASHP5M", act360, modified, Period.ofMonths(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP6M")), "ITLCASHP6M", act360, modified, Period.ofMonths(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP7M")), "ITLCASHP7M", act360, modified, Period.ofMonths(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP8M")), "ITLCASHP8M", act360, modified, Period.ofMonths(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP9M")), "ITLCASHP9M", act360, modified, Period.ofMonths(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP10M")), "ITLCASHP10M", act360, modified, Period.ofMonths(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP11M")), "ITLCASHP11M", act360, modified, Period.ofMonths(11), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLCASHP12M")), "ITLCASHP12M", act360, modified, Period.ofMonths(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP2Y")), "ITLSWAPP2Y", thirty360, modified, Period.ofYears(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP3Y")), "ITLSWAPP3Y", thirty360, modified, Period.ofYears(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP4Y")), "ITLSWAPP4Y", thirty360, modified, Period.ofYears(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP5Y")), "ITLSWAPP5Y", thirty360, modified, Period.ofYears(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP6Y")), "ITLSWAPP6Y", thirty360, modified, Period.ofYears(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP7Y")), "ITLSWAPP7Y", thirty360, modified, Period.ofYears(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP8Y")), "ITLSWAPP8Y", thirty360, modified, Period.ofYears(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP9Y")), "ITLSWAPP9Y", thirty360, modified, Period.ofYears(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP10Y")), "ITLSWAPP10Y", thirty360, modified, Period.ofYears(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP12Y")), "ITLSWAPP12Y", thirty360, modified, Period.ofYears(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP15Y")), "ITLSWAPP15Y", thirty360, modified, Period.ofYears(15), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP20Y")), "ITLSWAPP20Y", thirty360, modified, Period.ofYears(20), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP25Y")), "ITLSWAPP25Y", thirty360, modified, Period.ofYears(25), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP30Y")), "ITLSWAPP30Y", thirty360, modified, Period.ofYears(30), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP40Y")), "ITLSWAPP40Y", thirty360, modified, Period.ofYears(40), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP50Y")), "ITLSWAPP50Y", thirty360, modified, Period.ofYears(50), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ITLSWAPP60Y")), "ITLSWAPP80Y", thirty360, modified, Period.ofYears(80), 2, false, null); } private void addDEFixedIncomeInstruments() { final BusinessDayConvention modified = BusinessDayConventions.MODIFIED_FOLLOWING; final BusinessDayConvention following = BusinessDayConventions.FOLLOWING; final DayCount act360 = DayCounts.ACT_360; final DayCount thirty360 = DayCounts.THIRTY_U_360; //Identifiers for external data _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP1D")), "DEMCASHP1D", act360, following, Period.ofDays(1), 0, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP1M")), "DEMCASHP1M", act360, modified, Period.ofMonths(1), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP2M")), "DEMCASHP2M", act360, modified, Period.ofMonths(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP3M")), "DEMCASHP3M", act360, modified, Period.ofMonths(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP4M")), "DEMCASHP4M", act360, modified, Period.ofMonths(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP5M")), "DEMCASHP5M", act360, modified, Period.ofMonths(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP6M")), "DEMCASHP6M", act360, modified, Period.ofMonths(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP7M")), "DEMCASHP7M", act360, modified, Period.ofMonths(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP8M")), "DEMCASHP8M", act360, modified, Period.ofMonths(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP9M")), "DEMCASHP9M", act360, modified, Period.ofMonths(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP10M")), "DEMCASHP10M", act360, modified, Period.ofMonths(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP11M")), "DEMCASHP11M", act360, modified, Period.ofMonths(11), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMCASHP12M")), "DEMCASHP12M", act360, modified, Period.ofMonths(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP2Y")), "DEMSWAPP2Y", thirty360, modified, Period.ofYears(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP3Y")), "DEMSWAPP3Y", thirty360, modified, Period.ofYears(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP4Y")), "DEMSWAPP4Y", thirty360, modified, Period.ofYears(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP5Y")), "DEMSWAPP5Y", thirty360, modified, Period.ofYears(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP6Y")), "DEMSWAPP6Y", thirty360, modified, Period.ofYears(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP7Y")), "DEMSWAPP7Y", thirty360, modified, Period.ofYears(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP8Y")), "DEMSWAPP8Y", thirty360, modified, Period.ofYears(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP9Y")), "DEMSWAPP9Y", thirty360, modified, Period.ofYears(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP10Y")), "DEMSWAPP10Y", thirty360, modified, Period.ofYears(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP12Y")), "DEMSWAPP12Y", thirty360, modified, Period.ofYears(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP15Y")), "DEMSWAPP15Y", thirty360, modified, Period.ofYears(15), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP20Y")), "DEMSWAPP20Y", thirty360, modified, Period.ofYears(20), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP25Y")), "DEMSWAPP25Y", thirty360, modified, Period.ofYears(25), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP30Y")), "DEMSWAPP30Y", thirty360, modified, Period.ofYears(30), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP40Y")), "DEMSWAPP40Y", thirty360, modified, Period.ofYears(40), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP50Y")), "DEMSWAPP50Y", thirty360, modified, Period.ofYears(50), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DEMSWAPP60Y")), "DEMSWAPP80Y", thirty360, modified, Period.ofYears(80), 2, false, null); } private void addFRFixedIncomeInstruments() { final BusinessDayConvention modified = BusinessDayConventions.MODIFIED_FOLLOWING; final BusinessDayConvention following = BusinessDayConventions.FOLLOWING; final DayCount act360 = DayCounts.ACT_360; final DayCount thirty360 = DayCounts.THIRTY_U_360; //Identifiers for external data _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP1D")), "FRFCASHP1D", act360, following, Period.ofDays(1), 0, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP1M")), "FRFCASHP1M", act360, modified, Period.ofMonths(1), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP2M")), "FRFCASHP2M", act360, modified, Period.ofMonths(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP3M")), "FRFCASHP3M", act360, modified, Period.ofMonths(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP4M")), "FRFCASHP4M", act360, modified, Period.ofMonths(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP5M")), "FRFCASHP5M", act360, modified, Period.ofMonths(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP6M")), "FRFCASHP6M", act360, modified, Period.ofMonths(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP7M")), "FRFCASHP7M", act360, modified, Period.ofMonths(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP8M")), "FRFCASHP8M", act360, modified, Period.ofMonths(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP9M")), "FRFCASHP9M", act360, modified, Period.ofMonths(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP10M")), "FRFCASHP10M", act360, modified, Period.ofMonths(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP11M")), "FRFCASHP11M", act360, modified, Period.ofMonths(11), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFCASHP12M")), "FRFCASHP12M", act360, modified, Period.ofMonths(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP2Y")), "FRFSWAPP2Y", thirty360, modified, Period.ofYears(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP3Y")), "FRFSWAPP3Y", thirty360, modified, Period.ofYears(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP4Y")), "FRFSWAPP4Y", thirty360, modified, Period.ofYears(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP5Y")), "FRFSWAPP5Y", thirty360, modified, Period.ofYears(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP6Y")), "FRFSWAPP6Y", thirty360, modified, Period.ofYears(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP7Y")), "FRFSWAPP7Y", thirty360, modified, Period.ofYears(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP8Y")), "FRFSWAPP8Y", thirty360, modified, Period.ofYears(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP9Y")), "FRFSWAPP9Y", thirty360, modified, Period.ofYears(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP10Y")), "FRFSWAPP10Y", thirty360, modified, Period.ofYears(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP12Y")), "FRFSWAPP12Y", thirty360, modified, Period.ofYears(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP15Y")), "FRFSWAPP15Y", thirty360, modified, Period.ofYears(15), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP20Y")), "FRFSWAPP20Y", thirty360, modified, Period.ofYears(20), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP25Y")), "FRFSWAPP25Y", thirty360, modified, Period.ofYears(25), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP30Y")), "FRFSWAPP30Y", thirty360, modified, Period.ofYears(30), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP40Y")), "FRFSWAPP40Y", thirty360, modified, Period.ofYears(40), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP50Y")), "FRFSWAPP50Y", thirty360, modified, Period.ofYears(50), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FRFSWAPP60Y")), "FRFSWAPP80Y", thirty360, modified, Period.ofYears(80), 2, false, null); } private void addSEFixedIncomeInstruments() { final BusinessDayConvention modified = BusinessDayConventions.MODIFIED_FOLLOWING; final BusinessDayConvention following = BusinessDayConventions.FOLLOWING; final DayCount act360 = DayCounts.ACT_360; final DayCount act365 = DayCounts.ACT_365; //Identifiers for external data _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP1D")), "SEKCASHP1D", act360, following, Period.ofDays(1), 0, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP1M")), "SEKCASHP1M", act360, modified, Period.ofMonths(1), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP2M")), "SEKCASHP2M", act360, modified, Period.ofMonths(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP3M")), "SEKCASHP3M", act360, modified, Period.ofMonths(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP4M")), "SEKCASHP4M", act360, modified, Period.ofMonths(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP5M")), "SEKCASHP5M", act360, modified, Period.ofMonths(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP6M")), "SEKCASHP6M", act360, modified, Period.ofMonths(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP7M")), "SEKCASHP7M", act360, modified, Period.ofMonths(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP8M")), "SEKCASHP8M", act360, modified, Period.ofMonths(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP9M")), "SEKCASHP9M", act360, modified, Period.ofMonths(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP10M")), "SEKCASHP10M", act365, modified, Period.ofMonths(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP11M")), "SEKCASHP11M", act365, modified, Period.ofMonths(11), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKCASHP12M")), "SEKCASHP12M", act360, modified, Period.ofMonths(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP2Y")), "SEKSWAPP2Y", act360, modified, Period.ofYears(2), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP3Y")), "SEKSWAPP3Y", act360, modified, Period.ofYears(3), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP4Y")), "SEKSWAPP4Y", act360, modified, Period.ofYears(4), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP5Y")), "SEKSWAPP5Y", act360, modified, Period.ofYears(5), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP6Y")), "SEKSWAPP6Y", act360, modified, Period.ofYears(6), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP7Y")), "SEKSWAPP7Y", act360, modified, Period.ofYears(7), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP8Y")), "SEKSWAPP8Y", act360, modified, Period.ofYears(8), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP9Y")), "SEKSWAPP9Y", act360, modified, Period.ofYears(9), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP10Y")), "SEKSWAPP10Y", act360, modified, Period.ofYears(10), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP12Y")), "SEKSWAPP12Y", act360, modified, Period.ofYears(12), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP15Y")), "SEKSWAPP15Y", act360, modified, Period.ofYears(15), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP20Y")), "SEKSWAPP20Y", act360, modified, Period.ofYears(20), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP25Y")), "SEKSWAPP25Y", act360, modified, Period.ofYears(25), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP30Y")), "SEKSWAPP30Y", act360, modified, Period.ofYears(30), 2, false, null); _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SEKSWAPP40Y")), "SEKSWAPP40Y", act360, modified, Period.ofYears(40), 2, false, null); } //TODO all of the conventions named treasury need to be changed - after we can differentiate T-bills, Treasuries, etc private void addATTreasuryBondConvention() { // Government Austria _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "AT_TREASURY_BOND_CONVENTION")), "AT_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed - after we can differentiate T-bills, Treasuries, etc private void addBETreasuryBondConvention() { // Government Belgium _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "BE_TREASURY_BOND_CONVENTION")), "BE_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed - after we can differentiate T-bills, Treasuries, etc private void addIETreasuryBondConvention() { // Government Ireland _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "IE_TREASURY_BOND_CONVENTION")), "IE_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed - after we can differentiate T-bills, Treasuries, etc private void addLUTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "LU_TREASURY_BOND_CONVENTION")), "LU_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addLUCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "LU_CORPORATE_BOND_CONVENTION")), "LU_CORPORATE_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addHUTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HU_TREASURY_BOND_CONVENTION")), "HU_TREASURY_BOND_CONVENTION", true, true, 0, 2, true); } //TODO all of the conventions named treasury need to be changed private void addHUCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "HU_CORPORATE_BOND_CONVENTION")), "HU_CORPORATE_BOND_CONVENTION", true, true, 0, 2, true); } //TODO all of the conventions named treasury need to be changed private void addITTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "IT_TREASURY_BOND_CONVENTION")), "IT_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addITCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "IT_CORPORATE_BOND_CONVENTION")), "IT_CORPORATE_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addDETreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DE_TREASURY_BOND_CONVENTION")), "DE_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addDECorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "DE_CORPORATE_BOND_CONVENTION")), "DE_CORPORATE_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addESTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ES_TREASURY_BOND_CONVENTION")), "ES_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addESCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "ES_CORPORATE_BOND_CONVENTION")), "ES_CORPORATE_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addNLTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "NL_TREASURY_BOND_CONVENTION")), "NL_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addNLCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "NL_CORPORATE_BOND_CONVENTION")), "NL_CORPORATE_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addPLTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "PL_TREASURY_BOND_CONVENTION")), "PL_TREASURY_BOND_CONVENTION", true, true, 10, 2, true); } //TODO all of the conventions named treasury need to be changed private void addPLCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "PL_CORPORATE_BOND_CONVENTION")), "PL_CORPORATE_BOND_CONVENTION", true, true, 10, 2, true); } //TODO all of the conventions named treasury need to be changed private void addFRTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FR_TREASURY_BOND_CONVENTION")), "FR_TREASURY_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addFRCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "FR_CORPORATE_BOND_CONVENTION")), "FR_CORPORATE_BOND_CONVENTION", true, true, 0, 3, true); } //TODO all of the conventions named treasury need to be changed private void addBHTreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "BH_TREASURY_BOND_CONVENTION")), "BH_TREASURY_BOND_CONVENTION", true, true, 0, 1, true); } //TODO all of the conventions named treasury need to be changed private void addBHCorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "BH_CORPORATE_BOND_CONVENTION")), "BH_CORPORATE_BOND_CONVENTION", true, true, 0, 1, true); } //TODO all of the conventions named treasury need to be changed private void addSETreasuryBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SE_TREASURY_BOND_CONVENTION")), "SE_TREASURY_BOND_CONVENTION", true, true, 4, 3, true); } //TODO all of the conventions named treasury need to be changed private void addSECorporateBondConvention() { _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, "SE_CORPORATE_BOND_CONVENTION")), "SE_CORPORATE_BOND_CONVENTION", true, true, 4, 3, true); } private void addDummyTreasuryBondConvention(final String domicile) { final String name = domicile + "_TREASURY_BOND_CONVENTION"; _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, name)), name, true, true, 0, 3, true); } private void addDummyCorporateBondConvention(final String domicile) { final String name = domicile + "_CORPORATE_BOND_CONVENTION"; _utils.addConventionBundle(ExternalIdBundle.of(ExternalId.of(SIMPLE_NAME_SCHEME, name)), name, true, true, 0, 3, true); } /** * Creates a simple name security Id. * <p> * * @param securityId the simple name security id, not null * @return the security identifier, not null */ public static ExternalId simpleNameSecurityId(final String securityId) { ArgumentChecker.notNull(securityId, "code"); if (securityId.length() == 0) { throw new IllegalArgumentException("SecurityId is invalid: " + securityId); } return ExternalId.of(SIMPLE_NAME_SCHEME, securityId); } /** * Creates a simple exchange name id. * <p> * * @param exchangeName the simple exchange name, not null * @return the exchange identifier, not null */ public static ExternalId simpleExchangeNameSecurityId(final String exchangeName) { ArgumentChecker.notNull(exchangeName, "exchange name"); if (exchangeName.length() == 0) { throw new IllegalArgumentException("Exchange name is invalid: " + exchangeName); } return ExternalId.of(SIMPLE_EXCHANGE_NAME_SCHEME, exchangeName); } }
package com.neverwinterdp.scribengin.storage.s3; import java.io.IOException; import java.util.UUID; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.amazonaws.services.s3.model.ObjectMetadata; public class S3ObjectWriterExperimentTest { static public String BUCKET_NAME = "s3-client-integration-test-" + UUID.randomUUID(); static S3Client s3Client ; @BeforeClass static public void beforeClass() { s3Client = new S3Client() ; s3Client.createBucket(BUCKET_NAME); } @AfterClass static public void afterClass() { s3Client.deleteBucket(BUCKET_NAME, true); s3Client.onDestroy(); } @Test public void testS3ObjectWriter() throws Exception, IOException, InterruptedException { String KEY = "test-s3-object-writer" ; S3ObjectWriter writer = new S3ObjectWriter(s3Client, BUCKET_NAME, KEY, new ObjectMetadata()); int totalBytes = 0 ; for(int i = 0; i < 100000; i++) { byte[] data = new byte[512] ; writer.write(data); totalBytes += data.length; if((i + 1) % 1000 == 0) { System.out.println("write " + i + ", bytes " + totalBytes); } } writer.waitAndClose(5000); } }
package org.sagebionetworks.file.services; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.sagebionetworks.StackConfigurationSingleton; import org.sagebionetworks.aws.SynapseS3Client; import org.sagebionetworks.repo.manager.AuthenticationManager; import org.sagebionetworks.repo.manager.file.FileHandleManager; import org.sagebionetworks.repo.manager.file.LocalFileUploadRequest; import org.sagebionetworks.repo.model.ACCESS_TYPE; import org.sagebionetworks.repo.model.AccessControlList; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Folder; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.ResourceAccess; import org.sagebionetworks.repo.model.auth.AccessToken; import org.sagebionetworks.repo.model.auth.JSONWebTokenHelper; import org.sagebionetworks.repo.model.auth.LoginResponse; import org.sagebionetworks.repo.model.auth.NewIntegrationTestUser; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.project.ExternalS3StorageLocationSetting; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.S3StorageLocationSetting; import org.sagebionetworks.repo.model.project.UploadDestinationListSetting; import org.sagebionetworks.repo.model.util.ModelConstants; import org.sagebionetworks.repo.web.service.AdministrationService; import org.sagebionetworks.repo.web.service.CertifiedUserService; import org.sagebionetworks.repo.web.service.EntityService; import org.sagebionetworks.repo.web.service.ProjectSettingsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.util.StringInputStream; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.io.Files; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "classpath:test-context.xml" }) public class FileUploadServiceImplAutowireTest { @Autowired private AdministrationService adminService; // Bypass Auth Service to sign terms of use. @Autowired private AuthenticationManager authManager; @Autowired private CertifiedUserService certifiedUserService; @Autowired private EntityService entityService; @Autowired private FileUploadService fileUploadService; // Used only to test multipart upload. @Autowired private FileHandleManager fileHandleManager; @Autowired private ProjectSettingsService projectSettingsService; @Autowired private SynapseS3Client s3Client; private List<Entity> entitiesToDelete; private List<S3FileHandle> fileHandlesToDelete; private List<File> filesToDelete; private String projectId; private Long userId; private String username; private Long user2Id; @BeforeEach public void beforeEach() throws Exception { // Set up lists of entities to delete. entitiesToDelete = new ArrayList<>(); fileHandlesToDelete = new ArrayList<>(); filesToDelete = new ArrayList<>(); // Set up test user. Long adminUserId = AuthorizationConstants.BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId(); NewIntegrationTestUser user = new NewIntegrationTestUser(); username = UUID.randomUUID().toString(); user.setEmail(username + "@test.com"); user.setUsername(username); user.setTou(true); LoginResponse loginResponse = adminService.createOrGetTestUser(adminUserId, user); String subject = JSONWebTokenHelper.getSubjectFromJWTAccessToken(loginResponse.getAccessToken()); userId = Long.valueOf(subject); certifiedUserService.setUserCertificationStatus(adminUserId, userId, true); NewIntegrationTestUser user2 = new NewIntegrationTestUser(); String user2name = UUID.randomUUID().toString(); user2.setEmail(user2name + "@test.com"); user2.setUsername(user2name); user2.setTou(true); LoginResponse loginResponse2 = adminService.createOrGetTestUser(adminUserId, user2); String subject2 = JSONWebTokenHelper.getSubjectFromJWTAccessToken(loginResponse2.getAccessToken()); user2Id = Long.valueOf(subject2); certifiedUserService.setUserCertificationStatus(adminUserId, user2Id, true); // Set up test project. Project project = new Project(); String projectName = "project" + new Random().nextInt(); project.setName(projectName); project = entityService.createEntity(userId, project, null); entitiesToDelete.add(project); projectId = project.getId(); // Give ACL to user2. ResourceAccess userAccess = new ResourceAccess(); userAccess.setPrincipalId(userId); userAccess.setAccessType(ModelConstants.ENTITY_ADMIN_ACCESS_PERMISSIONS); ResourceAccess user2Access = new ResourceAccess(); user2Access.setPrincipalId(user2Id); user2Access.setAccessType(EnumSet.of(ACCESS_TYPE.CREATE, ACCESS_TYPE.READ, ACCESS_TYPE.UPDATE, ACCESS_TYPE.CHANGE_PERMISSIONS)); AccessControlList acl = entityService.getEntityACL(projectId, userId); acl.setResourceAccess(ImmutableSet.of(userAccess, user2Access)); entityService.updateEntityACL(userId, acl); } @AfterEach public void afterEach() { // Delete entities. for (Entity entity : Lists.reverse(entitiesToDelete)) { entityService.deleteEntity(userId, entity.getId()); } // Delete file handles. for (S3FileHandle fileHandle : fileHandlesToDelete) { fileUploadService.deleteFileHandle(fileHandle.getId(), userId); } // Delete local files. for (File file : filesToDelete) { file.delete(); } } @Test public void uploadWithSts() throws Exception { // Set up bucket and owner.txt. String externalS3Bucket = StackConfigurationSingleton.singleton().getExternalS3TestBucketName(); String externalS3StorageBaseKey = "test-base-" + UUID.randomUUID(); s3Client.createBucket(externalS3Bucket); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(username.length()); s3Client.putObject(externalS3Bucket, externalS3StorageBaseKey + "/owner.txt", new StringInputStream(username), metadata); // Create Synapse Storage and External S3 Storage w/ STS. S3StorageLocationSetting synapseStorageLocationSetting = new S3StorageLocationSetting(); synapseStorageLocationSetting.setStsEnabled(true); synapseStorageLocationSetting = (S3StorageLocationSetting) projectSettingsService .createStorageLocationSetting(userId, synapseStorageLocationSetting); long synapseStorageLocationId = synapseStorageLocationSetting.getStorageLocationId(); String synapseStorageBaseKey = synapseStorageLocationSetting.getBaseKey(); assertNotNull(synapseStorageBaseKey); assertNotEquals(externalS3StorageBaseKey, synapseStorageBaseKey); ExternalS3StorageLocationSetting externalS3StorageLocationSetting = new ExternalS3StorageLocationSetting(); externalS3StorageLocationSetting.setBucket(externalS3Bucket); externalS3StorageLocationSetting.setBaseKey(externalS3StorageBaseKey); externalS3StorageLocationSetting.setStsEnabled(true); externalS3StorageLocationSetting = (ExternalS3StorageLocationSetting) projectSettingsService .createStorageLocationSetting(userId, externalS3StorageLocationSetting); long externalS3StorageLocationId = externalS3StorageLocationSetting.getStorageLocationId(); assertNotEquals(synapseStorageLocationId, externalS3StorageLocationId); assertEquals(externalS3StorageBaseKey, externalS3StorageLocationSetting.getBaseKey()); // Upload to Synapse Storage. File synapseFile = File.createTempFile("uploadWithSts-Synapse", ".txt"); filesToDelete.add(synapseFile); Files.asCharSink(synapseFile, StandardCharsets.UTF_8).write( "Test file in Synapse storage location with STS"); LocalFileUploadRequest synapseUploadRequest = new LocalFileUploadRequest().withContentType("text/plain") .withFileToUpload(synapseFile).withStorageLocationId(synapseStorageLocationId) .withUserId(userId.toString()); S3FileHandle synapseFileHandle = fileHandleManager.uploadLocalFile(synapseUploadRequest); assertNotNull(synapseFileHandle); assertEquals(synapseStorageLocationId, synapseFileHandle.getStorageLocationId()); fileHandlesToDelete.add(synapseFileHandle); assertNotNull(synapseFileHandle.getBucketName()); assertTrue(synapseFileHandle.getKey().startsWith(synapseStorageBaseKey)); // Verify file exists in S3. assertTrue(s3Client.doesObjectExist(synapseFileHandle.getBucketName(), synapseFileHandle.getKey())); // Upload to External S3 Storage. File externalS3File = File.createTempFile("uploadWithSts-ExternalS3", ".txt"); filesToDelete.add(externalS3File); Files.asCharSink(externalS3File, StandardCharsets.UTF_8).write( "Test file in external S3 storage location with STS"); LocalFileUploadRequest externalS3UploadRequest = new LocalFileUploadRequest().withContentType("text/plain") .withFileToUpload(externalS3File).withStorageLocationId(externalS3StorageLocationId) .withUserId(userId.toString()); S3FileHandle externalS3FileHandle = fileHandleManager.uploadLocalFile(externalS3UploadRequest); assertNotNull(externalS3FileHandle); assertEquals(externalS3StorageLocationId, externalS3FileHandle.getStorageLocationId()); fileHandlesToDelete.add(externalS3FileHandle); assertEquals(externalS3Bucket, externalS3FileHandle.getBucketName()); assertTrue(externalS3FileHandle.getKey().startsWith(externalS3StorageBaseKey)); // Verify file exists in S3. assertTrue(s3Client.doesObjectExist(externalS3FileHandle.getBucketName(), externalS3FileHandle.getKey())); // Attempt to create a new file handle that points at the same file. Even though there's a copy API that does // exactly this, we're specifically testing the more general createExternalS3FileHandle() API.) S3FileHandle externalS3FileHandleCopy = (S3FileHandle) fileUploadService.getFileHandle( externalS3FileHandle.getId(), userId); externalS3FileHandleCopy = fileUploadService.createExternalS3FileHandle(userId, externalS3FileHandleCopy); assertNotNull(externalS3FileHandleCopy); fileHandlesToDelete.add(externalS3FileHandleCopy); assertNotEquals(externalS3FileHandle.getId(), externalS3FileHandleCopy.getId()); assertEquals(externalS3Bucket, externalS3FileHandleCopy.getBucketName()); assertEquals(externalS3FileHandle.getKey(), externalS3FileHandleCopy.getKey()); // Create folders for the project. Folder synapseFolder = new Folder(); synapseFolder.setParentId(projectId); synapseFolder = entityService.createEntity(userId, synapseFolder, null); entitiesToDelete.add(synapseFolder); Folder externalS3Folder = new Folder(); externalS3Folder.setParentId(projectId); externalS3Folder = entityService.createEntity(userId, externalS3Folder, null); entitiesToDelete.add(externalS3Folder); // Add storage locations to the folders. UploadDestinationListSetting synapseProjectSetting = new UploadDestinationListSetting(); synapseProjectSetting.setProjectId(synapseFolder.getId()); synapseProjectSetting.setSettingsType(ProjectSettingsType.upload); synapseProjectSetting.setLocations(ImmutableList.of(synapseStorageLocationId)); projectSettingsService.createProjectSetting(userId, synapseProjectSetting); UploadDestinationListSetting externalS3ProjectSetting = new UploadDestinationListSetting(); externalS3ProjectSetting.setProjectId(externalS3Folder.getId()); externalS3ProjectSetting.setSettingsType(ProjectSettingsType.upload); externalS3ProjectSetting.setLocations(ImmutableList.of(externalS3StorageLocationId)); projectSettingsService.createProjectSetting(userId, externalS3ProjectSetting); // Before we can create file entities, we must agree to terms of use. authManager.setTermsOfUseAcceptance(userId, true); // Create file entities for each file handle. FileEntity synapseFileEntity = new FileEntity(); synapseFileEntity.setDataFileHandleId(synapseFileHandle.getId()); synapseFileEntity.setParentId(synapseFolder.getId()); synapseFileEntity = entityService.createEntity(userId, synapseFileEntity, null); entitiesToDelete.add(synapseFileEntity); FileEntity externalS3FileEntity = new FileEntity(); externalS3FileEntity.setDataFileHandleId(externalS3FileHandle.getId()); externalS3FileEntity.setParentId(externalS3Folder.getId()); externalS3FileEntity = entityService.createEntity(userId, externalS3FileEntity, null); entitiesToDelete.add(externalS3FileEntity); // Create a file handle and file entity in the default storage location (such as project root). File nonStsFile = File.createTempFile("nonStsFile", ".txt"); filesToDelete.add(nonStsFile); Files.asCharSink(nonStsFile, StandardCharsets.UTF_8).write("Test file in without STS"); LocalFileUploadRequest nonStsUploadRequest = new LocalFileUploadRequest().withContentType("text/plain") .withFileToUpload(nonStsFile).withStorageLocationId(null).withUserId(userId.toString()); S3FileHandle nonStsFileHandle = fileHandleManager.uploadLocalFile(nonStsUploadRequest); fileHandlesToDelete.add(nonStsFileHandle); FileEntity nonStsFileEntity = new FileEntity(); nonStsFileEntity.setDataFileHandleId(nonStsFileHandle.getId()); nonStsFileEntity.setParentId(projectId); nonStsFileEntity = entityService.createEntity(userId, nonStsFileEntity, null); entitiesToDelete.add(nonStsFileEntity); } // PLFM-6097 @Test public void fileHandleNonOwnerCanMoveFileEntity() throws Exception { // Create folders for the project. Folder folderA = new Folder(); folderA.setParentId(projectId); folderA = entityService.createEntity(userId, folderA, null); entitiesToDelete.add(folderA); Folder folderB = new Folder(); folderB.setParentId(projectId); folderB = entityService.createEntity(userId, folderB, null); entitiesToDelete.add(folderB); // Create a file handle. File file = File.createTempFile("plfm-6097-test-file", ".txt"); filesToDelete.add(file); Files.asCharSink(file, StandardCharsets.UTF_8).write("Test file for PLFM-6097"); LocalFileUploadRequest fileUploadRequest = new LocalFileUploadRequest().withContentType("text/plain") .withFileToUpload(file).withUserId(userId.toString()); S3FileHandle fileHandle = fileHandleManager.uploadLocalFile(fileUploadRequest); fileHandlesToDelete.add(fileHandle); // Before we can create file entities, we must agree to terms of use. authManager.setTermsOfUseAcceptance(userId, true); // Make a FileEntity out of that FileHandle in Folder A. FileEntity fileEntity = new FileEntity(); fileEntity.setDataFileHandleId(fileHandle.getId()); fileEntity.setParentId(folderA.getId()); fileEntity = entityService.createEntity(userId, fileEntity, null); entitiesToDelete.add(fileEntity); // User2 can move the FileEntity to Folder B. fileEntity.setParentId(folderB.getId()); entityService.updateEntity(user2Id, fileEntity, false, null); } }
// copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // persons to whom the Software is furnished to do so, subject to the // notice shall be included in all copies or substantial portions of the // Software. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.assetpack.ui; import static java.util.stream.Collectors.joining; import java.util.LinkedHashSet; import org.eclipse.core.resources.IProject; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import phasereditor.animation.ui.AnimationTreeCanvasItemRenderer; import phasereditor.animation.ui.AnimationsAssetTreeCanvasItemRenderer; import phasereditor.assetpack.core.AnimationsAssetModel; import phasereditor.assetpack.core.AssetPackModel; import phasereditor.assetpack.core.AtlasAssetModel; import phasereditor.assetpack.core.AudioAssetModel; import phasereditor.assetpack.core.AudioSpriteAssetModel; import phasereditor.assetpack.core.BitmapFontAssetModel; import phasereditor.assetpack.core.IAssetFrameModel; import phasereditor.assetpack.core.IAssetKey; import phasereditor.assetpack.core.ImageAssetModel; import phasereditor.assetpack.core.MultiAtlasAssetModel; import phasereditor.assetpack.core.SpritesheetAssetModel; import phasereditor.assetpack.core.animations.AnimationFrameModel; import phasereditor.assetpack.core.animations.AnimationModel; import phasereditor.assetpack.core.animations.AnimationsModel; import phasereditor.ui.ImageProxy; import phasereditor.ui.ImageProxyTreeCanvasItemRenderer; import phasereditor.ui.TreeCanvas; import phasereditor.ui.TreeCanvas.TreeCanvasItem; import phasereditor.ui.TreeCanvasViewer; /** * @author arian * */ public class AssetsTreeCanvasViewer extends TreeCanvasViewer { public AssetsTreeCanvasViewer(TreeCanvas tree, ITreeContentProvider contentProvider, LabelProvider labelProvider) { super(tree, contentProvider, labelProvider); AssetPackUI.installAssetTooltips(tree, tree.getUtils()); } public AssetsTreeCanvasViewer(TreeCanvas tree) { this(tree, null, null); } @Override protected void setItemIconProperties(TreeCanvasItem item) { var elem = item.getData(); LinkedHashSet<String> keywords = new LinkedHashSet<>(); addKeywords(elem, keywords); item.setKeywords(keywords.isEmpty() ? null : keywords.stream().collect(joining(","))); var imageRenderer = createImageRenderer(item, elem); if (imageRenderer == null) { super.setItemIconProperties(item); } else { item.setRenderer(imageRenderer); } if (elem instanceof AnimationsAssetModel) { item.setRenderer(new AnimationsAssetTreeCanvasItemRenderer(item)); } else if (elem instanceof AnimationModel) { item.setRenderer(new AnimationTreeCanvasItemRenderer(item)); } else if (elem instanceof AudioSpriteAssetModel) { item.setRenderer(new AudioSpriteAssetTreeCanvasItemRenderer(item)); } else if (elem instanceof AudioSpriteAssetModel.AssetAudioSprite) { item.setRenderer(new AudioSpriteAssetElementTreeCanvasRenderer(item)); } else if (elem instanceof AudioAssetModel) { item.setRenderer(new AudioAssetTreeCanvasItemRenderer(item)); } else if (elem instanceof BitmapFontAssetModel) { item.setRenderer(new BitmapFontTreeCanvasRenderer(item)); } else if (elem instanceof MultiAtlasAssetModel) { item.setRenderer(new MultiAtlasAssetTreeCanvasItemRenderer(item)); } } public static ImageProxyTreeCanvasItemRenderer createImageRenderer(TreeCanvasItem item, Object element) { ImageProxy proxy = getAssetKeyImageProxy(element); if (proxy == null) { return null; } return new ImageProxyTreeCanvasItemRenderer(item, proxy); } public static ImageProxy getAssetKeyImageProxy(Object element) { ImageProxy proxy = null; if (element instanceof IAssetFrameModel) { var asset = (IAssetFrameModel) element; proxy = AssetPackUI.getImageProxy(asset); } else if (element instanceof ImageAssetModel) { var asset = (ImageAssetModel) element; proxy = AssetPackUI.getImageProxy(asset.getFrame()); } else if (element instanceof AtlasAssetModel) { var asset = (AtlasAssetModel) element; proxy = ImageProxy.get(asset.getTextureFile(), null); } else if (element instanceof SpritesheetAssetModel) { var asset = (SpritesheetAssetModel) element; var file = asset.getUrlFile(); proxy = ImageProxy.get(file, null); } else if (element instanceof AnimationFrameModel) { AnimationFrameModel animFrame = (AnimationFrameModel) element; var assetFrame = animFrame.getAssetFrame(); proxy = AssetPackUI.getImageProxy(assetFrame); } if (proxy == null) { return null; } return proxy; } @SuppressWarnings("static-method") private void addKeywords(Object elem, LinkedHashSet<String> keywords) { if (elem instanceof IAssetKey) { var asset = ((IAssetKey) elem).getAsset(); if (asset instanceof ImageAssetModel) { keywords.add("image"); keywords.add("texture"); } if (asset instanceof SpritesheetAssetModel) { keywords.add("texture"); keywords.add("spritesheet"); } if (asset instanceof AtlasAssetModel || asset instanceof MultiAtlasAssetModel) { keywords.add("texture"); keywords.add("atlas"); } if (elem instanceof IAssetFrameModel) { keywords.add("texture"); keywords.add("frame"); } if (elem instanceof BitmapFontAssetModel) { keywords.add("font"); keywords.add("bitmap"); keywords.add("text"); } } if (elem instanceof AnimationsModel || elem instanceof AnimationModel) { keywords.add("animation"); } if (elem instanceof AssetPackModel) { keywords.add("pack"); } if (elem instanceof IProject) { keywords.add("project"); } } }
package org.rstudio.studio.client.workbench.views.source.editors.text; import org.rstudio.core.client.DebouncedCommand; import org.rstudio.core.client.command.AppCommand; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.panmirror.PanmirrorConfig; import org.rstudio.studio.client.panmirror.PanmirrorUIContext; import org.rstudio.studio.client.panmirror.PanmirrorWidget; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.views.source.model.DirtyState; import org.rstudio.studio.client.workbench.views.source.model.DocUpdateSentinel; import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.Command; import com.google.inject.Inject; // TODO: currently, scroll to the line doesn't happen for find source nav // when switching from visual to source mode // TODO: images currently display too large (2x) // TODO: test image handling when there is no path (use cwd?) // TODO: shortcut overlap / routing / remapping // TODO: command / keyboard shortcut for entering visual mode // TODO: save cursor and scroll position // TODO: introduce global pref to toggle availabilty of visual mode // TODO: apply themeing // TODO: accessibility pass // TODO: wire up find and replace actions to panmirror stubs // TODO: standard editor dialog boxes public class TextEditingTargetVisualMode { public TextEditingTargetVisualMode(TextEditingTarget target, TextEditingTarget.Display display, DirtyState dirtyState, DocUpdateSentinel docUpdateSentinel) { RStudioGinjector.INSTANCE.injectMembers(this); target_ = target; display_ = display; dirtyState_ = dirtyState; docUpdateSentinel_ = docUpdateSentinel; // manage ui based on current pref + changes over time manageUI(false); onDocPropChanged(TextEditingTarget.RMD_VISUAL_MODE, (value) -> { manageUI(true); }); // sync to outline visible prop onDocPropChanged(TextEditingTarget.DOC_OUTLINE_VISIBLE, (value) -> { panmirror_.showOutline(getOutlineVisible(), getOutlineWidth(), true); }); } @Inject public void initialize(Commands commands, SourceServerOperations source) { commands_ = commands; source_ = source; } public boolean isEnabled() { return docUpdateSentinel_.getBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, false); } public void setEnabled(boolean enable) { docUpdateSentinel_.setBoolProperty(TextEditingTarget.RMD_VISUAL_MODE, enable); } public void sync() { sync(null); } public void sync(Command ready) { // if panmirror is active and has a dirty state, then generate markdown, // sync it to the editor, then clear the dirty flag if (isPanmirrorActive() && isDirty_) { withPanmirror(() -> { panmirror_.getMarkdown(markdown -> { getSourceEditor().setCode(markdown); isDirty_ = false; if (ready != null) ready.execute(); }); }); } // otherwise just return (no-op) else { if (ready != null) ready.execute(); } } public void manageCommands() { disableForVisualMode( commands_.insertChunk(), commands_.jumpTo(), commands_.jumpToMatching(), commands_.showDiagnosticsActiveDocument(), commands_.goToHelp(), commands_.goToDefinition(), commands_.extractFunction(), commands_.extractLocalVariable(), commands_.renameInScope(), commands_.reflowComment(), commands_.commentUncomment(), commands_.insertRoxygenSkeleton(), commands_.reindent(), commands_.reformatCode(), commands_.executeSetupChunk(), commands_.executeAllCode(), commands_.executeCode(), commands_.executeCodeWithoutFocus(), commands_.executeCodeWithoutMovingCursor(), commands_.executeCurrentChunk(), commands_.executeCurrentFunction(), commands_.executeCurrentLine(), commands_.executeCurrentParagraph(), commands_.executeCurrentSection(), commands_.executeCurrentStatement(), commands_.executeFromCurrentLine(), commands_.executeLastCode(), commands_.executeNextChunk(), commands_.executePreviousChunks(), commands_.executeSubsequentChunks(), commands_.executeToCurrentLine(), commands_.sendToTerminal(), commands_.runSelectionAsJob(), commands_.runSelectionAsLauncherJob(), commands_.sourceActiveDocument(), commands_.sourceActiveDocumentWithEcho(), commands_.pasteWithIndentDummy(), commands_.fold(), commands_.foldAll(), commands_.unfold(), commands_.unfoldAll(), commands_.notebookExpandAllOutput(), commands_.notebookCollapseAllOutput(), commands_.notebookClearAllOutput(), commands_.notebookClearOutput(), commands_.goToLine(), commands_.wordCount(), commands_.checkSpelling(), commands_.restartRClearOutput(), commands_.restartRRunAllChunks(), commands_.profileCode() ); } private void manageUI(boolean focus) { // manage commands manageCommands(); // manage toolbar buttons / menus in display display_.manageCommandUI(); // get references to the editing container and it's source editor TextEditorContainer editorContainer = display_.editorContainer(); TextEditorContainer.Editor editor = editorContainer.getEditor(); // visual mode enabled (panmirror editor) if (isEnabled()) { withPanmirror(() -> { // if we aren't currently active then set our markdown based // on what's currently in the source ditor if (!isPanmirrorActive()) { panmirror_.setMarkdown(editor.getCode(), true, (completed) -> { isDirty_ = false; }); } // sync to editor outline prefs panmirror_.showOutline(getOutlineVisible(), getOutlineWidth()); // activate panmirror editorContainer.activateWidget(panmirror_, focus); // begin sync-on-idle behavior syncOnIdle_.resume(); }); } // visual mode not enabled (source editor) else { // sync any pending edits, then activate the editor sync(() -> { editorContainer.activateEditor(focus); if (syncOnIdle_ != null) syncOnIdle_.suspend(); }); } } private void withPanmirror(Command ready) { if (panmirror_ == null) { // create panmirror PanmirrorConfig config = new PanmirrorConfig(uiContext()); config.options.rmdCodeChunks = true; PanmirrorWidget.Options options = new PanmirrorWidget.Options(); PanmirrorWidget.create(config, options, (panmirror) -> { // save reference to panmirror panmirror_ = panmirror; // periodically sync edits back to main editor syncOnIdle_ = new DebouncedCommand(1000) { @Override protected void execute() { if (isDirty_) sync(); } }; // set dirty flag + nudge idle sync on change panmirror_.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { // set flag and nudge sync on idle isDirty_ = true; syncOnIdle_.nudge(); // update editor dirty state if necessary if (!dirtyState_.getValue()) { dirtyState_.markDirty(false); source_.setSourceDocumentDirty( docUpdateSentinel_.getId(), true, new VoidServerRequestCallback()); } } }); // track changes in outline sidebar and save as prefs panmirror_.addPanmirrorOutlineVisibleHandler((event) -> { setOutlineVisible(event.getVisible()); }); panmirror_.addPanmirrorOutlineWidthHandler((event) -> { setOutlineWidth(event.getWidth()); }); // good to go! ready.execute(); }); } else { // panmirror already created ready.execute(); } } // is our widget active in the editor container private boolean isPanmirrorActive() { return display_.editorContainer().isWidgetActive(panmirror_); } private TextEditorContainer.Editor getSourceEditor() { return display_.editorContainer().getEditor(); } private boolean getOutlineVisible() { return target_.getPreferredOutlineWidgetVisibility(); } private void setOutlineVisible(boolean visible) { target_.setPreferredOutlineWidgetVisibility(visible); } private double getOutlineWidth() { return target_.getPreferredOutlineWidgetSize(); } private void setOutlineWidth(double width) { target_.setPreferredOutlineWidgetSize(width); } private void disableForVisualMode(AppCommand... commands) { for (AppCommand command : commands) { if (command.isVisible()) command.setEnabled(!isEnabled()); } } private void onDocPropChanged(String prop, ValueChangeHandler<String> handler) { docUpdateSentinel_.addPropertyValueChangeHandler(prop, handler); } private PanmirrorUIContext uiContext() { PanmirrorUIContext uiContext = new PanmirrorUIContext(); uiContext.translateResourcePath = path -> { return ImagePreviewer.imgSrcPathFromHref(docUpdateSentinel_, path); }; return uiContext; } private Commands commands_; private SourceServerOperations source_; private final TextEditingTarget target_; private final TextEditingTarget.Display display_; private final DirtyState dirtyState_; private final DocUpdateSentinel docUpdateSentinel_; private DebouncedCommand syncOnIdle_; private boolean isDirty_ = false; private PanmirrorWidget panmirror_; }
package org.rstudio.studio.client.workbench.views.source.editors.text.visualmode; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.panmirror.ui.PanmirrorUIChunk; import org.rstudio.studio.client.panmirror.ui.PanmirrorUIChunkFactory; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; public class VisualModeChunks { public PanmirrorUIChunkFactory uiChunkFactory() { PanmirrorUIChunkFactory factory = new PanmirrorUIChunkFactory(); factory.createChunkEditor = () -> { PanmirrorUIChunk chunk = new PanmirrorUIChunk(); // Create a new AceEditor instance and allow access to the underlying // native JavaScript object it represents (AceEditorNative) final AceEditor editor = new AceEditor(); chunk.editor = editor.getWidget().getEditor(); // Provide the editor's container element; in the future this will be a // host element which hosts chunk output DivElement ele = Document.get().createDivElement(); ele.appendChild(chunk.editor.getContainer()); chunk.element = ele; // Provide a callback to set the file's mode; this needs to happen in // GWT land since the editor accepts GWT-flavored Filetype objects chunk.setMode = (String mode) -> { setMode(editor, mode); }; // Turn off line numbers as they're not helpful in chunks chunk.editor.getRenderer().setShowGutter(false); // Allow the editor's size to be determined by its content (these // settings trigger an auto-growing behavior), up to a max of 1000 // lines. chunk.editor.setMaxLines(1000); chunk.editor.setMinLines(1); return chunk; }; return factory; } private void setMode(AceEditor editor, String mode) { switch(mode) { case "r": editor.setFileType(FileTypeRegistry.R); break; case "python": editor.setFileType(FileTypeRegistry.PYTHON); break; case "js": case "javascript": editor.setFileType(FileTypeRegistry.JS); break; case "tex": case "latex": editor.setFileType(FileTypeRegistry.TEX); break; case "c": editor.setFileType(FileTypeRegistry.C); break; case "cpp": editor.setFileType(FileTypeRegistry.CPP); break; case "sql": editor.setFileType(FileTypeRegistry.SQL); break; case "yaml": case "yaml-frontmatter": editor.setFileType(FileTypeRegistry.YAML); break; case "java": editor.setFileType(FileTypeRegistry.JAVA); break; case "html": editor.setFileType(FileTypeRegistry.HTML); break; case "shell": case "bash": editor.setFileType(FileTypeRegistry.SH); break; case "theorem": case "lemma": case "corollary": case "proposition": case "conjecture": case "definition": case "example": case "exercise": // These are Bookdown theorem types editor.setFileType(FileTypeRegistry.TEX); default: editor.setFileType(FileTypeRegistry.TEXT); break; } } }
package org.sagebionetworks.web.client.widget.accessrequirements.approval; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.Modal; import org.gwtbootstrap3.client.ui.html.Div; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class AccessorGroupViewImpl implements AccessorGroupView { @UiField Div synAlertContainer; @UiField Div accessorsContainer; @UiField Div submittedByContainer; @UiField Button showAccessRequirementButton; @UiField Div showEmailsButtonContainer; @UiField Button revokeAccessButton; @UiField Label expiresOnField; @UiField Button closeButton; @UiField Modal dialog; @UiField Div accessRequirementWidgetContainer; Presenter presenter; public interface Binder extends UiBinder<Widget, AccessorGroupViewImpl> {} Widget w; @Inject public AccessorGroupViewImpl(Binder binder){ this.w = binder.createAndBindUi(this); showAccessRequirementButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.onShowAccessRequirement(); } }); revokeAccessButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.onRevoke(); } }); closeButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { dialog.hide(); } }); } @Override public void addStyleNames(String styleNames) { w.addStyleName(styleNames); } @Override public Widget asWidget() { return w; } @Override public void setVisible(boolean visible) { w.setVisible(visible); } @Override public void setSynAlert(IsWidget w) { synAlertContainer.clear(); synAlertContainer.add(w); } @Override public void addAccessor(IsWidget w) { accessorsContainer.add(w); } @Override public void clearAccessors() { accessorsContainer.clear(); } @Override public void setSubmittedBy(IsWidget w) { submittedByContainer.clear(); submittedByContainer.add(w); } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public void showAccessRequirementDialog() { accessRequirementWidgetContainer.setVisible(true); dialog.show(); } @Override public void setAccessRequirementWidget(IsWidget w) { accessRequirementWidgetContainer.clear(); accessRequirementWidgetContainer.add(w); } @Override public void setExpiresOn(String expiresOnString) { expiresOnField.setText(expiresOnString); } @Override public void setShowEmailsButton(IsWidget w) { showEmailsButtonContainer.clear(); showEmailsButtonContainer.add(w); } }
package ca.corefacility.bioinformatics.irida.service.impl.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPOutputStream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithSecurityContextTestExcecutionListener; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import ca.corefacility.bioinformatics.irida.config.IridaApiServicesConfig; import ca.corefacility.bioinformatics.irida.config.IridaApiNoGalaxyTestConfig; import ca.corefacility.bioinformatics.irida.config.data.IridaApiTestDataSourceConfig; import ca.corefacility.bioinformatics.irida.config.processing.IridaApiTestMultithreadingConfig; import ca.corefacility.bioinformatics.irida.model.OverrepresentedSequence; import ca.corefacility.bioinformatics.irida.model.SequenceFile; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.run.SequencingRun; import ca.corefacility.bioinformatics.irida.model.sample.Sample; import ca.corefacility.bioinformatics.irida.model.user.Role; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisFastQC; import ca.corefacility.bioinformatics.irida.service.AnalysisService; import ca.corefacility.bioinformatics.irida.service.SequenceFileService; import ca.corefacility.bioinformatics.irida.service.SequencingRunService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.google.common.collect.ImmutableList; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiServicesConfig.class, IridaApiNoGalaxyTestConfig.class, IridaApiTestDataSourceConfig.class, IridaApiTestMultithreadingConfig.class }) @ActiveProfiles("test") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class, WithSecurityContextTestExcecutionListener.class }) @DatabaseSetup("/ca/corefacility/bioinformatics/irida/service/impl/SequenceFileServiceImplIT.xml") @DatabaseTearDown(value = "/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml", type = DatabaseOperation.DELETE_ALL) public class SequenceFileServiceImplIT { private static final String SEQUENCE = "ACGTACGTN"; private static final byte[] FASTQ_FILE_CONTENTS = ("@testread\n" + SEQUENCE + "\n+\n?????????\n@testread2\n" + SEQUENCE + "\n+\n?????????").getBytes(); private static final Logger logger = LoggerFactory.getLogger(SequenceFileServiceImplIT.class); @Autowired private SequenceFileService sequenceFileService; @Autowired private AnalysisService analysisService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private SampleService sampleService; @Autowired private SequencingRunService sequencingRunService; @Autowired @Qualifier("sequenceFileBaseDirectory") private Path baseDirectory; @Before public void setUp() throws IOException { Files.createDirectories(baseDirectory); } private SequenceFileServiceImplIT asRole(Role r, String username) { User u = new User(); u.setUsername(username); u.setPassword(passwordEncoder.encode("Password1")); u.setSystemRole(r); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(u, "Password1", ImmutableList.of(r)); auth.setDetails(u); SecurityContextHolder.getContext().setAuthentication(auth); return this; } @Test(expected = AccessDeniedException.class) @WithMockUser(username = "fbristow", roles = "USER") public void testReadSequenceFileAsUserNoPermissions() { sequenceFileService.read(1L); } @Test @WithMockUser(username = "fbristow1", roles = "USER") public void testReadSequenceFileAsUserWithPermissions() { sequenceFileService.read(1L); } @Test @WithMockUser(username = "fbristow1", roles = "USER") public void testReadOptionalProperties() { SequenceFile read = sequenceFileService.read(1L); assertEquals("5", read.getOptionalProperty("samplePlate")); assertEquals("10", read.getOptionalProperty("sampleWell")); } @Test @WithMockUser(username = "fbristow1", roles = "USER") public void testAddAdditionalProperties() throws IOException { SequenceFile file = sequenceFileService.read(1L); file.addOptionalProperty("index", "111"); Path sequenceFile = Files.createTempFile(null, null); Files.write(sequenceFile, FASTQ_FILE_CONTENTS); file.setFile(sequenceFile); Map<String, Object> changed = new HashMap<>(); changed.put("optionalProperties", file.getOptionalProperties()); changed.put("file", file.getFile()); sequenceFileService.update(file.getId(), changed); SequenceFile reread = sequenceFileService.read(1L); assertNotNull(reread.getOptionalProperty("index")); assertEquals("111", reread.getOptionalProperty("index")); } @Test @WithMockUser(username = "tom", roles = "SEQUENCER") public void testCreateNotCompressedSequenceFile() throws IOException { SequenceFile sf = new SequenceFile(); Path sequenceFile = Files.createTempFile(null, null); Files.write(sequenceFile, FASTQ_FILE_CONTENTS); sf.setFile(sequenceFile); logger.trace("About to save the file."); sf = asRole(Role.ROLE_SEQUENCER, "fbristow").sequenceFileService.create(sf); logger.trace("Finished saving the file."); assertNotNull("ID wasn't assigned.", sf.getId()); // figure out what the version number of the sequence file is (should be // 2; the file wasn't gzipped, but fastqc will have modified it.) sf = asRole(Role.ROLE_ADMIN, "tom").sequenceFileService.read(sf.getId()); assertEquals("Wrong version number after processing.", Long.valueOf(1), sf.getFileRevisionNumber()); Set<AnalysisFastQC> analyses = asRole(Role.ROLE_ADMIN, "tom").analysisService.getAnalysesForSequenceFile(sf, AnalysisFastQC.class); assertEquals("Only one analysis should be generated automatically.", 1, analyses.size()); AnalysisFastQC analysis = analyses.iterator().next(); Set<OverrepresentedSequence> overrepresentedSequences = analysis.getOverrepresentedSequences(); assertNotNull("No overrepresented sequences were found.", overrepresentedSequences); assertEquals("Wrong number of overrepresented sequences were found.", 1, overrepresentedSequences.size()); OverrepresentedSequence overrepresentedSequence = overrepresentedSequences.iterator().next(); assertEquals("Sequence was not the correct sequence.", SEQUENCE, overrepresentedSequence.getSequence()); assertEquals("The count was not correct.", 2, overrepresentedSequence.getOverrepresentedSequenceCount()); assertEquals("The percent was not correct.", new BigDecimal("100.00"), overrepresentedSequence.getPercentage()); // confirm that the file structure is correct Path idDirectory = baseDirectory.resolve(Paths.get(sf.getId().toString())); assertTrue("Revision directory doesn't exist.", Files.exists(idDirectory.resolve(Paths.get(sf .getFileRevisionNumber().toString(), sequenceFile.getFileName().toString())))); // no other files or directories should be beneath the ID directory int fileCount = 0; Iterator<Path> dir = Files.newDirectoryStream(idDirectory).iterator(); while (dir.hasNext()) { dir.next(); fileCount++; } assertEquals("Wrong number of directories beneath the id directory", 1, fileCount); } @Test @WithMockUser(username = "fbristow", roles = "SEQUENCER") public void testCreateCompressedSequenceFile() throws IOException { SequenceFile sf = new SequenceFile(); Path sequenceFile = Files.createTempFile("TEMPORARY-SEQUENCE-FILE", ".gz"); OutputStream gzOut = new GZIPOutputStream(Files.newOutputStream(sequenceFile)); gzOut.write(FASTQ_FILE_CONTENTS); gzOut.close(); sf.setFile(sequenceFile); logger.trace("About to save the file."); sf = sequenceFileService.create(sf); logger.trace("Finished saving the file."); assertNotNull("ID wasn't assigned.", sf.getId()); // figure out what the version number of the sequence file is (should be // 2; the file was gzipped) // get the MOST RECENT version of the sequence file from the database // (it will have been modified outside of the create method.) sf = asRole(Role.ROLE_ADMIN, "tom").sequenceFileService.read(sf.getId()); assertEquals("Wrong version number after processing.", Long.valueOf(2L), sf.getFileRevisionNumber()); assertFalse("File name is still gzipped.", sf.getFile().getFileName().toString().endsWith(".gz")); Set<AnalysisFastQC> analyses = asRole(Role.ROLE_ADMIN, "tom").analysisService.getAnalysesForSequenceFile(sf, AnalysisFastQC.class); assertEquals("Only one analysis should be generated automatically.", 1, analyses.size()); AnalysisFastQC analysis = analyses.iterator().next(); Set<OverrepresentedSequence> overrepresentedSequences = analysis.getOverrepresentedSequences(); assertNotNull("No overrepresented sequences were found.", overrepresentedSequences); assertEquals("Wrong number of overrepresented sequences were found.", 1, overrepresentedSequences.size()); OverrepresentedSequence overrepresentedSequence = overrepresentedSequences.iterator().next(); assertEquals("Sequence was not the correct sequence.", SEQUENCE, overrepresentedSequence.getSequence()); assertEquals("The count was not correct.", 2, overrepresentedSequence.getOverrepresentedSequenceCount()); assertEquals("The percent was not correct.", new BigDecimal("100.00"), overrepresentedSequence.getPercentage()); // confirm that the file structure is correct String filename = sequenceFile.getFileName().toString(); filename = filename.substring(0, filename.lastIndexOf('.')); Path idDirectory = baseDirectory.resolve(Paths.get(sf.getId().toString())); assertTrue("Revision directory doesn't exist.", Files.exists(idDirectory.resolve(Paths.get(sf.getFileRevisionNumber().toString(), filename)))); // no other files or directories should be beneath the ID directory int fileCount = 0; Iterator<Path> dir = Files.newDirectoryStream(idDirectory).iterator(); while (dir.hasNext()) { dir.next(); fileCount++; } assertEquals("Wrong number of directories beneath the id directory", 2, fileCount); } @Test @WithMockUser(username = "fbristow", roles = "SEQUENCER") public void testCreateSequenceFileInSample() throws IOException { Sample s = sampleService.read(1L); SequenceFile sf = new SequenceFile(); Path sequenceFile = Files.createTempFile("TEMPORARY-SEQUENCE-FILE", ".gz"); OutputStream gzOut = new GZIPOutputStream(Files.newOutputStream(sequenceFile)); gzOut.write(FASTQ_FILE_CONTENTS); gzOut.close(); sf.setFile(sequenceFile); sequenceFileService.createSequenceFileInSample(sf, s); SequencingRun mr = sequencingRunService.read(1L); sequencingRunService.addSequenceFileToSequencingRun(mr, sf); } @Test @WithMockUser(username = "fbristow", roles = "SEQUENCER") public void testGetSequencefilesForSampleAsSequencer() throws IOException { Sample s = sampleService.read(1L); List<Join<Sample, SequenceFile>> sequenceFilesForSample = sequenceFileService.getSequenceFilesForSample(s); assertEquals(1, sequenceFilesForSample.size()); } }
package org.carlspring.strongbox.users.domain; import org.carlspring.strongbox.data.domain.GenericEntity; import java.util.HashSet; import java.util.Set; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.common.base.Objects; /** * An application user */ @JsonInclude(JsonInclude.Include.NON_NULL) public class User extends GenericEntity { private String username; private String password; private boolean enabled; private Set<String> roles; private String securityTokenKey; private AccessModel accessModel; public User() { roles = new HashSet<>(); } public User(String id, String username, String password, boolean enabled, Set<String> roles) { this.objectId = id; this.username = username; this.password = password; this.enabled = enabled; this.roles = roles; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return enabled == user.enabled && Objects.equal(username, user.username) && Objects.equal(password, user.password) && Objects.equal(roles, user.roles) && Objects.equal(securityTokenKey, user.securityTokenKey) && Objects.equal(accessModel, user.accessModel); } @Override public int hashCode() { return Objects.hashCode(username, password, enabled, roles, securityTokenKey, accessModel); } public String getUsername() { return username; } public void setUsername(final String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } public boolean isEnabled() { return enabled; } public void setEnabled(final boolean enabled) { this.enabled = enabled; } public Set<String> getRoles() { return roles; } public void setRoles(final Set<String> roles) { this.roles = roles; } public String getSecurityTokenKey() { return securityTokenKey; } public void setSecurityTokenKey(String securityTokenKey) { this.securityTokenKey = securityTokenKey; } public AccessModel getAccessModel() { return accessModel; } public void setAccessModel(AccessModel accessModel) { // ORecordDuplicatedException: Cannot index record AccessModel{....}: // found duplicated key '....' in index 'idx_uuid' previously assigned to the record ... if (this.accessModel != null && accessModel != null && accessModel.getUuid() != null && Objects.equal(this.accessModel.getUuid(), accessModel.getUuid()) && !Objects.equal(this.accessModel.getObjectId(), accessModel.getObjectId())) { accessModel.setUuid(UUID.randomUUID().toString()); } this.accessModel = accessModel; } @Override public String toString() { final StringBuilder sb = new StringBuilder("User{"); sb.append("username='") .append(username) .append('\''); sb.append(", enabled=") .append(enabled); sb.append(", roles=") .append(roles); sb.append(", securityTokenKey='") .append(securityTokenKey) .append('\''); sb.append(", accessModel=") .append(accessModel); sb.append('}'); return sb.toString(); } }
package ch.elexis.data; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.constants.TextContainerConstants; import ch.elexis.core.data.interfaces.scripting.Interpreter; import ch.elexis.core.exceptions.ElexisException; import ch.elexis.core.model.ILabItem; import ch.elexis.core.model.ILabResult; import ch.elexis.core.types.LabItemTyp; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; public class LabItem extends PersistentObject implements Comparable<LabItem>, ILabItem { public static final String REF_MALE = "RefMann"; //$NON-NLS-1$ public static final String REF_FEMALE_OR_TEXT = "RefFrauOrTx"; //$NON-NLS-1$ public static final String PRIO = "prio"; //$NON-NLS-1$ public static final String GROUP = "Gruppe"; //$NON-NLS-1$ public static final String TYPE = "Typ"; //$NON-NLS-1$ public static final String UNIT = "Einheit"; //$NON-NLS-1$ public static final String LAB_ID = "LaborID"; //$NON-NLS-1$ public static final String TITLE = "titel"; //$NON-NLS-1$ public static final String SHORTNAME = "kuerzel"; //$NON-NLS-1$ public static final String EXPORT = "export"; //$NON-NLS-1$ public static final String FORMULA = "formula"; //$NON-NLS-1$ public static final String DIGITS = "digits"; //$NON-NLS-1$ public static final String VISIBLE = "visible"; //$NON-NLS-1$ public static final String BILLINGCODE = "billingcode"; //$NON-NLS-1$ public static final String LOINCCODE = "loinccode"; //$NON-NLS-1$ static final String LABITEMS = "LABORITEMS"; //$NON-NLS-1$ private static final Pattern varPattern = Pattern.compile(TextContainerConstants.MATCH_TEMPLATE); @Override protected String getTableName(){ return LABITEMS; } static { addMapping(LABITEMS, SHORTNAME, TITLE, LAB_ID, REF_MALE, REF_FEMALE_OR_TEXT, UNIT, TYPE, GROUP, PRIO, EXPORT, FORMULA, DIGITS, VISIBLE, BILLINGCODE, LOINCCODE); } /** * Erstellt ein neues LaborItem. * * @param k * Testkuerzel (e.g. BILI) * @param t * Testname (e.g. Bilirubin gesamt) * @param labor * Labor-Identitaet (e.g. Eigenlabor) * @param RefMann * Referenzwerte Mann (e.g. 0.0-1.2) * @param RefFrau * Referenzwerte Frau (e.g. 0.0-1.2) * @param Unit * Masseinheit (e.g. mg/dl) * @param type * NUMERIC, ABSOLUTE or DOCUMENT * @param grp * Gruppenzugehoerigkeit * @param seq * Sequenz-Nummer */ public LabItem(String k, String t, Kontakt labor, String RefMann, String RefFrau, String Unit, LabItemTyp type, String grp, String seq){ this(k, t, (labor != null) ? labor.getId() : null, RefMann, RefFrau, Unit, type, grp, seq); } /** * @since 3.2 */ public LabItem(String k, String t, String laborId, String RefMann, String RefFrau, String Unit, LabItemTyp type, String grp, String seq){ String tp = "1"; //$NON-NLS-1$ if (type == LabItemTyp.NUMERIC) { tp = "0"; //$NON-NLS-1$ } else if (type == LabItemTyp.ABSOLUTE) { tp = "2"; //$NON-NLS-1$ } else if (type == LabItemTyp.FORMULA) { tp = "3"; //$NON-NLS-1$ } else if (type == LabItemTyp.DOCUMENT) { tp = "4"; //$NON-NLS-1$ } create(null); if (StringTool.isNothing(seq)) { seq = t.substring(0, 1); } if (StringTool.isNothing(grp)) { grp = Messages.LabItem_defaultGroup; } if (laborId == null) { Query<Kontakt> qbe = new Query<Kontakt>(Kontakt.class); String labid = qbe.findSingle(Kontakt.FLD_IS_LAB, Query.EQUALS, StringConstants.ONE); if (labid == null) { laborId = new Labor(Messages.LabItem_shortOwnLab, Messages.LabItem_longOwnLab).getId(); } } set(new String[] { SHORTNAME, TITLE, LAB_ID, REF_MALE, REF_FEMALE_OR_TEXT, UNIT, TYPE, GROUP, PRIO }, k, t, laborId, RefMann, RefFrau, Unit, tp, grp, seq); } protected LabItem(){/* leer */ } protected LabItem(String id){ super(id); } public static LabItem load(String id){ return new LabItem(id); } /** * This is the value that will be used for a LabResult if there is no other unit value * available. The effective unit value is moved to the LabResult. */ public String getEinheit(){ return checkNull(get(UNIT)); } /** * This is the value that will be used for a LabResult if there is no other unit value * available. The effective unit value is moved to the LabResult. */ public void setEinheit(String unit){ set(UNIT, unit); } public String getGroup(){ return checkNull(get(GROUP)); } public void setGroup(String group){ set(GROUP, group); } public String getPrio(){ return checkNull(get(PRIO)); } public void setPrio(String prio){ set(PRIO, prio); } public String getKuerzel(){ return checkNull(get(SHORTNAME)); } public void setKuerzel(String shortname){ set(SHORTNAME, shortname); } public String getName(){ return checkNull(get(TITLE)); } public void setName(String title){ set(TITLE, title); } /** * @deprecated The labor has been moved to the LabOrder. */ public Labor getLabor(){ return Labor.load(get(LAB_ID)); } public String getExport(){ return checkNull(get(EXPORT)); } public void setExport(String export){ set(EXPORT, export); } public void setTyp(LabItemTyp typ){ String t = "0"; //$NON-NLS-1$ if (typ == LabItemTyp.TEXT) { t = "1"; //$NON-NLS-1$ } else if (typ == LabItemTyp.ABSOLUTE) { t = "2"; //$NON-NLS-1$ } else if (typ == LabItemTyp.FORMULA) { t = "3"; //$NON-NLS-1$ } else if (typ == LabItemTyp.DOCUMENT) { t = "4"; //$NON-NLS-1$ } set(TYPE, t); } public LabItemTyp getTyp(){ String t = get(TYPE); if (t != null) { if (t.equals(StringConstants.ZERO)) { return LabItemTyp.NUMERIC; } else if (t.equals(StringConstants.ONE)) { return LabItemTyp.TEXT; } else if (t.equals("2")) { //$NON-NLS-1$ return LabItemTyp.ABSOLUTE; } else if (t.equals("3")) { //$NON-NLS-1$ return LabItemTyp.FORMULA; } else if (t.equals("4")) { //$NON-NLS-1$ return LabItemTyp.DOCUMENT; } } return LabItemTyp.TEXT; } public String evaluateNew(Patient pat, TimeTool date, List<ILabResult> results){ String formel = getFormula(); formel = formel.substring(Script.SCRIPT_MARKER.length()); results = sortResultsDescending(results); for (ILabResult result : results) { String var = ((LabItem) result.getItem()).makeVarName(); if (formel.indexOf(var) != -1) { formel = formel.replaceAll(var, result.getResult()); } } try { return Script.executeScript(formel, pat).toString(); } catch (ElexisException e) { return "?formel?"; //$NON-NLS-1$ } } public String evaluate(Patient pat, List<ILabResult> results) throws ElexisException{ if (!getTyp().equals(LabItemTyp.FORMULA)) { return null; } String formel = getFormula(); if (formel.startsWith(Script.SCRIPT_MARKER)) { return evaluateNew(pat, null, results); } boolean bMatched = false; results = sortResultsDescending(results); for (ILabResult result : results) { String var = ((LabItem) result.getItem()).makeVarName(); if (formel.indexOf(var) != -1) { if (result.getResult() != null && !result.getResult().isEmpty() && !result.getResult().equals("?")) { //$NON-NLS-1$ formel = formel.replaceAll(var, result.getResult()); bMatched = true; } } } Matcher matcher = varPattern.matcher(formel); // Suche Variablen der Form [Patient.Alter] StringBuffer sb = new StringBuffer(); while (matcher.find()) { String var = matcher.group(); String[] fields = var.split("\\."); //$NON-NLS-1$ if (fields.length > 1) { String repl = "\"" + pat.get(fields[1].replaceFirst("\\]", StringTool.leer)) + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // formel=matcher.replaceFirst(repl); matcher.appendReplacement(sb, repl); bMatched = true; } } matcher.appendTail(sb); if (!bMatched) { return null; } Interpreter scripter = Script.getInterpreterFor(formel); try { String result = scripter.run(sb.toString(), false).toString(); return result; } catch (ElexisException e) { return "?formel?"; //$NON-NLS-1$ } } private List<ILabResult> sortResultsDescending(List<ILabResult> results){ Collections.sort(results, new Comparator<ILabResult>() { @Override public int compare(ILabResult lr1, ILabResult lr2){ int var1Length = ((LabItem) lr1.getItem()).makeVarName().length(); int var2Length = ((LabItem) lr2.getItem()).makeVarName().length(); if (var1Length < var2Length) { return 1; } else if (var1Length > var2Length) { return -1; } return 0; } }); return results; } /** * Evaluate a formula-based LabItem for a given Patient at a given date. It will try to retrieve * all LabValues it depends on of that Patient and date and then calculate the result. If there * are not all necessare values given, it will return "?formula?". The formula can be a * beanshell-script by itself (for compatibility with previous versions), or the name of a * script prefixed with SCRIPT:, e.g. SCRIPT:mdrd($krea=c_10). Variable names are the group and * priority values of a lab item separated with an underscore. * * @param date * The date to consider for calculating * @return the result or "?formel?" if no result could be calculated. */ public String evaluate(Patient pat, TimeTool date) throws ElexisException{ if (!getTyp().equals(LabItemTyp.FORMULA)) { return null; } Query<ILabResult> qbe = new Query<ILabResult>(LabResult.class); qbe.add(LabResult.PATIENT_ID, Query.EQUALS, pat.getId()); qbe.add(LabResult.DATE, Query.EQUALS, date.toString(TimeTool.DATE_COMPACT)); List<ILabResult> results = qbe.execute(); return evaluate(pat, results); } /** * Return the variable Name that identifies this item (in a script) * * @return a name that is made of the group and the priority values. */ public String makeVarName(){ String[] group = getGroup().split(StringTool.space, 2); String num = getPrio().trim(); return group[0] + "_" + num; //$NON-NLS-1$ } public int getDigits(){ String digits = checkNull(get(DIGITS)); if (digits.isEmpty()) { return 0; } else { return Integer.parseInt(digits); } } public void setDigits(int digits){ set(DIGITS, Integer.toString(digits)); } public boolean isVisible(){ String visible = get(VISIBLE); // not set defaults to true if (visible == null || visible.isEmpty()) { setVisible(true); return true; } return visible.equals("1"); //$NON-NLS-1$ } public void setVisible(boolean visible){ if (visible) { set(VISIBLE, "1"); //$NON-NLS-1$ } else { set(VISIBLE, "0"); //$NON-NLS-1$ } } /** * This is the value that will be used for a LabResult if there is no other Ref value available. * The effective Ref value is moved to the LabResult. */ public String getRefW(){ String ret = checkNull(get(REF_FEMALE_OR_TEXT)).split("##")[0]; //$NON-NLS-1$ return ret; } /** * This is the value that will be used for a LabResult if there is no other Ref value available. * The effective Ref value is moved to the LabResult. */ public String getRefM(){ return checkNull(get(REF_MALE)); } /** * This is the value that will be used for a LabResult if there is no other Ref value available. * The effective Ref value is moved to the LabResult. */ public void setRefW(String r){ set(REF_FEMALE_OR_TEXT, r); } /** * This is the value that will be used for a LabResult if there is no other Ref value available. * The effective Ref value is moved to the LabResult. */ public void setRefM(String r){ set(REF_MALE, r); } public void setFormula(String f){ set(FORMULA, f); } public String getFormula(){ String formula = get(FORMULA); if (formula == null || formula.isEmpty()) { String[] refWEntry = get(REF_FEMALE_OR_TEXT).split(" formula = refWEntry.length > 1 ? refWEntry[1] : ""; if (formula != null && !formula.isEmpty()) { setFormula(formula); } } return formula; } public String getLoincCode(){ return checkNull(get(LOINCCODE)); } public void setLoincCode(String code){ set(LOINCCODE, code); } public String getBillingCode(){ return checkNull(get(BILLINGCODE)); } public void setBillingCode(String code){ set(BILLINGCODE, code); } @Override public String getLabel(){ StringBuilder sb = new StringBuilder(); String[] fields = { SHORTNAME, TITLE, REF_MALE, REF_FEMALE_OR_TEXT, UNIT, TYPE, GROUP, PRIO }; String[] vals = new String[fields.length]; get(fields, vals); sb.append(vals[0]).append(", ").append(vals[1]); //$NON-NLS-1$ if (vals[5].equals(StringConstants.ZERO)) { sb.append(" (").append(vals[2]).append("/").append(getRefW()).append(StringTool.space) //$NON-NLS-1$ //$NON-NLS-2$ .append(vals[4]).append(")"); //$NON-NLS-1$ } else { sb.append(" (").append(getRefW()).append(")"); //$NON-NLS-1$ //$NON-NLS-2$ } sb.append("[").append(vals[6]).append(", ").append(vals[7]).append("]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return sb.toString(); } public String getShortLabel(){ StringBuilder sb = new StringBuilder(); String[] fields = { TITLE, UNIT, LAB_ID }; String[] vals = new String[fields.length]; get(fields, vals); Labor lab = Labor.load(vals[2]); String labName = "Labor?"; //$NON-NLS-1$ if (lab != null) { labName = lab.get("Bezeichnung1"); //$NON-NLS-1$ } sb.append(vals[0]).append(" (").append(vals[1]).append("; ").append(labName).append(")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return sb.toString(); } public int compareTo(LabItem other){ // check for null; put null values at the end if (other == null) { return -1; } // first, compare the groups String mineGroup = getGroup(); String otherGroup = other.getGroup(); if (!mineGroup.equals(otherGroup)) { // groups differ, just compare groups return mineGroup.compareTo(otherGroup); } // compare item priorities String mine = getPrio().trim(); String others = other.getPrio().trim(); if ((mine.matches("[0-9]+")) && (others.matches("[0-9]+"))) { //$NON-NLS-1$ //$NON-NLS-2$ Integer iMine = Integer.parseInt(mine); Integer iOthers = Integer.parseInt(others); return iMine.compareTo(iOthers); } return mine.compareTo(others); } /** * Get a List of all LabItems from the database * * @return List of {@link LabItem} */ public static List<LabItem> getLabItems(){ Query<LabItem> qbe = new Query<LabItem>(LabItem.class); return qbe.execute(); } /** * Get a List of LabItems matching the specified parameters in the database By specifying null * parameters the LabItem selection can be broadened. * * @param laborId * the Id of the lab the items belong to * @param shortDesc * the short description for the items * @param refM * the male reference value for the items * @param refW * the female reference value for the items * @param unit * the unit for the items * * @return List of {@link LabItem} */ public static List<LabItem> getLabItems(String laborId, String shortDesc, String refM, String refW, String unit){ Query<LabItem> qbe = new Query<LabItem>(LabItem.class); if (laborId != null && laborId.length() > 0) { qbe.add("LaborID", "=", laborId); //$NON-NLS-1$ //$NON-NLS-2$ } if (shortDesc != null && shortDesc.length() > 0) { // none case sensitive matching for kuerzel qbe.add("kuerzel", "=", shortDesc, true); //$NON-NLS-1$ //$NON-NLS-2$ } if (refM != null && refM.length() > 0) { // none case sensitive matching for ref male qbe.add("RefMann", "=", refM, true); //$NON-NLS-1$ //$NON-NLS-2$ } if (refW != null && refW.length() > 0) { // none case sensitive matching for ref female qbe.add("RefFrauOrTx", "=", refW, true); //$NON-NLS-1$ //$NON-NLS-2$ } if (unit != null && unit.length() > 0) { // none case sensitive matching for unit qbe.add("Einheit", "=", unit, true); //$NON-NLS-1$ //$NON-NLS-2$ } return qbe.execute(); } /** * Copies all LabResults from the source LabItem to this LabItem. ATTENTION this can not be * reverted. The properties (originId,refW,refM,unit) will be updated from the source LabItem to * the LabResult if not already set. * * @param source */ public void mergeWith(LabItem source){ Query<LabResult> qsr = new Query<LabResult>(LabResult.class); qsr.add(LabResult.ITEM_ID, Query.EQUALS, source.getId()); List<LabResult> sourceResults = qsr.execute(); for (LabResult labResult : sourceResults) { // update data from the LabItem to the LabResult if (labResult.getOrigin() == null) { labResult.setOrigin(source.getLabor()); } // test against values in db as getter will return value from LabItem String resultProp = labResult.get(LabResult.REFFEMALE); if (resultProp == null || resultProp.isEmpty()) { labResult.setRefFemale(source.getRefW()); } resultProp = labResult.get(LabResult.REFMALE); if (resultProp == null || resultProp.isEmpty()) { labResult.setRefMale(source.getRefM()); } resultProp = labResult.get(LabResult.UNIT); if (resultProp == null || resultProp.isEmpty()) { labResult.setUnit(source.get(LabItem.UNIT)); } // update the reference to the LabItem labResult.set(LabResult.ITEM_ID, getId()); } } @Override public String getReferenceMale(){ return getRefM(); } @Override public void setReferenceMale(String value){ setRefM(value); } @Override public String getReferenceFemale(){ return getRefW(); } @Override public void setReferenceFemale(String value){ setRefW(value); } @Override public String getPriority(){ return getPrio(); } @Override public void setPriority(String value){ setPrio(value); } @Override public String getUnit(){ return getEinheit(); } @Override public void setUnit(String value){ setEinheit(value); } }
package com.splicemachine.derby.impl.sql.execute.operations; import com.google.common.collect.Lists; import com.splicemachine.constants.SIConstants; import com.splicemachine.constants.SpliceConstants; import com.splicemachine.derby.hbase.SpliceDriver; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext; import com.splicemachine.derby.iapi.sql.execute.SpliceRuntimeContext; import com.splicemachine.derby.iapi.storage.RowProvider; import com.splicemachine.derby.impl.storage.ClientScanProvider; import com.splicemachine.derby.impl.store.ExecRowAccumulator; import com.splicemachine.derby.metrics.OperationMetric; import com.splicemachine.derby.metrics.OperationRuntimeStats; import com.splicemachine.derby.utils.DerbyBytesUtil; import com.splicemachine.derby.utils.EntryPredicateUtils; import com.splicemachine.derby.utils.SpliceUtils; import com.splicemachine.derby.utils.StandardSupplier; import com.splicemachine.derby.utils.marshall.*; import com.splicemachine.encoding.MultiFieldDecoder; import com.splicemachine.si.api.HTransactorFactory; import com.splicemachine.si.data.hbase.HRowAccumulator; import com.splicemachine.si.impl.FilterState; import com.splicemachine.si.impl.FilterStatePacked; import com.splicemachine.si.impl.IFilterState; import com.splicemachine.si.impl.TransactionId; import com.splicemachine.stats.Counter; import com.splicemachine.stats.TimeView; import com.splicemachine.storage.EntryPredicateFilter; import com.splicemachine.utils.ByteSlice; import com.splicemachine.utils.SpliceLogUtils; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.io.FormatableBitSet; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.loader.GeneratedMethod; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.execute.ExecRow; import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.types.RowLocation; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; public class TableScanOperation extends ScanOperation { private static final long serialVersionUID = 3l; protected static Logger LOG = Logger.getLogger(TableScanOperation.class); protected static List<NodeType> nodeTypes; protected int indexColItem; public String userSuppliedOptimizerOverrides; public int rowsPerRead; protected boolean runTimeStatisticsOn; private Properties scanProperties; public String startPositionString; public String stopPositionString; public ByteSlice slice; static { nodeTypes = Arrays.asList(NodeType.MAP,NodeType.SCAN); } private int[] baseColumnMap; private int[] keyColumns; private List<KeyValue> keyValues; private FilterStatePacked siFilter; private Scan scan; private Counter filterCount; public TableScanOperation() { super(); } public TableScanOperation(ScanInformation scanInformation, OperationInformation operationInformation, int lockMode, int isolationLevel) throws StandardException { super(scanInformation, operationInformation, lockMode, isolationLevel); } @SuppressWarnings("UnusedParameters") public TableScanOperation(long conglomId, StaticCompiledOpenConglomInfo scoci, Activation activation, GeneratedMethod resultRowAllocator, int resultSetNumber, GeneratedMethod startKeyGetter, int startSearchOperator, GeneratedMethod stopKeyGetter, int stopSearchOperator, boolean sameStartStopPosition, String qualifiersField, String tableName, String userSuppliedOptimizerOverrides, String indexName, boolean isConstraint, boolean forUpdate, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel, int rowsPerRead, boolean oneRowScan, double optimizerEstimatedRowCount, double optimizerEstimatedCost) throws StandardException { super(conglomId, activation, resultSetNumber, startKeyGetter, startSearchOperator, stopKeyGetter, stopSearchOperator, sameStartStopPosition, qualifiersField, resultRowAllocator, lockMode, tableLocked, isolationLevel, colRefItem, optimizerEstimatedRowCount, optimizerEstimatedCost); SpliceLogUtils.trace(LOG, "instantiated for tablename %s or indexName %s with conglomerateID %d", tableName, indexName, conglomId); this.forUpdate = forUpdate; this.isConstraint = isConstraint; this.rowsPerRead = rowsPerRead; this.tableName = Long.toString(scanInformation.getConglomerateId()); this.indexColItem = indexColItem; this.indexName = indexName; runTimeStatisticsOn = operationInformation.isRuntimeStatisticsEnabled(); if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG, "statisticsTimingOn=%s,isTopResultSet=%s,runTimeStatisticsOn%s",statisticsTimingOn,isTopResultSet,runTimeStatisticsOn); init(SpliceOperationContext.newContext(activation)); recordConstructorTime(); } @Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { super.readExternal(in); tableName = in.readUTF(); indexColItem = in.readInt(); if(in.readBoolean()) indexName = in.readUTF(); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeUTF(tableName); out.writeInt(indexColItem); out.writeBoolean(indexName != null); if(indexName!=null) out.writeUTF(indexName); } @Override public void init(SpliceOperationContext context) throws StandardException{ super.init(context); this.baseColumnMap = operationInformation.getBaseColumnMap(); this.slice = ByteSlice.empty(); this.startExecutionTime = System.currentTimeMillis(); this.scan = context.getScan(); } @Override public List<SpliceOperation> getSubOperations() { return Collections.emptyList(); } @Override public RowProvider getMapRowProvider(SpliceOperation top,PairDecoder decoder, SpliceRuntimeContext spliceRuntimeContext) throws StandardException { SpliceLogUtils.trace(LOG, "getMapRowProvider"); beginTime = System.currentTimeMillis(); Scan scan = getNonSIScan(spliceRuntimeContext); SpliceUtils.setInstructions(scan, activation, top,spliceRuntimeContext); ClientScanProvider provider = new ClientScanProvider("tableScan",Bytes.toBytes(tableName),scan, decoder,spliceRuntimeContext); nextTime += System.currentTimeMillis() - beginTime; return provider; } protected Scan getNonSIScan(SpliceRuntimeContext spliceRuntimeContext) { /* * Intended to get a scan which does NOT set up SI underneath us (since * we are doing it ourselves). */ Scan scan = buildScan(spliceRuntimeContext); deSiify(scan); return scan; } protected void deSiify(Scan scan) { /* * Remove SI-specific behaviors from the scan, so that we can handle it ourselves correctly. */ //exclude this from SI treatment, since we're doing it internally scan.setAttribute(SIConstants.SI_NEEDED,null); scan.setMaxVersions(); Map<byte[], NavigableSet<byte[]>> familyMap = scan.getFamilyMap(); if(familyMap!=null){ NavigableSet<byte[]> bytes = familyMap.get(SpliceConstants.DEFAULT_FAMILY_BYTES); if(bytes!=null) bytes.clear(); //make sure we get all columns } } @Override public RowProvider getReduceRowProvider(SpliceOperation top, PairDecoder decoder, SpliceRuntimeContext spliceRuntimeContext, boolean returnDefaultValue) throws StandardException { return getMapRowProvider(top, decoder, spliceRuntimeContext); } @Override public KeyEncoder getKeyEncoder(SpliceRuntimeContext spliceRuntimeContext) throws StandardException { columnOrdering = scanInformation.getColumnOrdering(); if(columnOrdering != null && columnOrdering.length > 0) { getKeyColumns(); } /* * Table Scans only use a key encoder when encoding to SpliceOperationRegionScanner, * in which case, the KeyEncoder should be either the row location of the last emitted * row, or a random field (if no row location is specified). */ DataHash hash = new KeyDataHash(new StandardSupplier<byte[]>() { @Override public byte[] get() throws StandardException { if(currentRowLocation!=null) return currentRowLocation.getBytes(); return SpliceDriver.driver().getUUIDGenerator().nextUUIDBytes(); } }, keyColumns, scanInformation.getKeyColumnDVDs()); return new KeyEncoder(NoOpPrefix.INSTANCE,hash,NoOpPostfix.INSTANCE); } protected int[] getKeyColumns() throws StandardException { if(keyColumns==null){ columnOrdering = scanInformation.getColumnOrdering(); keyColumns = new int[columnOrdering.length]; for (int i = 0; i < keyColumns.length; ++i) { keyColumns[i] = -1; } for (int i = 0; i < keyColumns.length && columnOrdering[i] < baseColumnMap.length; ++i) { keyColumns[i] = baseColumnMap[columnOrdering[i]]; } } return keyColumns; } private int[] getDecodingColumns(int n) { int[] columns = new int[baseColumnMap.length]; System.arraycopy(baseColumnMap, 0, columns, 0, columns.length); // Skip primary key columns to save space for(int pkCol:columnOrdering) { if (pkCol < n) columns[pkCol] = -1; } return columns; } @Override public DataHash getRowHash(SpliceRuntimeContext spliceRuntimeContext) throws StandardException { columnOrdering = scanInformation.getColumnOrdering(); ExecRow defnRow = getExecRowDefinition(); int [] cols = getDecodingColumns(defnRow.nColumns()); return BareKeyHash.encoder(cols,null); } @Override public List<NodeType> getNodeTypes() { return nodeTypes; } @Override public ExecRow getExecRowDefinition() { return currentTemplate; } @Override public String prettyPrint(int indentLevel) { return "Table"+super.prettyPrint(indentLevel); } @Override protected int getNumMetrics() { return 5; } @Override protected void updateStats(OperationRuntimeStats stats) { if(regionScanner!=null){ TimeView readTimer = regionScanner.getReadTime(); // long bytesRead = regionScanner.getBytesOutput(); stats.addMetric(OperationMetric.LOCAL_SCAN_ROWS,regionScanner.getRowsVisited()); stats.addMetric(OperationMetric.LOCAL_SCAN_BYTES,regionScanner.getBytesVisited()); stats.addMetric(OperationMetric.LOCAL_SCAN_CPU_TIME,readTimer.getCpuTime()); stats.addMetric(OperationMetric.LOCAL_SCAN_USER_TIME,readTimer.getUserTime()); stats.addMetric(OperationMetric.LOCAL_SCAN_WALL_TIME,readTimer.getWallClockTime()); long filtered = regionScanner.getRowsFiltered(); if(filterCount !=null) filtered+= filterCount.getTotal(); stats.addMetric(OperationMetric.FILTERED_ROWS,filtered); } } @Override public ExecRow nextRow(SpliceRuntimeContext spliceRuntimeContext) throws StandardException,IOException { if(timer==null){ timer = spliceRuntimeContext.newTimer(); filterCount = spliceRuntimeContext.newCounter(); } timer.startTiming(); int[] columnOrder = getColumnOrdering(); KeyMarshaller marshaller = getKeyMarshaller(); MultiFieldDecoder keyDecoder = getKeyDecoder(); if(keyValues==null) keyValues = Lists.newArrayListWithExpectedSize(2); FilterStatePacked filter = getSIFilter(); boolean hasRow; do{ keyValues.clear(); hasRow = regionScanner.next(keyValues); if (keyValues.size()<=0) { if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"%s:no more data retrieved from table",tableName); currentRow = null; currentRowLocation = null; } else { currentRow.resetRowArray(); DataValueDescriptor[] fields = currentRow.getRowArray(); if (fields.length != 0) { // Apply predicate to the row key first if (!filterRowKey(spliceRuntimeContext, keyValues.get(0), columnOrder, keyDecoder)||!filterRow(filter)){ filterCount.increment(); continue; } // Decode key data if primary key is accessed if (scanInformation.getAccessedPkColumns() != null && scanInformation.getAccessedPkColumns().getNumBitsSet() > 0) { marshaller.decode(keyValues.get(0), fields, baseColumnMap, keyDecoder, columnOrder, getColumnDVDs()); } }else if(!filterRow(filter)){ //still need to filter rows to deal with transactional issue filterCount.increment(); continue; } setRowLocation(keyValues.get(0)); break; } }while(hasRow); if(!hasRow){ clearCurrentRow(); }else{ setCurrentRow(currentRow); } //measure time if(currentRow==null){ timer.tick(0); stopExecutionTime = System.currentTimeMillis(); }else timer.tick(1); return currentRow; } protected void setRowLocation(KeyValue sampleKv) throws StandardException { if(indexName!=null && currentRow.nColumns() > 0 && currentRow.getColumn(currentRow.nColumns()).getTypeFormatId() == StoredFormatIds.ACCESS_HEAP_ROW_LOCATION_V1_ID){ /* * If indexName !=null, then we are currently scanning an index, * so our RowLocation should point to the main table, and not to the * index (that we're actually scanning) */ currentRowLocation = (RowLocation) currentRow.getColumn(currentRow.nColumns()); } else { slice.set(sampleKv.getBuffer(), sampleKv.getRowOffset(), sampleKv.getRowLength()); currentRowLocation.setValue(slice); } } protected boolean filterRow(FilterStatePacked filter) throws IOException { filter.nextRow(); Iterator<KeyValue> kvIter = keyValues.iterator(); while(kvIter.hasNext()){ KeyValue kv = kvIter.next(); Filter.ReturnCode returnCode = filter.filterKeyValue(kv); switch(returnCode){ case NEXT_COL: case NEXT_ROW: case SEEK_NEXT_USING_HINT: return false; //failed the predicate case SKIP: kvIter.remove(); default: //these are okay--they mean the encoding is good } } return filter.getAccumulator().result() != null && keyValues.size()>0; } @SuppressWarnings("unchecked") private FilterStatePacked getSIFilter() throws IOException, StandardException { if(siFilter==null){ boolean isCountStar = scan.getAttribute(SIConstants.SI_COUNT_STAR)!=null; EntryPredicateFilter epf = decodePredicateFilter(); TransactionId txnId= new TransactionId(this.transactionID); IFilterState iFilterState = HTransactorFactory.getTransactionReadController().newFilterState(null, txnId); ExecRowAccumulator rowAccumulator = ExecRowAccumulator.newAccumulator(epf,false,currentRow, baseColumnMap); HRowAccumulator accumulator = new HRowAccumulator(epf, getRowDecoder(), rowAccumulator, isCountStar); siFilter = new FilterStatePacked((FilterState)iFilterState, accumulator){ // @Override protected Filter.ReturnCode skipRow() { return Filter.ReturnCode.NEXT_COL; } @Override protected Filter.ReturnCode doAccumulate(KeyValue dataKeyValue) throws IOException { if (!accumulator.isFinished() && accumulator.isOfInterest(dataKeyValue)) { if (!accumulator.accumulate(dataKeyValue)) { return Filter.ReturnCode.NEXT_ROW; } return Filter.ReturnCode.INCLUDE; }else return Filter.ReturnCode.INCLUDE; } }; } return siFilter; } private EntryPredicateFilter decodePredicateFilter() throws IOException { return EntryPredicateFilter.fromBytes(scan.getAttribute(SpliceConstants.ENTRY_PREDICATE_LABEL)); } protected boolean filterRowKey(SpliceRuntimeContext spliceRuntimeContext, KeyValue keyValue, int[] columnOrder, MultiFieldDecoder keyDecoder) throws StandardException, IOException { return columnOrder != null && getPredicateFilter(spliceRuntimeContext) != null && EntryPredicateUtils.qualify(predicateFilter, keyValue.getRow(), getColumnDVDs(), columnOrder, keyDecoder); } @Override public String toString() { try { return String.format("TableScanOperation {tableName=%s,isKeyed=%b,resultSetNumber=%s}",tableName,scanInformation.isKeyed(),resultSetNumber); } catch (Exception e) { return String.format("TableScanOperation {tableName=%s,isKeyed=%s,resultSetNumber=%s}", tableName, "UNKNOWN", resultSetNumber); } } @Override public void close() throws StandardException, IOException { if(rowDecoder!=null) rowDecoder.close(); SpliceLogUtils.trace(LOG, "close in TableScan"); beginTime = getCurrentTimeMillis(); if (runTimeStatisticsOn) { // This is where we get the scan properties for a subquery scanProperties = getScanProperties(); startPositionString = printStartPosition(); stopPositionString = printStopPosition(); } if (forUpdate && scanInformation.isKeyed()) { activation.clearIndexScanInfo(); } super.close(); closeTime += getElapsedMillis(beginTime); } public Properties getScanProperties() { if (scanProperties == null) scanProperties = new Properties(); scanProperties.setProperty("numPagesVisited", "0"); scanProperties.setProperty("numRowsVisited", "0"); scanProperties.setProperty("numRowsQualified", "0"); scanProperties.setProperty("numColumnsFetched", "0");//FIXME: need to loop through accessedCols to figure out try { scanProperties.setProperty("columnsFetchedBitSet", ""+scanInformation.getAccessedColumns()); } catch (StandardException e) { SpliceLogUtils.logAndThrowRuntime(LOG,e); } //treeHeight return scanProperties; } @Override public int[] getAccessedNonPkColumns() throws StandardException{ FormatableBitSet accessedNonPkColumns = scanInformation.getAccessedNonPkColumns(); int num = accessedNonPkColumns.getNumBitsSet(); int[] cols = null; if (num > 0) { cols = new int[num]; int pos = 0; for (int i = accessedNonPkColumns.anySetBit(); i != -1; i = accessedNonPkColumns.anySetBit(i)) { cols[pos++] = baseColumnMap[i]; } } return cols; } private class KeyDataHash extends SuppliedDataHash { private int[] keyColumns; private DataValueDescriptor[] kdvds; public KeyDataHash(StandardSupplier<byte[]> supplier, int[] keyColumns, DataValueDescriptor[] kdvds) { super(supplier); this.keyColumns = keyColumns; this.kdvds = kdvds; } @Override public KeyHashDecoder getDecoder() { return new SuppliedKeyHashDecoder(keyColumns, kdvds); } } private class SuppliedKeyHashDecoder implements KeyHashDecoder { private int[] keyColumns; private DataValueDescriptor[] kdvds; MultiFieldDecoder decoder; public SuppliedKeyHashDecoder(int[] keyColumns, DataValueDescriptor[] kdvds) { this.keyColumns = keyColumns; this.kdvds = kdvds; } @Override public void set(byte[] bytes, int hashOffset, int length){ if (decoder == null) decoder = MultiFieldDecoder.create(SpliceDriver.getKryoPool()); decoder.set(bytes, hashOffset, length); } @Override public void decode(ExecRow destination) throws StandardException { unpack(decoder, destination); } private void unpack(MultiFieldDecoder decoder, ExecRow destination) throws StandardException { if (keyColumns == null) return; DataValueDescriptor[] fields = destination.getRowArray(); for (int i = 0; i < keyColumns.length; ++i) { if (keyColumns[i] == -1) { // skip the key columns that are not in the result if(kdvds[i] != null && i!=keyColumns.length-1) DerbyBytesUtil.skip(decoder, kdvds[i]); } else { DataValueDescriptor field = fields[keyColumns[i]]; decodeNext(decoder, field); } } } void decodeNext(MultiFieldDecoder decoder, DataValueDescriptor field) throws StandardException { if(DerbyBytesUtil.isNextFieldNull(decoder, field)){ field.setToNull(); DerbyBytesUtil.skip(decoder, field); }else DerbyBytesUtil.decodeInto(decoder,field); } } }
package coprocessor; import coprocessor.generated.RowCounterProtos; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.coprocessor.Batch; import org.apache.hadoop.hbase.ipc.BlockingRpcCallback; import org.apache.hadoop.hbase.util.Bytes; import util.HBaseHelper; import java.io.IOException; import java.util.Map; // cc EndpointExample Example using the custom row-count endpoint // vv EndpointExample public class EndpointExample { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); TableName tableName = TableName.valueOf("testtable"); Connection connection = ConnectionFactory.createConnection(conf); // ^^ EndpointExample HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); helper.createTable("testtable", "colfam1", "colfam2"); helper.put("testtable", new String[]{"row1", "row2", "row3", "row4", "row5"}, new String[]{"colfam1", "colfam2"}, new String[]{"qual1", "qual1"}, new long[]{1, 2}, new String[]{"val1", "val2"}); System.out.println("Before endpoint call..."); helper.dump("testtable", new String[]{"row1", "row2", "row3", "row4", "row5"}, null, null); Admin admin = connection.getAdmin(); try { admin.split(tableName, Bytes.toBytes("row3")); } catch (IOException e) { e.printStackTrace(); } // wait for the split to be done while (admin.getTableRegions(tableName).size() < 2) try { Thread.sleep(1000); } catch (InterruptedException e) { } //vv EndpointExample Table table = connection.getTable(tableName); try { final RowCounterProtos.CountRequest request = RowCounterProtos.CountRequest.getDefaultInstance(); Map<byte[], Long> results = table.coprocessorService( RowCounterProtos.RowCountService.class, // co EndpointExample-1-ClassName Define the protocol interface being invoked. null, null, // co EndpointExample-2-Rows Set start and end row key to "null" to count all rows. new Batch.Call<RowCounterProtos.RowCountService, Long>() { // co EndpointExample-3-Batch Create an anonymous class to be sent to all region servers. public Long call(RowCounterProtos.RowCountService counter) throws IOException { BlockingRpcCallback<RowCounterProtos.CountResponse> rpcCallback = new BlockingRpcCallback<RowCounterProtos.CountResponse>(); counter.getRowCount(null, request, rpcCallback); // co EndpointExample-4-Call The call() method is executing the endpoint functions. RowCounterProtos.CountResponse response = rpcCallback.get(); return response.hasCount() ? response.getCount() : 0; } } ); long total = 0; for (Map.Entry<byte[], Long> entry : results.entrySet()) { // co EndpointExample-5-Print Iterate over the returned map, containing the result for each region separately. total += entry.getValue().longValue(); System.out.println("Region: " + Bytes.toString(entry.getKey()) + ", Count: " + entry.getValue()); } System.out.println("Total Count: " + total); } catch (Throwable throwable) { throwable.printStackTrace(); } } } // ^^ EndpointExample
package com.splicemachine.derby.impl.sql.execute.operations; import com.splicemachine.constants.SpliceConstants; import com.splicemachine.constants.bytes.BytesUtil; import com.splicemachine.derby.hbase.SpliceDriver; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext; import com.splicemachine.derby.iapi.sql.execute.SpliceRuntimeContext; import com.splicemachine.derby.iapi.storage.RowProvider; import com.splicemachine.derby.impl.sql.execute.LazyDataValueFactory; import com.splicemachine.derby.impl.storage.ClientScanProvider; import com.splicemachine.utils.ByteSlice; import com.splicemachine.derby.metrics.OperationMetric; import com.splicemachine.derby.metrics.OperationRuntimeStats; import com.splicemachine.derby.utils.DerbyBytesUtil; import com.splicemachine.derby.utils.SpliceUtils; import com.splicemachine.derby.utils.StandardSupplier; import com.splicemachine.derby.utils.marshall.*; import com.splicemachine.encoding.MultiFieldDecoder; import com.splicemachine.stats.TimeView; import com.splicemachine.storage.EntryDecoder; import com.splicemachine.storage.EntryPredicateFilter; import com.splicemachine.storage.Predicate; import com.splicemachine.utils.IntArrays; import com.splicemachine.utils.SpliceLogUtils; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.io.FormatableBitSet; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.loader.GeneratedMethod; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.execute.ExecRow; import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.types.RowLocation; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; public class TableScanOperation extends ScanOperation { private static final long serialVersionUID = 3l; protected static Logger LOG = Logger.getLogger(TableScanOperation.class); protected static List<NodeType> nodeTypes; protected int indexColItem; public String userSuppliedOptimizerOverrides; public int rowsPerRead; protected boolean runTimeStatisticsOn; private Properties scanProperties; public String startPositionString; public String stopPositionString; public ByteSlice slice; private EntryPredicateFilter predicateFilter; private boolean cachedPredicateFilter = false; static { nodeTypes = Arrays.asList(NodeType.MAP,NodeType.SCAN); } private EntryDecoder rowDecoder; private MultiFieldDecoder keyDecoder; private KeyMarshaller keyMarshaller; private int[] baseColumnMap; private DataValueDescriptor[] kdvds; public TableScanOperation() { super(); } public TableScanOperation(ScanInformation scanInformation, OperationInformation operationInformation, int lockMode, int isolationLevel) throws StandardException { super(scanInformation, operationInformation, lockMode, isolationLevel); } @SuppressWarnings("UnusedParameters") public TableScanOperation(long conglomId, StaticCompiledOpenConglomInfo scoci, Activation activation, GeneratedMethod resultRowAllocator, int resultSetNumber, GeneratedMethod startKeyGetter, int startSearchOperator, GeneratedMethod stopKeyGetter, int stopSearchOperator, boolean sameStartStopPosition, String qualifiersField, String tableName, String userSuppliedOptimizerOverrides, String indexName, boolean isConstraint, boolean forUpdate, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel, int rowsPerRead, boolean oneRowScan, double optimizerEstimatedRowCount, double optimizerEstimatedCost) throws StandardException { super(conglomId, activation, resultSetNumber, startKeyGetter, startSearchOperator, stopKeyGetter, stopSearchOperator, sameStartStopPosition, qualifiersField, resultRowAllocator, lockMode, tableLocked, isolationLevel, colRefItem, optimizerEstimatedRowCount, optimizerEstimatedCost); SpliceLogUtils.trace(LOG, "instantiated for tablename %s or indexName %s with conglomerateID %d", tableName, indexName, conglomId); this.forUpdate = forUpdate; this.isConstraint = isConstraint; this.rowsPerRead = rowsPerRead; this.tableName = Long.toString(scanInformation.getConglomerateId()); this.indexColItem = indexColItem; this.indexName = indexName; runTimeStatisticsOn = operationInformation.isRuntimeStatisticsEnabled(); if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG, "statisticsTimingOn=%s,isTopResultSet=%s,runTimeStatisticsOn%s",statisticsTimingOn,isTopResultSet,runTimeStatisticsOn); init(SpliceOperationContext.newContext(activation)); recordConstructorTime(); } @Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { super.readExternal(in); tableName = in.readUTF(); indexColItem = in.readInt(); if(in.readBoolean()) indexName = in.readUTF(); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeUTF(tableName); out.writeInt(indexColItem); out.writeBoolean(indexName != null); if(indexName!=null) out.writeUTF(indexName); } @Override public void init(SpliceOperationContext context) throws StandardException{ super.init(context); this.baseColumnMap = operationInformation.getBaseColumnMap(); this.slice = ByteSlice.empty(); this.startExecutionTime = System.currentTimeMillis(); } @Override public List<SpliceOperation> getSubOperations() { return Collections.emptyList(); } @Override public RowProvider getMapRowProvider(SpliceOperation top,PairDecoder decoder, SpliceRuntimeContext spliceRuntimeContext) throws StandardException { SpliceLogUtils.trace(LOG, "getMapRowProvider"); beginTime = System.currentTimeMillis(); Scan scan = buildScan(spliceRuntimeContext); SpliceUtils.setInstructions(scan, activation, top,spliceRuntimeContext); ClientScanProvider provider = new ClientScanProvider("tableScan",Bytes.toBytes(tableName),scan, decoder,spliceRuntimeContext); nextTime += System.currentTimeMillis() - beginTime; return provider; } @Override public RowProvider getReduceRowProvider(SpliceOperation top, PairDecoder decoder, SpliceRuntimeContext spliceRuntimeContext) throws StandardException { return getMapRowProvider(top, decoder, spliceRuntimeContext); } @Override public KeyEncoder getKeyEncoder(SpliceRuntimeContext spliceRuntimeContext) throws StandardException { /*FormatableBitSet accessedPkCols = scanInformation.getAccessedPkColumns(); int size = accessedPkCols.getNumBitsSet();*/ columnOrdering = scanInformation.getColumnOrdering(); int[] keyColumns = new int[columnOrdering.length]; for (int i = 0; i < keyColumns.length; ++i) { keyColumns[i] = baseColumnMap[columnOrdering[i]]; } /* * Table Scans only use a key encoder when encoding to SpliceOperationRegionScanner, * in which case, the KeyEncoder should be either the row location of the last emitted * row, or a random field (if no row location is specified). */ DataHash hash = new KeyDataHash(new StandardSupplier<byte[]>() { @Override public byte[] get() throws StandardException { if(currentRowLocation!=null) return currentRowLocation.getBytes(); return SpliceDriver.driver().getUUIDGenerator().nextUUIDBytes(); } }, keyColumns, scanInformation.getKeyColumnDVDs()); return new KeyEncoder(NoOpPrefix.INSTANCE,hash,NoOpPostfix.INSTANCE); /*HashPrefix prefix; DataHash dataHash; KeyPostfix postfix = NoOpPostfix.INSTANCE; FormatableBitSet accessedPkCols = scanInformation.getAccessedPkColumns(); int size = accessedPkCols.getNumBitsSet(); columnOrdering = scanInformation.getColumnOrdering(); if(size == 0){ prefix = new SaltedPrefix(operationInformation.getUUIDGenerator()); dataHash = NoOpDataHash.INSTANCE; }else{ int[] keyColumns = new int[columnOrdering.length]; for (int i = 0; i < keyColumns.length; ++i) { keyColumns[i] = baseColumnMap[columnOrdering[i]]; } } return new KeyEncoder(prefix,dataHash,postfix);*/ } private int[] getDecodingColumns(int n) { int[] columns = new int[baseColumnMap.length]; for (int i = 0; i < columns.length; ++i) columns[i] = baseColumnMap[i]; // Skip primary key columns to save space for(int pkCol:columnOrdering) { if (pkCol < n) columns[pkCol] = -1; } return columns; } @Override public DataHash getRowHash(SpliceRuntimeContext spliceRuntimeContext) throws StandardException { columnOrdering = scanInformation.getColumnOrdering(); ExecRow defnRow = getExecRowDefinition(); int [] cols = getDecodingColumns(defnRow.nColumns()); return BareKeyHash.encoder(cols,null); } @Override public List<NodeType> getNodeTypes() { return nodeTypes; } @Override public ExecRow getExecRowDefinition() { return currentTemplate; } @Override public String prettyPrint(int indentLevel) { return "Table"+super.prettyPrint(indentLevel); } @Override protected int getNumMetrics() { return 5; } @Override protected void updateStats(OperationRuntimeStats stats) { if(regionScanner!=null){ TimeView readTimer = regionScanner.getReadTime(); long bytesRead = regionScanner.getBytesOutput(); stats.addMetric(OperationMetric.LOCAL_SCAN_ROWS,regionScanner.getRowsVisited()); stats.addMetric(OperationMetric.LOCAL_SCAN_BYTES,regionScanner.getBytesVisited()); stats.addMetric(OperationMetric.LOCAL_SCAN_CPU_TIME,readTimer.getCpuTime()); stats.addMetric(OperationMetric.LOCAL_SCAN_USER_TIME,readTimer.getUserTime()); stats.addMetric(OperationMetric.LOCAL_SCAN_WALL_TIME,readTimer.getWallClockTime()); stats.addMetric(OperationMetric.FILTERED_ROWS,regionScanner.getRowsFiltered()); } } private EntryPredicateFilter getPredicateFilter(SpliceRuntimeContext spliceRuntimeContext) throws StandardException,IOException{ if (!cachedPredicateFilter) { Scan scan = getScan(spliceRuntimeContext); predicateFilter = EntryPredicateFilter.fromBytes(scan.getAttribute(SpliceConstants.ENTRY_PREDICATE_LABEL)); cachedPredicateFilter = true; } return predicateFilter; } @Override public ExecRow nextRow(SpliceRuntimeContext spliceRuntimeContext) throws StandardException,IOException { if(timer==null) timer = spliceRuntimeContext.newTimer(); timer.startTiming(); KeyValue keyValue = null; do{ keyValue = regionScanner.next(); if (keyValue == null) { if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"%s:no more data retrieved from table",tableName); currentRow = null; currentRowLocation = null; } else { if(rowDecoder==null) rowDecoder = new EntryDecoder(SpliceDriver.getKryoPool()); currentRow.resetRowArray(); DataValueDescriptor[] fields = currentRow.getRowArray(); if (fields.length != 0) { // Apply predicate to the row key first if (getColumnOrdering() != null && getPredicateFilter(spliceRuntimeContext) != null) { boolean passed = filterRow(keyValue.getRow()); if (!passed) continue; } // Decode row data RowMarshaller.sparsePacked().decode(keyValue,fields,baseColumnMap,rowDecoder); // Decode key data if primary key is accessed if (scanInformation.getAccessedPkColumns() != null && scanInformation.getAccessedPkColumns().getNumBitsSet() > 0) { getKeyMarshaller().decode(keyValue, fields, baseColumnMap, getKeyDecoder(), columnOrdering, kdvds); } } if(indexName!=null && currentRow.nColumns() > 0 && currentRow.getColumn(currentRow.nColumns()).getTypeFormatId() == StoredFormatIds.ACCESS_HEAP_ROW_LOCATION_V1_ID){ /* * If indexName !=null, then we are currently scanning an index, * so our RowLocation should point to the main table, and not to the * index (that we're actually scanning) */ currentRowLocation = (RowLocation) currentRow.getColumn(currentRow.nColumns()); } else { slice.set(keyValue.getBuffer(), keyValue.getRowOffset(), keyValue.getRowLength()); currentRowLocation.setValue(slice); } break; } } while (keyValue != null); setCurrentRow(currentRow); //measure time if(currentRow==null){ timer.tick(0); stopExecutionTime = System.currentTimeMillis(); }else timer.tick(1); return currentRow; } private boolean filterRow(byte[] data) throws StandardException{ getColumnDVDs(); MultiFieldDecoder keyDecoder = getKeyDecoder(); keyDecoder.set(data); for (int i = 0; i < kdvds.length; ++i) { int offset = keyDecoder.offset(); DerbyBytesUtil.skip(keyDecoder,kdvds[i]); int size = keyDecoder.offset()-1-offset; Object[] buffer = predicateFilter.getValuePredicates().buffer; int ibuffer = predicateFilter.getValuePredicates().size(); for (int j =0; j<ibuffer; j++) { if(((Predicate)buffer[j]).applies(i) && !((Predicate)buffer[j]).match(i,data,offset,size)) return false; } } return true; } private MultiFieldDecoder getKeyDecoder() { if (keyDecoder == null) keyDecoder = MultiFieldDecoder.create(SpliceDriver.getKryoPool()); return keyDecoder; } private KeyMarshaller getKeyMarshaller () { if (keyMarshaller == null) keyMarshaller = new KeyMarshaller(); return keyMarshaller; } @Override public String toString() { try { return String.format("TableScanOperation {tableName=%s,isKeyed=%b,resultSetNumber=%s}",tableName,scanInformation.isKeyed(),resultSetNumber); } catch (Exception e) { return String.format("TableScanOperation {tableName=%s,isKeyed=%s,resultSetNumber=%s}", tableName, "UNKNOWN", resultSetNumber); } } @Override public void close() throws StandardException, IOException { if(rowDecoder!=null) rowDecoder.close(); SpliceLogUtils.trace(LOG, "close in TableScan"); beginTime = getCurrentTimeMillis(); if (runTimeStatisticsOn) { // This is where we get the scan properties for a subquery scanProperties = getScanProperties(); startPositionString = printStartPosition(); stopPositionString = printStopPosition(); } if (forUpdate && scanInformation.isKeyed()) { activation.clearIndexScanInfo(); } super.close(); closeTime += getElapsedMillis(beginTime); } public Properties getScanProperties() { if (scanProperties == null) scanProperties = new Properties(); scanProperties.setProperty("numPagesVisited", "0"); scanProperties.setProperty("numRowsVisited", "0"); scanProperties.setProperty("numRowsQualified", "0"); scanProperties.setProperty("numColumnsFetched", "0");//FIXME: need to loop through accessedCols to figure out try { scanProperties.setProperty("columnsFetchedBitSet", ""+scanInformation.getAccessedColumns()); } catch (StandardException e) { SpliceLogUtils.logAndThrowRuntime(LOG,e); } //treeHeight return scanProperties; } protected int[] getColumnOrdering() throws StandardException{ if (columnOrdering == null) { columnOrdering = scanInformation.getColumnOrdering(); } return columnOrdering; } @Override public int[] getAccessedNonPkColumns() throws StandardException{ FormatableBitSet accessedNonPkColumns = scanInformation.getAccessedNonPkColumns(); int num = accessedNonPkColumns.getNumBitsSet(); int[] cols = null; if (num > 0) { cols = new int[num]; int pos = 0; for (int i = accessedNonPkColumns.anySetBit(); i != -1; i = accessedNonPkColumns.anySetBit(i)) { cols[pos++] = baseColumnMap[i]; } } return cols; } private void getColumnDVDs() throws StandardException{ if (kdvds == null) { int[] columnOrdering = getColumnOrdering(); int[] format_ids = scanInformation.getConglomerate().getFormat_ids(); kdvds = new DataValueDescriptor[columnOrdering.length]; for (int i = 0; i < columnOrdering.length; ++i) { kdvds[i] = LazyDataValueFactory.getLazyNull(format_ids[columnOrdering[i]]); } } } private class KeyDataHash extends SuppliedDataHash { private int[] keyColumns; private DataValueDescriptor[] kdvds; public KeyDataHash(StandardSupplier<byte[]> supplier, int[] keyColumns, DataValueDescriptor[] kdvds) { super(supplier); this.keyColumns = keyColumns; this.kdvds = kdvds; } @Override public KeyHashDecoder getDecoder() { return new SuppliedKeyHashDecoder(keyColumns, kdvds); } } private class SuppliedKeyHashDecoder implements KeyHashDecoder { private int[] keyColumns; private DataValueDescriptor[] kdvds; MultiFieldDecoder decoder; public SuppliedKeyHashDecoder(int[] keyColumns, DataValueDescriptor[] kdvds) { this.keyColumns = keyColumns; this.kdvds = kdvds; } @Override public void set(byte[] bytes, int hashOffset, int length){ if (decoder == null) decoder = MultiFieldDecoder.create(SpliceDriver.getKryoPool()); decoder.set(bytes, hashOffset, length); } @Override public void decode(ExecRow destination) throws StandardException { unpack(decoder, destination); } private void unpack(MultiFieldDecoder decoder, ExecRow destination) throws StandardException { DataValueDescriptor[] fields = destination.getRowArray(); for (int i = 0; i < keyColumns.length; ++i) { if (keyColumns[i] == -1) { // skip the key columns that are not in the result DerbyBytesUtil.skip(decoder, kdvds[i]); } else { DataValueDescriptor field = fields[keyColumns[i]]; decodeNext(decoder, field); } } } void decodeNext(MultiFieldDecoder decoder, DataValueDescriptor field) throws StandardException { if(DerbyBytesUtil.isNextFieldNull(decoder, field)){ field.setToNull(); DerbyBytesUtil.skip(decoder, field); }else DerbyBytesUtil.decodeInto(decoder,field); } } }
package com.splicemachine.derby.impl.sql.execute.operations; import com.google.common.collect.Lists; import com.splicemachine.constants.SIConstants; import com.splicemachine.constants.SpliceConstants; import com.splicemachine.derby.hbase.SpliceDriver; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext; import com.splicemachine.derby.iapi.sql.execute.SpliceRuntimeContext; import com.splicemachine.derby.iapi.storage.RowProvider; import com.splicemachine.derby.impl.storage.ClientScanProvider; import com.splicemachine.derby.impl.store.ExecRowAccumulator; import com.splicemachine.derby.metrics.OperationMetric; import com.splicemachine.derby.metrics.OperationRuntimeStats; import com.splicemachine.derby.utils.DerbyBytesUtil; import com.splicemachine.derby.utils.EntryPredicateUtils; import com.splicemachine.derby.utils.SpliceUtils; import com.splicemachine.derby.utils.StandardSupplier; import com.splicemachine.derby.utils.marshall.*; import com.splicemachine.encoding.MultiFieldDecoder; import com.splicemachine.si.api.HTransactorFactory; import com.splicemachine.si.data.hbase.HRowAccumulator; import com.splicemachine.si.impl.FilterState; import com.splicemachine.si.impl.FilterStatePacked; import com.splicemachine.si.impl.IFilterState; import com.splicemachine.si.impl.TransactionId; import com.splicemachine.stats.Counter; import com.splicemachine.stats.TimeView; import com.splicemachine.storage.EntryPredicateFilter; import com.splicemachine.utils.ByteSlice; import com.splicemachine.utils.SpliceLogUtils; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.io.FormatableBitSet; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.loader.GeneratedMethod; import org.apache.derby.iapi.sql.Activation; import org.apache.derby.iapi.sql.execute.ExecRow; import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.types.RowLocation; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; public class TableScanOperation extends ScanOperation { private static final long serialVersionUID = 3l; protected static Logger LOG = Logger.getLogger(TableScanOperation.class); protected static List<NodeType> nodeTypes; protected int indexColItem; public String userSuppliedOptimizerOverrides; public int rowsPerRead; protected boolean runTimeStatisticsOn; private Properties scanProperties; public String startPositionString; public String stopPositionString; public ByteSlice slice; static { nodeTypes = Arrays.asList(NodeType.MAP,NodeType.SCAN); } private int[] baseColumnMap; private int[] keyColumns; private List<KeyValue> keyValues; private FilterStatePacked siFilter; private Scan scan; private Counter filterCount; public TableScanOperation() { super(); } public TableScanOperation(ScanInformation scanInformation, OperationInformation operationInformation, int lockMode, int isolationLevel) throws StandardException { super(scanInformation, operationInformation, lockMode, isolationLevel); } @SuppressWarnings("UnusedParameters") public TableScanOperation(long conglomId, StaticCompiledOpenConglomInfo scoci, Activation activation, GeneratedMethod resultRowAllocator, int resultSetNumber, GeneratedMethod startKeyGetter, int startSearchOperator, GeneratedMethod stopKeyGetter, int stopSearchOperator, boolean sameStartStopPosition, String qualifiersField, String tableName, String userSuppliedOptimizerOverrides, String indexName, boolean isConstraint, boolean forUpdate, int colRefItem, int indexColItem, int lockMode, boolean tableLocked, int isolationLevel, int rowsPerRead, boolean oneRowScan, double optimizerEstimatedRowCount, double optimizerEstimatedCost) throws StandardException { super(conglomId, activation, resultSetNumber, startKeyGetter, startSearchOperator, stopKeyGetter, stopSearchOperator, sameStartStopPosition, qualifiersField, resultRowAllocator, lockMode, tableLocked, isolationLevel, colRefItem, optimizerEstimatedRowCount, optimizerEstimatedCost); SpliceLogUtils.trace(LOG, "instantiated for tablename %s or indexName %s with conglomerateID %d", tableName, indexName, conglomId); this.forUpdate = forUpdate; this.isConstraint = isConstraint; this.rowsPerRead = rowsPerRead; this.tableName = Long.toString(scanInformation.getConglomerateId()); this.indexColItem = indexColItem; this.indexName = indexName; runTimeStatisticsOn = operationInformation.isRuntimeStatisticsEnabled(); if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG, "statisticsTimingOn=%s,isTopResultSet=%s,runTimeStatisticsOn%s",statisticsTimingOn,isTopResultSet,runTimeStatisticsOn); init(SpliceOperationContext.newContext(activation)); recordConstructorTime(); } @Override public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException { super.readExternal(in); tableName = in.readUTF(); indexColItem = in.readInt(); if(in.readBoolean()) indexName = in.readUTF(); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeUTF(tableName); out.writeInt(indexColItem); out.writeBoolean(indexName != null); if(indexName!=null) out.writeUTF(indexName); } @Override public void init(SpliceOperationContext context) throws StandardException{ super.init(context); this.baseColumnMap = operationInformation.getBaseColumnMap(); this.slice = ByteSlice.empty(); this.startExecutionTime = System.currentTimeMillis(); this.scan = context.getScan(); } @Override public List<SpliceOperation> getSubOperations() { return Collections.emptyList(); } @Override public RowProvider getMapRowProvider(SpliceOperation top,PairDecoder decoder, SpliceRuntimeContext spliceRuntimeContext) throws StandardException { SpliceLogUtils.trace(LOG, "getMapRowProvider"); beginTime = System.currentTimeMillis(); Scan scan = getNonSIScan(spliceRuntimeContext); SpliceUtils.setInstructions(scan, activation, top,spliceRuntimeContext); ClientScanProvider provider = new ClientScanProvider("tableScan",Bytes.toBytes(tableName),scan, decoder,spliceRuntimeContext); nextTime += System.currentTimeMillis() - beginTime; return provider; } protected Scan getNonSIScan(SpliceRuntimeContext spliceRuntimeContext) { /* * Intended to get a scan which does NOT set up SI underneath us (since * we are doing it ourselves). */ Scan scan = buildScan(spliceRuntimeContext); deSiify(scan); return scan; } protected void deSiify(Scan scan) { /* * Remove SI-specific behaviors from the scan, so that we can handle it ourselves correctly. */ //exclude this from SI treatment, since we're doing it internally scan.setAttribute(SIConstants.SI_NEEDED,null); scan.setMaxVersions(); Map<byte[], NavigableSet<byte[]>> familyMap = scan.getFamilyMap(); if(familyMap!=null){ NavigableSet<byte[]> bytes = familyMap.get(SpliceConstants.DEFAULT_FAMILY_BYTES); if(bytes!=null) bytes.clear(); //make sure we get all columns } } @Override public RowProvider getReduceRowProvider(SpliceOperation top, PairDecoder decoder, SpliceRuntimeContext spliceRuntimeContext, boolean returnDefaultValue) throws StandardException { return getMapRowProvider(top, decoder, spliceRuntimeContext); } @Override public KeyEncoder getKeyEncoder(SpliceRuntimeContext spliceRuntimeContext) throws StandardException { columnOrdering = scanInformation.getColumnOrdering(); if(columnOrdering != null && columnOrdering.length > 0) { getKeyColumns(); } /* * Table Scans only use a key encoder when encoding to SpliceOperationRegionScanner, * in which case, the KeyEncoder should be either the row location of the last emitted * row, or a random field (if no row location is specified). */ DataHash hash = new KeyDataHash(new StandardSupplier<byte[]>() { @Override public byte[] get() throws StandardException { if(currentRowLocation!=null) return currentRowLocation.getBytes(); return SpliceDriver.driver().getUUIDGenerator().nextUUIDBytes(); } }, keyColumns, scanInformation.getKeyColumnDVDs()); return new KeyEncoder(NoOpPrefix.INSTANCE,hash,NoOpPostfix.INSTANCE); } protected int[] getKeyColumns() throws StandardException { if(keyColumns==null){ columnOrdering = scanInformation.getColumnOrdering(); keyColumns = new int[columnOrdering.length]; for (int i = 0; i < keyColumns.length; ++i) { keyColumns[i] = -1; } for (int i = 0; i < keyColumns.length && columnOrdering[i] < baseColumnMap.length; ++i) { keyColumns[i] = baseColumnMap[columnOrdering[i]]; } } return keyColumns; } private int[] getDecodingColumns(int n) { int[] columns = new int[baseColumnMap.length]; System.arraycopy(baseColumnMap, 0, columns, 0, columns.length); // Skip primary key columns to save space for(int pkCol:columnOrdering) { if (pkCol < n) columns[pkCol] = -1; } return columns; } @Override public DataHash getRowHash(SpliceRuntimeContext spliceRuntimeContext) throws StandardException { columnOrdering = scanInformation.getColumnOrdering(); ExecRow defnRow = getExecRowDefinition(); int [] cols = getDecodingColumns(defnRow.nColumns()); return BareKeyHash.encoder(cols,null); } @Override public List<NodeType> getNodeTypes() { return nodeTypes; } @Override public ExecRow getExecRowDefinition() { return currentTemplate; } @Override public String prettyPrint(int indentLevel) { return "Table"+super.prettyPrint(indentLevel); } @Override protected int getNumMetrics() { return 5; } @Override protected void updateStats(OperationRuntimeStats stats) { if(regionScanner!=null){ TimeView readTimer = regionScanner.getReadTime(); // long bytesRead = regionScanner.getBytesOutput(); stats.addMetric(OperationMetric.LOCAL_SCAN_ROWS,regionScanner.getRowsVisited()); stats.addMetric(OperationMetric.LOCAL_SCAN_BYTES,regionScanner.getBytesVisited()); stats.addMetric(OperationMetric.LOCAL_SCAN_CPU_TIME,readTimer.getCpuTime()); stats.addMetric(OperationMetric.LOCAL_SCAN_USER_TIME,readTimer.getUserTime()); stats.addMetric(OperationMetric.LOCAL_SCAN_WALL_TIME,readTimer.getWallClockTime()); long filtered = regionScanner.getRowsFiltered(); if(filterCount !=null) filtered+= filterCount.getTotal(); stats.addMetric(OperationMetric.FILTERED_ROWS,filtered); } } @Override public ExecRow nextRow(SpliceRuntimeContext spliceRuntimeContext) throws StandardException,IOException { if(timer==null){ timer = spliceRuntimeContext.newTimer(); filterCount = spliceRuntimeContext.newCounter(); } timer.startTiming(); int[] columnOrder = getColumnOrdering(); KeyMarshaller marshaller = getKeyMarshaller(); MultiFieldDecoder keyDecoder = getKeyDecoder(); if(keyValues==null) keyValues = Lists.newArrayListWithExpectedSize(2); FilterStatePacked filter = getSIFilter(); boolean hasRow; do{ keyValues.clear(); hasRow = regionScanner.next(keyValues); if (keyValues.size()<=0) { if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"%s:no more data retrieved from table",tableName); currentRow = null; currentRowLocation = null; } else { currentRow.resetRowArray(); DataValueDescriptor[] fields = currentRow.getRowArray(); if (fields.length != 0) { // Apply predicate to the row key first if (!filterRowKey(spliceRuntimeContext, keyValues.get(0), columnOrder, keyDecoder)||!filterRow(filter)){ filterCount.increment(); continue; } // Decode key data if primary key is accessed if (scanInformation.getAccessedPkColumns() != null && scanInformation.getAccessedPkColumns().getNumBitsSet() > 0) { marshaller.decode(keyValues.get(0), fields, baseColumnMap, keyDecoder, columnOrder, getColumnDVDs()); } } setRowLocation(keyValues.get(0)); break; } }while(hasRow); if(!hasRow){ clearCurrentRow(); }else{ setCurrentRow(currentRow); } //measure time if(currentRow==null){ timer.tick(0); stopExecutionTime = System.currentTimeMillis(); }else timer.tick(1); return currentRow; } protected void setRowLocation(KeyValue sampleKv) throws StandardException { if(indexName!=null && currentRow.nColumns() > 0 && currentRow.getColumn(currentRow.nColumns()).getTypeFormatId() == StoredFormatIds.ACCESS_HEAP_ROW_LOCATION_V1_ID){ /* * If indexName !=null, then we are currently scanning an index, * so our RowLocation should point to the main table, and not to the * index (that we're actually scanning) */ currentRowLocation = (RowLocation) currentRow.getColumn(currentRow.nColumns()); } else { slice.set(sampleKv.getBuffer(), sampleKv.getRowOffset(), sampleKv.getRowLength()); currentRowLocation.setValue(slice); } } protected boolean filterRow(FilterStatePacked filter) throws IOException { filter.nextRow(); Iterator<KeyValue> kvIter = keyValues.iterator(); while(kvIter.hasNext()){ KeyValue kv = kvIter.next(); Filter.ReturnCode returnCode = filter.filterKeyValue(kv); switch(returnCode){ case NEXT_COL: case NEXT_ROW: case SEEK_NEXT_USING_HINT: return false; //failed the predicate case SKIP: kvIter.remove(); default: //these are okay--they mean the encoding is good } } return filter.getAccumulator().result() != null && keyValues.size()>0; } @SuppressWarnings("unchecked") private FilterStatePacked getSIFilter() throws IOException, StandardException { if(siFilter==null){ boolean isCountStar = scan.getAttribute(SIConstants.SI_COUNT_STAR)!=null; EntryPredicateFilter epf = decodePredicateFilter(); TransactionId txnId= new TransactionId(this.transactionID); IFilterState iFilterState = HTransactorFactory.getTransactionReadController().newFilterState(null, txnId); ExecRowAccumulator rowAccumulator = ExecRowAccumulator.newAccumulator(epf,false,currentRow, baseColumnMap); HRowAccumulator accumulator = new HRowAccumulator(epf, getRowDecoder(), rowAccumulator, isCountStar); siFilter = new FilterStatePacked((FilterState)iFilterState, accumulator){ // @Override protected Filter.ReturnCode skipRow() { return Filter.ReturnCode.NEXT_COL; } @Override protected Filter.ReturnCode doAccumulate(KeyValue dataKeyValue) throws IOException { if (!accumulator.isFinished() && accumulator.isOfInterest(dataKeyValue)) { if (!accumulator.accumulate(dataKeyValue)) { return Filter.ReturnCode.NEXT_ROW; } return Filter.ReturnCode.INCLUDE; }else return Filter.ReturnCode.INCLUDE; } }; } return siFilter; } private EntryPredicateFilter decodePredicateFilter() throws IOException { return EntryPredicateFilter.fromBytes(scan.getAttribute(SpliceConstants.ENTRY_PREDICATE_LABEL)); } protected boolean filterRowKey(SpliceRuntimeContext spliceRuntimeContext, KeyValue keyValue, int[] columnOrder, MultiFieldDecoder keyDecoder) throws StandardException, IOException { return columnOrder != null && getPredicateFilter(spliceRuntimeContext) != null && EntryPredicateUtils.qualify(predicateFilter, keyValue.getRow(), getColumnDVDs(), columnOrder, keyDecoder); } @Override public String toString() { try { return String.format("TableScanOperation {tableName=%s,isKeyed=%b,resultSetNumber=%s}",tableName,scanInformation.isKeyed(),resultSetNumber); } catch (Exception e) { return String.format("TableScanOperation {tableName=%s,isKeyed=%s,resultSetNumber=%s}", tableName, "UNKNOWN", resultSetNumber); } } @Override public void close() throws StandardException, IOException { if(rowDecoder!=null) rowDecoder.close(); SpliceLogUtils.trace(LOG, "close in TableScan"); beginTime = getCurrentTimeMillis(); if (runTimeStatisticsOn) { // This is where we get the scan properties for a subquery scanProperties = getScanProperties(); startPositionString = printStartPosition(); stopPositionString = printStopPosition(); } if (forUpdate && scanInformation.isKeyed()) { activation.clearIndexScanInfo(); } super.close(); closeTime += getElapsedMillis(beginTime); } public Properties getScanProperties() { if (scanProperties == null) scanProperties = new Properties(); scanProperties.setProperty("numPagesVisited", "0"); scanProperties.setProperty("numRowsVisited", "0"); scanProperties.setProperty("numRowsQualified", "0"); scanProperties.setProperty("numColumnsFetched", "0");//FIXME: need to loop through accessedCols to figure out try { scanProperties.setProperty("columnsFetchedBitSet", ""+scanInformation.getAccessedColumns()); } catch (StandardException e) { SpliceLogUtils.logAndThrowRuntime(LOG,e); } //treeHeight return scanProperties; } @Override public int[] getAccessedNonPkColumns() throws StandardException{ FormatableBitSet accessedNonPkColumns = scanInformation.getAccessedNonPkColumns(); int num = accessedNonPkColumns.getNumBitsSet(); int[] cols = null; if (num > 0) { cols = new int[num]; int pos = 0; for (int i = accessedNonPkColumns.anySetBit(); i != -1; i = accessedNonPkColumns.anySetBit(i)) { cols[pos++] = baseColumnMap[i]; } } return cols; } private class KeyDataHash extends SuppliedDataHash { private int[] keyColumns; private DataValueDescriptor[] kdvds; public KeyDataHash(StandardSupplier<byte[]> supplier, int[] keyColumns, DataValueDescriptor[] kdvds) { super(supplier); this.keyColumns = keyColumns; this.kdvds = kdvds; } @Override public KeyHashDecoder getDecoder() { return new SuppliedKeyHashDecoder(keyColumns, kdvds); } } private class SuppliedKeyHashDecoder implements KeyHashDecoder { private int[] keyColumns; private DataValueDescriptor[] kdvds; MultiFieldDecoder decoder; public SuppliedKeyHashDecoder(int[] keyColumns, DataValueDescriptor[] kdvds) { this.keyColumns = keyColumns; this.kdvds = kdvds; } @Override public void set(byte[] bytes, int hashOffset, int length){ if (decoder == null) decoder = MultiFieldDecoder.create(SpliceDriver.getKryoPool()); decoder.set(bytes, hashOffset, length); } @Override public void decode(ExecRow destination) throws StandardException { unpack(decoder, destination); } private void unpack(MultiFieldDecoder decoder, ExecRow destination) throws StandardException { if (keyColumns == null) return; DataValueDescriptor[] fields = destination.getRowArray(); for (int i = 0; i < keyColumns.length; ++i) { if (keyColumns[i] == -1) { // skip the key columns that are not in the result if(kdvds[i] != null && i!=keyColumns.length-1) DerbyBytesUtil.skip(decoder, kdvds[i]); } else { DataValueDescriptor field = fields[keyColumns[i]]; decodeNext(decoder, field); } } } void decodeNext(MultiFieldDecoder decoder, DataValueDescriptor field) throws StandardException { if(DerbyBytesUtil.isNextFieldNull(decoder, field)){ field.setToNull(); DerbyBytesUtil.skip(decoder, field); }else DerbyBytesUtil.decodeInto(decoder,field); } } }
package ru.job4j.max; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** *Test Max class. * * @author Kucyh Vasily (mailto:basil135@mail.ru) * @version $Id$ * @since 31.03.2017 */ public class MaxTest { /** * The method returns the second number, because numbers identical. */ @Test public void whenMaxTwoAndTwoThenTwo() { final int expectedValue; final int actualValue; Max max = new Max(); expectedValue = 2; actualValue = max.max(2, 2); assertThat(expectedValue, is(actualValue)); } /** * The method returns the most large number from two numbers, where the second number is large then first. */ @Test public void whenMaxTwoAndFourThenFour() { final int expectedValue; final int actualValue; Max max = new Max(); expectedValue = 4; actualValue = max.max(2, 4); assertThat(expectedValue, is(actualValue)); } /** * The method returns the most large number from two numbers, where the first number is large then second. */ @Test public void whenFourAndTwoThenFour() { final int expectedValue; final int actualValue; Max max = new Max(); expectedValue = 4; actualValue = max.max(4, 2); assertThat(expectedValue, is(actualValue)); } /** * The method return the largest value from three numbers. */ public void whenOneAndTwoAndThreeThenThree() { final int expectedValue; final int actualValue; Max max = new Max(); expectedValue = 3; actualValue = max.max(1, 2, 3); assertThat(expectedValue, is(actualValue)); } }
package io.takari.maven.plugins.configurator; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.util.List; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; // The normal process in Maven does merging of default Mojo configuration with the configuration // provided by the POM, but we need to change the procesing in order to support the namespacing of configuration in the POM // configuraiton. So we take the original configuration, take the POM configuration and take out the configuration that is namespaced to // the Mojo we are executing and create a configuration that looks normal to the standard Maven process. public class MojoConfigurationProcessor { private static PluginDescriptorBuilder pluginDescriptorBuilder = new PluginDescriptorBuilder(); public PlexusConfiguration mojoConfigurationFor(Object mojoInstance, PlexusConfiguration pluginConfigurationFromMaven) throws ComponentConfigurationException { try (InputStream is = mojoInstance.getClass().getResourceAsStream("/META-INF/maven/plugin.xml")) { PluginDescriptor pd = pluginDescriptorBuilder.build(new InputStreamReader(is, "UTF-8")); // closes input stream too String goal = determineGoal(mojoInstance.getClass().getName(), pd); PlexusConfiguration defaultMojoConfiguration = pd.getMojo(goal).getMojoConfiguration(); PlexusConfiguration mojoConfiguration = extractAndMerge(goal, pluginConfigurationFromMaven, defaultMojoConfiguration); return mojoConfiguration; } catch (Exception e) { throw new ComponentConfigurationException(e); } } /** * Extract the Mojo specific configuration from the incoming plugin configuration from Maven by looking at an enclosing element with the goal name. Use this and merge it with the default Mojo * configuration and use this to apply values to the Mojo. * * @param goal * @param pluginConfigurationFromMaven * @param defaultMojoConfiguration * @return * @throws ComponentConfigurationException */ PlexusConfiguration extractAndMerge(String goal, PlexusConfiguration pluginConfigurationFromMaven, PlexusConfiguration defaultMojoConfiguration) throws ComponentConfigurationException { // We need to extract the specific configuration for this goal out of the POM configuration PlexusConfiguration mojoConfigurationFromPom = new XmlPlexusConfiguration("configuration"); for (PlexusConfiguration element : pluginConfigurationFromMaven.getChildren()) { if (element.getName().equals(goal)) { for (PlexusConfiguration goalConfigurationElements : element.getChildren()) { mojoConfigurationFromPom.addChild(goalConfigurationElements); } } } return new XmlPlexusConfiguration(Xpp3Dom.mergeXpp3Dom(convert(mojoConfigurationFromPom), convert(defaultMojoConfiguration))); } PlexusConfiguration mergePlexusConfiguration(PlexusConfiguration dominant, PlexusConfiguration recessive) throws ComponentConfigurationException { return new XmlPlexusConfiguration(Xpp3Dom.mergeXpp3Dom(convert(dominant), convert(recessive))); } Xpp3Dom convert(PlexusConfiguration c) throws ComponentConfigurationException { try { return Xpp3DomBuilder.build(new StringReader(c.toString())); } catch (Exception e) { throw new ComponentConfigurationException("Failure converting PlexusConfiguration to Xpp3Dom.", e); } } String determineGoal(String className, PluginDescriptor pluginDescriptor) throws ComponentConfigurationException { List<MojoDescriptor> mojos = pluginDescriptor.getMojos(); for (MojoDescriptor mojo : mojos) { if (className.equals(mojo.getImplementation())) { return mojo.getGoal(); } } throw new ComponentConfigurationException("Cannot find the goal implementation with " + className); } }
package de.interseroh.tmb.user.client; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import de.interseroh.tmb.user.client.domain.UserInfoClient; import org.fusesource.restygwt.client.*; import org.gwtbootstrap3.client.ui.AnchorButton; import org.gwtbootstrap3.client.ui.base.ComplexWidget; import org.gwtbootstrap3.client.ui.constants.ButtonType; import java.util.logging.Level; import java.util.logging.Logger; public class UserInformationServiceImpl implements UserInformationService { public final String oidConnectGatewayLocation; public final String userInfoUrl; public final String cookiePath; public final String logoutUrl; public final String ssoLogoutUrl; public final static String USER_CLASS = "userLogin"; private static final Logger logger = Logger .getLogger(UserInformationServiceImpl.class.getName()); public UserInformationServiceImpl(String gatewayLocation, String ssoLogoutUrl, String userInfoUrl, String cookiePath, String logoutUrl) { oidConnectGatewayLocation =gatewayLocation; this.ssoLogoutUrl = ssoLogoutUrl; this.userInfoUrl = userInfoUrl; this.cookiePath = cookiePath; this.logoutUrl = logoutUrl; } public UserInformationServiceImpl(UserInformationServiceImpl dolly){ this.oidConnectGatewayLocation = dolly.oidConnectGatewayLocation; this.userInfoUrl = dolly.userInfoUrl; this.cookiePath = dolly.cookiePath; this.logoutUrl = dolly.logoutUrl; this.ssoLogoutUrl = dolly.ssoLogoutUrl; } @Override public ComplexWidget createLoginButton() { AnchorButton loginButton = new AnchorButton(ButtonType.fromStyleName("fa-user")); loginButton.getElement().addClassName(USER_CLASS); loginButton.setHref(oidConnectGatewayLocation); loginButton.setId(ID_LOGIN_BUTTON); return loginButton; } @Override public ComplexWidget createLogoutButton(final Callback logoutCallback) { final UserInformationServiceImpl me = this; AnchorButton logoutButton = new AnchorButton(ButtonType.fromStyleName("fa-user")); logoutButton.getElement().addClassName(USER_CLASS); logoutButton.setId(ID_LOGOUT_BUTTON); logoutButton.addClickHandler(new ClickHandler() { final UserInformationServiceImpl userService = new UserInformationServiceImpl(me); @Override public void onClick(ClickEvent event) { userService.logger.info("BEGIN INITIATING PERFORM LOGOUT"); userService.performLogout(logoutCallback); userService.logger.info("DONE INITIATING PERFORM LOGOUT"); } }); return logoutButton; } @Override public boolean performLogout(final Callback logoutCallback) { logger.info("BEGIN PERFOMING LOGOUT"); try { // In order to destory all session info, we are stacking the callbacks like a matryoshka. // last step : terminate session and navigate to logout url final LogoutTask methodObject3= new LogoutTask(new UserInformationServiceImpl(this)) { @Override public void run() { logger.info("BEGIN COOKIE REMOVAL"); LogoutCallback callback = new LogoutCallback(new UserInformationServiceImpl(userService), logoutCallback) { @Override public void onFailure(Object reason) { userService.logger.info("A FAILURE HAS HAPPENED. REASON: "+(reason != null? reason.toString():"NULL")); logoutCallback.onFailure(reason); } @Override public void onSuccess(Object result) { } }; userService.removeCookies(callback); logger.info("END COOKIE REMOVAL"); if (logoutUrl != null && !logoutUrl.trim().isEmpty()) { if (ssoLogoutUrl != null && !ssoLogoutUrl.isEmpty()) { String logoutHook = ssoLogoutUrl + "/endsession?post_logout_redirect_uri=" + logoutUrl; userService.logger.info("MOVING TO " + logoutHook); Window.Location.replace(logoutHook); } else { userService.logger.info("MOVING TO " + logoutUrl); Window.Location.replace(logoutUrl); } } logoutCallback.onSuccess(null); } }; // second step : end gateway session final LogoutTask methodObject2 = new LogoutTask(new UserInformationServiceImpl(this)) { @Override public void run() { logger.info("BEGIN GW SHALLOW LOGOUT"); final UserInfoClient userInfoClient = userService.getUserInfoClient(); userInfoClient.logout(new MethodCallback<Void>() { @Override public void onFailure(Method method, Throwable exception) { logger.warning("GW LOGOUT FAILED " + exception.getMessage()); methodObject3.run(); } @Override public void onSuccess(Method method, Void response) { logger.info("GW LOGOUT SUCCESSFUL"); methodObject3.run(); } }); logger.info("DONE GW SHALLOW LOGOUT"); } ; }; // first step : end sso session final LogoutTask methodObject1 = new LogoutTask(new UserInformationServiceImpl(this)) { @Override public void run() { logger.info("BEGIN DEEP LOGOUT"); logger.log(Level.INFO, () -> "Deep Logout : logoutURL = " + logoutUrl); final UserInfoClient userInfoClient = userService.getUserInfoClient(); logger.log(Level.INFO, () -> "UserInfoClient: LoggedIn?" + userService.isLoggedIn()); userInfoClient.deepLogout(logoutUrl, new MethodCallback<Void>() { @Override public void onFailure(Method method, Throwable exception) { logger.warning("DEEP LOGOUT FAILED " + exception.getMessage()); methodObject2.run(); } @Override public void onSuccess(Method method, Void response) { logger.info("DEEP LOGOUT SUCCESSFUL"); methodObject2.run(); } }); logger.info("DONE DEEP LOGOUT"); } }; logger.info("LAUNCHING: PERFORM LOGOUT"); methodObject1.run(); logger.fine("DONE: PERFOMING LOGOUT"); }catch (Exception e){ logger.warning("SOMETHING SCREWED UP ON LOGOUT :"+e.getMessage()); return false; } return true; } @Override public void getUserInfo(MethodCallback<UserInfoResponse> uiCallback) { logger.info("Get userInfo begins..."); UserInfoClient client = getUserInfoClient(); MethodCallback<UserInfoResponseImpl> callback = new MethodCallback<UserInfoResponseImpl>() { @Override public void onFailure(Method method, Throwable exception) { logger.severe("FAILED TO RETRIEVE USER DATA. ERROR "+exception.getClass().getName()+" MSG "+exception.getMessage()); uiCallback.onFailure(method,exception); } @Override public void onSuccess(Method method, UserInfoResponseImpl response) { uiCallback.onSuccess(method,response); } }; client.getUserInfo(callback); logger.info("Get userInfo ends..."); } /** * @return a instance of the user info client */ private UserInfoClient getUserInfoClient() { Resource resource = new Resource(userInfoUrl); UserInfoClient client = GWT.create(UserInfoClient.class); ((RestServiceProxy) client).setResource(resource); return client; } @Override public String getCookiePath() { return cookiePath; } void removeCookies(final Callback callback){ if (UserInformationService.super.performLogout(callback)){ logger.fine("SESSION COOKIE SUCCESSFULLY REMOVED"); } else { logger.warning("NO SESSION COOKIE FOUND FOR REMOVAL?"); } } private static abstract class LogoutTask implements Runnable{ final UserInformationServiceImpl userService; private LogoutTask(UserInformationServiceImpl userService) { this.userService = userService; } @Override public abstract void run(); } private static abstract class LogoutCallback implements Callback { final UserInformationServiceImpl userService; final Callback nestedCallback; private LogoutCallback(UserInformationServiceImpl userService, Callback nestedCallback) { this.userService = userService; this.nestedCallback = nestedCallback; } } }
package com.github.treasurehunt.controller; import com.github.treasurehunt.dao.UserDao; import com.github.treasurehunt.dto.ConfigDTO; import com.github.treasurehunt.dto.Reward; import com.google.common.util.concurrent.RateLimiter; import lombok.extern.slf4j.Slf4j; import org.influxdb.dto.Point; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.influxdb.InfluxDBTemplate; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @RestController @RequestMapping("/treasure") @Slf4j public class TreasureController { @Autowired private UserDao userDao; private static ConfigDTO configDTO = new ConfigDTO(); private static final AtomicInteger totalHits = new AtomicInteger(); private static final Random random = new Random(); private Map<String, RateLimiter> limiterMap = new ConcurrentHashMap<>(); @Autowired private InfluxDBTemplate<Point> influxDBTemplate; @Secured("ROLE_ADMIN") @PostMapping("/config") public ConfigDTO setParams(@RequestBody ConfigDTO configDTO) { TreasureController.configDTO = configDTO; totalHits.set(0); return configDTO; } @Secured("ROLE_USER") @GetMapping("/earn") public Reward earnMoney(Principal user) throws InterruptedException { Reward reward; if (!limiterMap.containsKey(user.getName())) { limiterMap.put(user.getName(), RateLimiter.create(configDTO.getRateLimit())); } if (limiterMap.get(user.getName()).getRate() != configDTO.getRateLimit()) { limiterMap.get(user.getName()).setRate(configDTO.getRateLimit()); } limiterMap.get(user.getName()).acquire(); if (totalHits.incrementAndGet() < configDTO.getFirstNLucky()) { reward = new Reward(configDTO.getFirstNLuckyPoints()); } else { reward = new Reward(configDTO.getMinPoints() + random.nextInt(configDTO.getMaxPoints() - configDTO.getMinPoints())); } if (configDTO.getResponseDelay() > 0) { Thread.sleep(configDTO.getResponseDelay()); } try { final Point p = Point.measurement("money") .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS) .field("value", reward.getMoney()) .field("username", user.getName()) .build(); influxDBTemplate.write(p); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("Can't provide money now. Internal server error"); } return reward; } }
package jp.troter.servlet.httpsession.spi.impl; import java.util.HashMap; import jp.troter.servlet.httpsession.spi.SessionStateManager; import jp.troter.servlet.httpsession.state.DefaultSessionState; import jp.troter.servlet.httpsession.state.SessionState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultSessionStateManager extends SessionStateManager { private static Logger log = LoggerFactory.getLogger(DefaultSessionStateManager.class); @Override public void updateState(String sessionId, SessionState sessionState) { log.error("DefaultSessionStateManager.updateState is stub."); } @Override public void removeState(String sessionId) { log.error("DefaultSessionStateManager.removeState is stub."); } @Override public SessionState loadState(String sessionId) { log.error("DefaultSessionStateManager.loadState is stub."); return new DefaultSessionState(new HashMap<String, Object>()); } }
package com.hp.oo.execution.services; import com.hp.oo.engine.node.services.WorkerNodeService; import com.hp.oo.orchestrator.services.configuration.WorkerConfigurationService; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.io.FileFilter; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static ch.lambdaj.Lambda.*; public class WorkerManager implements ApplicationListener, EndExecutionCallback, WorkerRecoveryListener { private final Logger logger = Logger.getLogger(this.getClass()); private static final int KEEP_ALIVE_FAIL_LIMIT = 4; @Resource private String workerUuid; @Autowired private WorkerNodeService workerNodeService; @Autowired private WorkerConfigurationService workerConfigurationService; @Autowired private WorkerRecoveryManager recoveryManager; private LinkedBlockingQueue<Runnable> inBuffer = new LinkedBlockingQueue<>(); @Autowired @Qualifier("numberOfExecutionThreads") private Integer numberOfThreads; @Autowired(required = false) @Qualifier("initStartUpSleep") private Long initStartUpSleep = 15*1000L; // by default 15 seconds @Autowired(required = false) @Qualifier("maxStartUpSleep") private Long maxStartUpSleep = 10*60*1000L; // by default 10 minutes private int keepAliveFailCount = 0; private ExecutorService executorService; private Map<Long, Future> mapOfRunningTasks; private volatile boolean endOfInit = false; private volatile boolean initStarted = false; private boolean up = false; @PostConstruct private void init() { logger.info("Initialize worker with UUID: " + workerUuid); System.setProperty("worker.uuid", workerUuid); //do not remove!!! executorService = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, inBuffer, new WorkerThreadFactory("WorkerExecutionThread")); mapOfRunningTasks = new ConcurrentHashMap<>(numberOfThreads); } public void addExecution(Long executionId, Runnable runnable) { if (!recoveryManager.isInRecovery()) { Future future = executorService.submit(runnable); mapOfRunningTasks.put(executionId, future); } } @Override public void endExecution(Long executionId) { mapOfRunningTasks.remove(executionId); } public int getInBufferSize() { return inBuffer.size(); } @SuppressWarnings("unused") //scheduled in xml public void workerKeepAlive() { if (!recoveryManager.isInRecovery()) { if (endOfInit) { try { String newWrv = workerNodeService.keepAlive(workerUuid); String currentWrv = recoveryManager.getWRV(); //do not update it!!! if it is different than we have - restart worker (clean state) if(!currentWrv.equals(newWrv)){ logger.warn("Got new WRV from Orchestrator during keepAlive(). Going to reload..."); recoveryManager.doRecovery(); } keepAliveFailCount = 0; } catch (Exception e) { keepAliveFailCount++; logger.error("Could not send keep alive to Central, keepAliveFailCount = "+keepAliveFailCount); if(keepAliveFailCount > KEEP_ALIVE_FAIL_LIMIT){ recoveryManager.doRecovery(); } } } } else { if (logger.isDebugEnabled()) logger.debug("worker waits for recovery"); } } @SuppressWarnings("unused") // called by scheduler public void logStatistics() { if (logger.isDebugEnabled()) { logger.debug("InBuffer size: " + getInBufferSize()); logger.debug("Running task size: " + mapOfRunningTasks.size()); } } public String getWorkerUuid() { return workerUuid; } public int getRunningTasksCount() { return mapOfRunningTasks.size(); } @Override public void onApplicationEvent(final ApplicationEvent applicationEvent) { if (applicationEvent instanceof ContextRefreshedEvent && !initStarted) { doStartup(); } else if (applicationEvent instanceof ContextClosedEvent) { doShutdown(); } } private void doStartup() { new Thread(new Runnable() { @Override public void run() { initStarted = true; long sleep = initStartUpSleep; boolean shouldRetry = true; while (shouldRetry) { try { String newWrv = workerNodeService.up(workerUuid); recoveryManager.setWRV(newWrv); //we do set of WRV here and in doRecovery() only!!! not in keepalive!!! shouldRetry = false; logger.info("Worker is up"); } catch (Exception ex) { logger.error("Worker failed on start up, will retry in a " + sleep / 1000 + " seconds", ex); try { Thread.sleep(sleep); } catch (InterruptedException iex) {/*do nothing*/} sleep = Math.min(maxStartUpSleep, sleep * 2); // double the sleep time until max 10 minute } } endOfInit = true; //mark that worker is up and its recovery is ended - only now we can start asking for messages from queue up = true; workerConfigurationService.enabled(true); workerNodeService.updateEnvironmentParams(workerUuid, System.getProperty("os.name"), System.getProperty("java.version"), resolveDotNetVersion()); } }).start(); } private void doShutdown() { endOfInit = false; initStarted = false; workerConfigurationService.enabled(false); workerNodeService.down(workerUuid); up = false; logger.info("The worker is down"); } protected String resolveDotNetVersion() { File dotNetHome = new File(System.getenv("WINDIR") + "/Microsoft.NET/Framework"); if (dotNetHome.isDirectory()) { File[] versionFolders = dotNetHome.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory() && file.getName().startsWith("v"); } }); if (!ArrayUtils.isEmpty(versionFolders)) { String maxVersion = max(versionFolders, on(File.class).getName()).substring(1); return maxVersion.substring(0, 1) + ".x"; } } return "N/A"; } public boolean isUp() { return up; } //Must clean the buffer that holds Runnables that wait for execution and also drop all the executions that currently run public void doRecovery() { // Attempts to stop all actively executing tasks, halts the // processing of waiting tasks, and returns a list of the tasks // that were awaiting execution. // This method does not wait for actively executing tasks to // terminate. // There are no guarantees beyond best-effort attempts to stop // processing actively executing tasks. For example, typical // implementations will cancel via {@link Thread#interrupt}, so any // task that fails to respond to interrupts may never terminate. executorService.shutdownNow(); try { logger.warn("Worker is in doRecovery(). Cleaning state and cancelling running tasks. It may take up to 5 minutes..."); boolean finished = executorService.awaitTermination(5, TimeUnit.MINUTES); if(finished){ logger.warn("Worker succeeded to cancel running tasks during doRecovery()."); } else { logger.warn("Not all running tasks responded to cancel."); } } catch (InterruptedException ex){/*ignore*/} mapOfRunningTasks.clear(); //Make new executor executorService = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, inBuffer, new WorkerThreadFactory("WorkerExecutionThread")); } }
package org.xwiki.test.selenium; import junit.framework.Test; import org.xwiki.test.selenium.framework.AbstractXWikiTestCase; import org.xwiki.test.selenium.framework.ColibriSkinExecutor; import org.xwiki.test.selenium.framework.XWikiTestSuite; /** * Verify the document extra feature of XWiki. * * @version $Id$ */ public class DocExtraTest extends AbstractXWikiTestCase { public static Test suite() { XWikiTestSuite suite = new XWikiTestSuite("Verify the document extra feature of XWiki"); suite.addTestSuite(DocExtraTest.class, ColibriSkinExecutor.class); return suite; } @Override public void setUp() throws Exception { super.setUp(); loginAsAdmin(); } /** * Test document extras presence after a click on the corresponding tabs. */ public void testDocExtraLoadingFromTabClicks() { open("Main", "WebHome"); clickLinkWithXPath("//a[@id='Attachmentslink']", false); waitForDocExtraPaneActive("attachments"); clickLinkWithXPath("//a[@id='Historylink']", false); waitForDocExtraPaneActive("history"); clickLinkWithXPath("//a[@id='Informationlink']", false); waitForDocExtraPaneActive("information"); clickLinkWithXPath("//a[@id='Commentslink']", false); waitForDocExtraPaneActive("comments"); } /** * Test document extras presence after pressing the corresponding keyboard shortcuts. This test also verify that the * browser scrolls to the bottom of the page. * * @throws InterruptedException if selenium fails to simulate keyboard shortcut. */ public void testDocExtraLoadingFromKeyboardShortcuts() throws InterruptedException { open("Main", "WebHome"); int initialVerticalScroll = getVerticalScroll(); getSkinExecutor().pressKeyboardShortcut("a", false, false, false); waitForDocExtraPaneActive("attachments"); assertTrue(initialVerticalScroll < getVerticalScroll()); scrollToPageTop(); getSkinExecutor().pressKeyboardShortcut("h", false, false, false); waitForDocExtraPaneActive("history"); assertTrue(initialVerticalScroll < getVerticalScroll()); scrollToPageTop(); getSkinExecutor().pressKeyboardShortcut("i", false, false, false); waitForDocExtraPaneActive("information"); assertTrue(initialVerticalScroll < getVerticalScroll()); scrollToPageTop(); getSkinExecutor().pressKeyboardShortcut("c", false, false, false); waitForDocExtraPaneActive("comments"); assertTrue(initialVerticalScroll < getVerticalScroll()); } /** * Test document extra presence when the user arrives from an URL with anchor. This test also verify that the * browser scrolls to the bottom of the page. */ public void testDocExtraLoadingFromURLAnchor() { // We have to load a different page first since opening the same page with a new anchor doesn't call // our functions (on purpose) open("Main", "ThisPageDoesNotExist"); open("Main", "WebHome#Attachments"); waitForDocExtraPaneActive("attachments"); assertTrue(getVerticalScroll() > 0); open("Main", "ThisPageDoesNotExist"); open("Main", "WebHome#History"); waitForDocExtraPaneActive("history"); assertTrue(getVerticalScroll() > 0); open("Main", "ThisPageDoesNotExist"); open("Main", "WebHome#Information"); waitForDocExtraPaneActive("information"); assertTrue(getVerticalScroll() > 0); open("Main", "ThisPageDoesNotExist"); open("Main", "WebHome#Comments"); waitForDocExtraPaneActive("comments"); assertTrue(getVerticalScroll() > 0); } /** * Test document extra presence after clicks on links directing to the extra tabs (top menu for Toucan skin for * example and shortcuts for Colibri skin for example). This test also verify that the browser scrolls to the bottom * of the page. */ public void testDocExtraLoadingFromLinks() { open("Main", "WebHome"); clickShowAttachments(); waitForDocExtraPaneActive("attachments"); assertTrue(getVerticalScroll() > 0); scrollToPageTop(); clickShowHistory(); waitForDocExtraPaneActive("history"); assertTrue(getVerticalScroll() > 0); scrollToPageTop(); clickShowInformation(); waitForDocExtraPaneActive("information"); assertTrue(getVerticalScroll() > 0); scrollToPageTop(); clickShowComments(); waitForDocExtraPaneActive("comments"); assertTrue(getVerticalScroll() > 0); } /** * @param paneId valid values: "history", "comments", etc */ private void waitForDocExtraPaneActive(String paneId) { waitForElement(paneId + "content"); } private int getVerticalScroll() { return Integer.parseInt(getSelenium().getEval("window.scrollY")); } private void scrollToPageTop() { getSelenium().getEval("window.scroll(0,0);"); } }
package com.kinancity.core.captcha.imageTypers; import java.io.IOException; import java.net.SocketTimeoutException; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kinancity.api.errors.TechnicalException; import com.kinancity.core.captcha.CaptchaException; import com.kinancity.core.captcha.CaptchaProvider; import com.kinancity.core.captcha.CaptchaQueue; import lombok.Getter; import lombok.Setter; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class ImageTypersProvider extends CaptchaProvider { private CaptchaQueue queue; /** * List of 2captcha Challenges sent */ private List<ImageTypersRequest> challenges = new ArrayList<>(); private Logger logger = LoggerFactory.getLogger(getClass()); /** * Captcha API key */ private String apiKey = null; /** * ImageTypers Id; */ private String softId = "535817"; /** * Wait at least that time (in seconds) before sending first resolve request. (default 5s) */ @Setter private int minTimeBeforeFirstResolve = 5; /** * How often should we call 2Captcha (default 5000 ms) */ @Setter private int waitBeforeRetry = 5000; private boolean runFlag = true; private boolean stopOnInsufficientBalance = true; public static final String INSUFFICIENT_BALANCE = "INSUFFICIENT_BALANCE"; /** * Google Site key */ private String googleSiteKey = "6LdpuiYTAAAAAL6y9JNUZzJ7cF3F8MQGGKko1bCy"; // URLs private static final String PAGE_URL = "https://club.pokemon.com/us/pokemon-trainer-club/parents/sign-up"; private static String RECAPTCHA_SUBMIT_ENDPOINT = "http://captchatypers.com/captchaapi/UploadRecaptchaToken.ashx"; private static String RECAPTCHA_RETRIEVE_ENDPOINT = "http://captchatypers.com/captchaapi/GetRecaptchaTextToken.ashx"; private static String BALANCE_ENDPOINT = "http://captchatypers.com/Forms/RequestBalanceToken.ashx"; private OkHttpClient captchaClient = new OkHttpClient(); // Count the number of captcha sent @Getter private int nbSent = 0; public static CaptchaProvider getInstance(CaptchaQueue queue, String apiKey) throws CaptchaException { return new ImageTypersProvider(queue, apiKey); } public ImageTypersProvider(CaptchaQueue queue, String apiKey) throws ImageTypersConfigurationException { this.queue = queue; this.apiKey = apiKey; this.captchaClient = new OkHttpClient(); if (this.apiKey == null || this.apiKey.isEmpty()) { throw new ImageTypersConfigurationException("Missing ImageTypers Access Token"); } } @Override public void run() { while (runFlag) { LocalDateTime minDate = LocalDateTime.now().minusSeconds(minTimeBeforeFirstResolve); Set<ImageTypersRequest> challengesToResolve = challenges.stream().filter(c -> c.getSentTime().isBefore(minDate)).collect(Collectors.toSet()); if (challengesToResolve.isEmpty()) { // No captcha waiting logger.debug("No captcha check needed, {} in queue", challenges.size()); } else { // Currently waiting for captcha logger.debug("Check status of {} captchas", challengesToResolve.size()); for (ImageTypersRequest challenge : challengesToResolve) { String captchaId = challenge.getCaptchaId(); Request receiveRequest = buildReceiveCaptchaRequest(captchaId); try (Response sendResponse = captchaClient.newCall(receiveRequest).execute()) { String body = sendResponse.body().string(); if (body.startsWith("ERROR")) { if (body.contains("NOT_DECODED")) { // Captcha not ready, should wait if (getMaxWait() > 0 && LocalDateTime.now().isAfter(challenge.getSentTime().plusSeconds(getMaxWait()))) { logger.error("This captcha has been waiting too long, drop it. Increase `maxWait` if that happens too often"); challenges.remove(challenge); } else { // Keep the challenge in queue challenge.setNbPolls(challenge.getNbPolls() + 1); } } else if (body.contains("IMAGE_TIMED_OUT")) { logger.warn("ImageTypers IMAGE_TIMED_OUT. Try again"); challenges.remove(challenge); } else if (body.contains("INVALID_CAPTCHA_ID")) { logger.error("ImageTypers reported captcha ID as invdalid : " + captchaId); challenges.remove(challenge); } else { logger.error("Unknown ImageTypers Error : " + body); challenges.remove(challenge); } } else { String response = body; logger.info("Captcha response given in {}s", ChronoUnit.SECONDS.between(challenge.getSentTime(), LocalDateTime.now())); queue.addCaptcha(response); challenges.remove(challenge); } } catch (IOException e) { logger.error("ImageTypers Error : " + e.getMessage(), e); logger.debug("ImageTypers Error details", e); challenges.remove(challenge); } } } // Update queue size // Number of elements waiting for a captcha int nbInQueue = queue.size(); // Number currently waiting at 2captcha int nbWaiting = challenges.size(); // How many more do we need int nbNeeded = Math.min(nbInQueue, getMaxParallelChallenges()); int nbToRequest = Math.max(0, nbNeeded - nbWaiting); if (nbToRequest > 0) { // Send new captcha requests Request sendRequest = buildSendCaptchaRequest(); for (int i = 0; i < nbToRequest; i++) { try (Response sendResponse = captchaClient.newCall(sendRequest).execute()) { String body = sendResponse.body().string(); if (body.contains("ERROR")) { if (body.contains("INSUFFICIENT_BALANCE")) { if (manageInsufficientBalanceStop()) { break; } } else { logger.error("Error while calling IN ImageTypers : {}", body); } } else { String captchaId = body; logger.info("Requested new Captcha, id : {}", captchaId); challenges.add(new ImageTypersRequest(captchaId)); } } catch (Exception e) { if (INSUFFICIENT_BALANCE.equals(e.getMessage())) { if (manageInsufficientBalanceStop()) { break; } } else { logger.error("Error while calling IN ImageTypers : {}", e.getMessage()); } } } } try { Thread.sleep(waitBeforeRetry); } catch (InterruptedException e) { logger.error("Interrupted"); } } } /** * Manage insufficient Balance * * @return true if loop should stop */ private boolean manageInsufficientBalanceStop() { logger.error("Insufficient balance"); if (stopOnInsufficientBalance) { logger.error("STOP"); this.runFlag = false; return true; } else { logger.error("WAIT"); try { Thread.sleep(30000); } catch (InterruptedException e1) { // Interrupted } } return false; } /** * Get Current Balance. Should be called at least once before use to check for valid key. * * @return current balance in USD * @throws TechnicalException */ public double getBalance() throws ImageTypersConfigurationException { try { Request sendRequest = buildBalanceCheckequestGet(); Response sendResponse = captchaClient.newCall(sendRequest).execute(); String body = sendResponse.body().string(); if (body.contains("ERROR")) { if (body.contains("AUTHENTICATION_FAILED")) { throw new ImageTypersConfigurationException("Authentication failed, captcha key might be bad"); } else { throw new ImageTypersConfigurationException(body); } } return Double.valueOf(body.replaceAll("\\$", "")); } catch (IOException e) { throw new ImageTypersConfigurationException("Error getting account balance", e); } } /** * Send Captcha Request * * @return */ private Request buildSendCaptchaRequest() { HttpUrl url = HttpUrl.parse(RECAPTCHA_SUBMIT_ENDPOINT).newBuilder() .addQueryParameter("action", "UPLOADCAPTCHA") .addQueryParameter("googlekey", googleSiteKey) .addQueryParameter("pageurl", PAGE_URL) .addQueryParameter("token", apiKey) .addQueryParameter("refid", softId) .addQueryParameter("affiliateid", softId) .build(); Request request = new Request.Builder() .url(url) .build(); return request; } /** * Receive Captcha Request * * @param catpchaId * @return */ private Request buildReceiveCaptchaRequest(String catpchaId) { HttpUrl url = HttpUrl.parse(RECAPTCHA_RETRIEVE_ENDPOINT).newBuilder() .addQueryParameter("action", "GETTEXT") .addQueryParameter("captchaid", catpchaId) .addQueryParameter("ids", catpchaId) .addQueryParameter("token", apiKey) .addQueryParameter("refid", softId) .addQueryParameter("affiliateid", softId) .build(); Request request = new Request.Builder() .url(url) .build(); return request; } /** * Check Balance * * @param catpchaId * @return */ private Request buildBalanceCheckequestGet() { HttpUrl url = HttpUrl.parse(BALANCE_ENDPOINT).newBuilder() .addQueryParameter("action", "REQUESTBALANCE") .addQueryParameter("token", apiKey) .build(); Request request = new Request.Builder() .url(url) .build(); return request; } /** * Check Balance * * @param catpchaId * @return */ private Request buildBalanceCheckequestPost() { HttpUrl url = HttpUrl.parse(BALANCE_ENDPOINT).newBuilder() .build(); FormBody body = new FormBody.Builder() .addEncoded("action", "REQUESTBALANCE") .addEncoded("token", apiKey) .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); return request; } }
package rapture.elasticsearch; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import com.google.common.net.MediaType; import rapture.common.BlobUpdateObject; import rapture.common.DocUpdateObject; import rapture.common.RaptureURI; import rapture.common.Scheme; import rapture.common.exception.ExceptionToString; import rapture.common.impl.jackson.JacksonUtil; import rapture.common.model.DocumentMetadata; import rapture.common.model.DocumentWithMeta; import rapture.common.series.SeriesUpdateObject; import rapture.search.SearchRepoType; public class ElasticSearchSearchRepositoryTest { private ElasticSearchSearchRepository e; private EmbeddedServer es; @Before public void setup() { e = new ElasticSearchSearchRepository(); e.setIndex("unittest"); es = new EmbeddedServer(); e.setClient(es.getClient()); } @Test public void testEasySearch() { String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2014-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}"; RaptureURI uri = new RaptureURI("document://unittest/doc1", Scheme.DOCUMENT); DocumentWithMeta d = createDummyDocumentWithMeta(uri.toString(), json); e.put(new DocUpdateObject(d)); e.refresh(); rapture.common.SearchResponse response = e.search(Arrays.asList(Scheme.DOCUMENT.toString()), "kimchy"); assertEquals(1, response.getTotal().longValue()); assertEquals(1, response.getSearchHits().size()); assertEquals(uri.toShortString(), response.getSearchHits().get(0).getUri()); assertEquals(uri.toShortString(), response.getSearchHits().get(0).getId()); assertEquals(json, response.getSearchHits().get(0).getSource()); } @Test public void testSearchWithCursor() { insertTestDocs(); int size = 25; String query = "u*er*"; rapture.common.SearchResponse res = e.searchWithCursor(Arrays.asList(Scheme.DOCUMENT.toString()), null, size, query); assertNotNull(res.getCursorId()); assertEquals(25, res.getSearchHits().size()); assertEquals(100, res.getTotal().longValue()); assertNotNull(res.getMaxScore()); for (int i = 0; i < res.getSearchHits().size(); i++) { rapture.common.SearchHit hit = res.getSearchHits().get(i); assertEquals("document://unittest/doc" + i, hit.getUri()); } int counter = size; while (true) { res = e.searchWithCursor(Arrays.asList(Scheme.DOCUMENT.toString()), res.getCursorId(), size, query); if (res.getSearchHits().isEmpty()) { break; } assertNotNull(res.getCursorId()); assertEquals(25, res.getSearchHits().size()); assertEquals(100, res.getTotal().longValue()); assertNotNull(res.getMaxScore()); for (int i = 0; i < res.getSearchHits().size(); i++) { rapture.common.SearchHit hit = res.getSearchHits().get(i); assertEquals("document://unittest/doc" + (i + counter), hit.getUri()); } counter += size; } } @Test public void testSearchAndConvert() { insertTestDocs(); String query = "*"; Client c = es.getClient(); SearchResponse response = c.prepareSearch().setExplain(false).setQuery(QueryBuilders.queryStringQuery(query)).setTypes(Scheme.DOCUMENT.toString()) .setScroll(new TimeValue(60000)).setSize(20).get(); rapture.common.SearchResponse ret = e.convert(response); assertEquals(response.getHits().getTotalHits(), ret.getTotal().longValue()); assertEquals(response.getScrollId(), ret.getCursorId()); assertEquals(new Double(response.getHits().getMaxScore()), ret.getMaxScore()); assertEquals(response.getHits().hits().length, ret.getSearchHits().size()); for (int i = 0; i < ret.getSearchHits().size(); i++) { rapture.common.SearchHit hit = ret.getSearchHits().get(i); SearchHit eHit = response.getHits().hits()[i]; assertEquals(new Double(Double.parseDouble(Float.toString(eHit.getScore()))), hit.getScore()); assertEquals(eHit.getSourceAsString(), hit.getSource()); assertEquals("document://unittest/doc" + i, hit.getUri()); } } @Test public void testDocPut() { String docPath = "dubnation/d2/d1"; DocumentWithMeta d = createDummyDocumentWithMeta(Scheme.DOCUMENT.toString() + "://" + docPath, "{\"k1\":\"v1\"}"); e.put(new DocUpdateObject(d)); e.refresh(); rapture.common.SearchResponse r = e.search(Arrays.asList(Scheme.DOCUMENT.toString()), "v1"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals("document", r.getSearchHits().get(0).getIndexType()); assertEquals("document://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("document://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"k1\":\"v1\"}", r.getSearchHits().get(0).getSource()); r = e.search(Arrays.asList(SearchRepoType.uri.toString()), "d2"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals("document://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("document://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"d2\",\"d1\"],\"repo\":\"dubnation\",\"scheme\":\"document\"}", r.getSearchHits().get(0).getSource()); } @Test public void testScriptPut() { String docPath = "somescript/d2/d1"; DocumentWithMeta d = createDummyDocumentWithMeta(Scheme.SCRIPT.toString() + "://" + docPath, "{\"k1\":\"v1\"}"); e.put(new DocUpdateObject(d)); e.refresh(); rapture.common.SearchResponse r = e.search(Arrays.asList(Scheme.SCRIPT.toString()), "v1"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals("script", r.getSearchHits().get(0).getIndexType()); assertEquals("script://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("script://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"k1\":\"v1\"}", r.getSearchHits().get(0).getSource()); r = e.search(Arrays.asList(SearchRepoType.uri.toString()), "d2"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals("script://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("script://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"d2\",\"d1\"],\"repo\":\"somescript\",\"scheme\":\"script\"}", r.getSearchHits().get(0).getSource()); } @Test public void testSeriesPut() { String docPath = "testme/x/y"; SeriesUpdateObject s = new SeriesUpdateObject(docPath, Arrays.asList("k1"), Arrays.asList("v1")); e.put(s); e.refresh(); rapture.common.SearchResponse r = e.search(Arrays.asList(Scheme.SERIES.toString()), "v1"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals("series", r.getSearchHits().get(0).getIndexType()); assertEquals("series://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("series://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"k1\":\"v1\"}", r.getSearchHits().get(0).getSource()); s = new SeriesUpdateObject("testme/x/y", Arrays.asList("k2"), Arrays.asList("v2")); e.put(s); e.refresh(); r = e.search(Arrays.asList(Scheme.SERIES.toString()), "v1"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals("series", r.getSearchHits().get(0).getIndexType()); assertEquals("series://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("series://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"k1\":\"v1\",\"k2\":\"v2\"}", r.getSearchHits().get(0).getSource()); r = e.search(Arrays.asList(SearchRepoType.uri.toString()), "x"); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals("series://" + docPath, r.getSearchHits().get(0).getId()); assertEquals("series://" + docPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"x\",\"y\"],\"repo\":\"testme\",\"scheme\":\"series\"}", r.getSearchHits().get(0).getSource()); } @Test public void testSearchForRepoUris() { String authority = "unittest"; String seriesDocPath = authority + "/x/y"; String docDocPath = authority + "/doc0"; SeriesUpdateObject s = new SeriesUpdateObject(seriesDocPath, Arrays.asList("k1", "k2", "k3"), Arrays.asList(1.0, 2.0, 4.0)); e.put(s); insertTestDocs(); rapture.common.SearchResponse r = e.searchForRepoUris(Scheme.SERIES.toString(), authority, null); assertEquals(1L, r.getTotal().longValue()); assertEquals(1, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals("series://" + seriesDocPath, r.getSearchHits().get(0).getId()); assertEquals("series://" + seriesDocPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"x\",\"y\"],\"repo\":\"" + authority + "\",\"scheme\":\"series\"}", r.getSearchHits().get(0).getSource()); r = e.searchForRepoUris(Scheme.DOCUMENT.toString(), authority, null); assertEquals(100, r.getTotal().longValue()); assertEquals(10, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals("document://" + docDocPath, r.getSearchHits().get(0).getId()); assertEquals("document://" + docDocPath, r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"doc0\"],\"repo\":\"" + authority + "\",\"scheme\":\"document\"}", r.getSearchHits().get(0).getSource()); } @Test public void testRemove() { insertTestDocs(); rapture.common.SearchResponse r = e.search(Arrays.asList(Scheme.DOCUMENT.toString()), "trying out Elasticsearch"); assertEquals(100, r.getTotal().longValue()); e.remove(new RaptureURI("document://unittest/doc24")); e.remove(new RaptureURI("document://unittest/doc69")); e.remove(new RaptureURI("document://unittest/doc77")); e.refresh(); r = e.search(Arrays.asList(Scheme.DOCUMENT.toString()), "trying out Elasticsearch"); assertEquals(97, r.getTotal().longValue()); SeriesUpdateObject s = new SeriesUpdateObject("removerepo/a/b/c", Arrays.asList("k1", "k2", "k3"), Arrays.asList(1.0, 2.0, 4.0)); e.put(s); e.refresh(); r = e.search(Arrays.asList(Scheme.SERIES.toString()), "4.0"); assertEquals(1, r.getTotal().longValue()); e.remove(new RaptureURI("series://removerepo/a/b/c")); e.refresh(); r = e.search(Arrays.asList(Scheme.SERIES.toString()), "v3"); assertEquals(0, r.getTotal().longValue()); r = e.search(Arrays.asList(Scheme.DOCUMENT.toString()), "trying out Elasticsearch"); assertEquals(97, r.getTotal().longValue()); } @Ignore @Test public void testSearchBlob() { String premier = "1,Leicester City,36,30,77\n2,Tottenham Hotspur,36,39,70\n3,Arsenal,36,25,67\n4,Manchester City,36,30,64\n5,Manchester United,35,12,60\n" + "6,West Ham United,35,17,59\n7,Southampton,36,14,57\n8,Liverpool,35,11,55\n9,Chelsea,35,7,48\n10,Stoke City,36,-14,48\n" + "11,Everton,35,6,44\n12,Watford,35,-6,44\n13,Swansea City,36,-13,43\n14,West Bromwich Albion,36,-14,41\n15,Bournemouth,36,-20,41\n1" + "6,Crystal Palace,36,-10,39\n17,Newcastle United,36,-25,33\n18,Sunderland,35,-18,32\n19,Norwich City,35,-26,31\n20,Aston Villa,36,-45,16\n"; String championship = "1,Burnley,45,34,90\n2,Middlesbrough,45,32,88\n3,Brighton & Hove Albion,45,30,88\n4,Hull City,45,30,80\n" + "5,Derby County,45,24,78\n6,Sheffield Wednesday,45,22,74\n7,Cardiff City,45,5,67\n8,Ipswich Town,45,1,66\n9,Birmingham City,45,4,62\n" + "10,Brentford,45,1,62\n11,Preston North End,45,0,61\n12,Leeds United,45,-8,58\n13,Queens Park Rangers,45,-1,57\n14,Wolverhampton Wanderers,45,-6,55\n" + "15,Blackburn Rovers,45,-2,52\n16,Reading,45,-5,52\n17,Nottingham Forest,45,-5,52\n18,Bristol City,45,-16,52\n19,Huddersfield Town,45,-7,51\n" + "20,Rotherham United,45,-14,49\n21,Fulham,45,-14,48\n22,Charlton Athletic,45,-37,40\n23,Milton Keynes Dons,45,-29,39\n24,Bolton Wanderers,45,-39,30\n"; // @SuppressWarnings("unchecked") // ImmutableList<ImmutableList<String>> leagueList = ImmutableList.of( // ImmutableList.of("1", "Leicester", "36", "30", "77"), // ImmutableList.of("2", "Tottenham", "36", "39", "70"), // ImmutableList.of("3", "Arsenal", "36", "25", "67"), // ImmutableList.of("4", "Man City", "36", "30", "64"), // ImmutableList.of("5", "Man Utd", "35", "12", "60"), // ImmutableList.of("6", "West Ham", "35", "17", "59"), // ImmutableList.of("7", "Southampton", "36", "14", "57"), // ImmutableList.of("8", "Liverpool", "35", "11", "55"), // ImmutableList.of("9", "Chelsea", "35", "7", "48"), // ImmutableList.of("10", "Stoke", "36", "-14", "48"), // ImmutableList.of("11", "Everton", "35", "6", "44"), // ImmutableList.of("12", "Watford", "35", "-6", "44"), // ImmutableList.of("13", "Swansea", "36", "-13", "43"), // ImmutableList.of("14", "West Brom", "36", "-14", "41"), // ImmutableList.of("15", "Bournemouth", "36", "-20", "41"), // ImmutableList.of("16", "Crystal Palace", "36", "-10", "39"), // ImmutableList.of("17", "Newcastle", "36", "-25", "33"), // ImmutableList.of("18", "Sunderland", "35", "-18", "32"), // ImmutableList.of("19", "Norwich", "35", "-26", "31"), // ImmutableList.of("20", "Aston Villa", "36", "-45", "16")); // String leagueJson = JacksonUtil.jsonFromObject(leagueList); // Unfortunately it seems that ElasticSearch requires a JSON document. // It won't accept a JSON list or a CSV. So we have to munge it. // This is a minimal PDF. Next step is to have one with data in it and show that we can index the contents String minimalPdf = "%PDF-1.0\n" + "1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\n" + "xref\n" + "0 4\n" + "0000000000 65535 f\n" + "0000000010 00000 n\n" + "0000000053 00000 n\n" + "0000000102 00000 n\n" + "trailer<</Size 4/Root 1 0 R>>\n" + "startxref\n" + "149\n" + "%EOF\n"; Map<String, String> copout = new HashMap<>(); copout.put("premier", premier); String leagueJson = JacksonUtil.jsonFromObject(copout); RaptureURI epl = new RaptureURI.Builder(Scheme.BLOB, "unittest").docPath("English/Premier").build(); e.put(new BlobUpdateObject(epl, leagueJson.getBytes(), MediaType.JSON_UTF_8.toString())); // e.put(new BlobUpdateObject(epl, premier.getBytes(), MediaType.JSON_UTF_8.toString())); RaptureURI champ = new RaptureURI.Builder(Scheme.BLOB, "unittest").docPath("English/Championship").build(); e.put(new BlobUpdateObject(champ, championship.getBytes(), MediaType.CSV_UTF_8.toString())); // Try reading a real PDF from a file File pdf = new File("src/test/resources/www-bbc-com.pdf"); try { byte[] content = Files.readAllBytes(pdf.toPath()); RaptureURI firstDiv = new RaptureURI.Builder(Scheme.BLOB, "unittest").docPath("English/First").build(); e.put(new BlobUpdateObject(firstDiv, content, MediaType.PDF.toString())); } catch (IOException e2) { fail(pdf.getAbsolutePath() + " : " + ExceptionToString.format(e2)); } File pdf2 = new File("src/test/resources/HelloWorld.pdf"); try { byte[] content = Files.readAllBytes(pdf2.toPath()); RaptureURI hello = new RaptureURI.Builder(Scheme.BLOB, "Hello").docPath("Hello/Wurld").build(); e.put(new BlobUpdateObject(hello, content, MediaType.PDF.toString())); } catch (IOException e3) { fail(pdf2.getAbsolutePath() + " : " + ExceptionToString.format(e3)); } try { // Tika parsing happens in a separate thread so give it a chance Thread.sleep(3000); } catch (InterruptedException e1) { } rapture.common.SearchResponse r = e.searchForRepoUris(Scheme.BLOB.toString(), epl.getAuthority(), null); assertEquals(3L, r.getTotal().longValue()); assertEquals(3, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals(epl.getShortPath(), r.getSearchHits().get(0).getId()); assertEquals(epl.toString(), r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"English\",\"Premier\"],\"repo\":\"" + epl.getAuthority() + "\",\"scheme\":\"blob\"}", r.getSearchHits().get(0).getSource()); r = e.searchForRepoUris(Scheme.BLOB.toString(), epl.getAuthority(), null); assertEquals(3, r.getSearchHits().size()); assertEquals(SearchRepoType.uri.toString(), r.getSearchHits().get(0).getIndexType()); assertEquals(epl.getShortPath(), r.getSearchHits().get(0).getId()); assertEquals(epl.toString(), r.getSearchHits().get(0).getUri()); assertEquals("{\"parts\":[\"English\",\"Premier\"],\"repo\":\"" + epl.getAuthority() + "\",\"scheme\":\"blob\"}", r.getSearchHits().get(0).getSource()); // Search inside the blob String query = "blob:*City"; rapture.common.SearchResponse res = e.searchWithCursor(Arrays.asList(Scheme.BLOB.toString()), null, 10, query); assertNotNull(res.getCursorId()); // The PDF has no data yet so shouldn't match assertEquals(2, res.getSearchHits().size()); assertNotNull(res.getMaxScore()); // Can we assume anything about the ordering? for (int i = 0; i < res.getSearchHits().size(); i++) { rapture.common.SearchHit hit = res.getSearchHits().get(i); assertTrue(hit.getUri().startsWith("blob://unittest/English/")); } query = "blob:*Wigan*"; res = e.searchWithCursor(SearchRepoType.valuesAsList(), null, 10, query); assertNotNull(res.getCursorId()); assertEquals(1, res.getSearchHits().size()); query = "blob:*World*"; res = e.searchWithCursor(SearchRepoType.valuesAsList(), null, 10, query); assertNotNull(res.getCursorId()); assertEquals(1, res.getSearchHits().size()); } private void insertTestDocs() { for (int i = 0; i < 100; i++) { String json = "{" + "\"user\":\"user" + i + "\"," + "\"postDate\":\"2014-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}"; RaptureURI uri = new RaptureURI("document://unittest/doc" + i, Scheme.DOCUMENT); DocumentWithMeta d = createDummyDocumentWithMeta(uri.toString(), json); e.put(new DocUpdateObject(d)); } e.refresh(); } private DocumentWithMeta createDummyDocumentWithMeta(String semanticUri, String json) { DocumentWithMeta d = new DocumentWithMeta(); DocumentMetadata dm = new DocumentMetadata(); dm.setComment("comment"); dm.setUser("user"); dm.setVersion(1); dm.setSemanticUri(semanticUri); d.setMetaData(dm); d.setDisplayName(semanticUri); d.setContent(json); return d; } @After public void teardown() { es.shutdown(); } }
package net.hawkengine.services.tests.filters; import com.fiftyonred.mock_jedis.MockJedisPool; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.hawkengine.core.ServerConfiguration; import net.hawkengine.core.utilities.constants.TestsConstants; import net.hawkengine.core.utilities.deserializers.MaterialDefinitionAdapter; import net.hawkengine.core.utilities.deserializers.TaskDefinitionAdapter; import net.hawkengine.core.utilities.deserializers.WsContractDeserializer; import net.hawkengine.db.IDbRepository; import net.hawkengine.db.redis.RedisRepository; import net.hawkengine.model.MaterialDefinition; import net.hawkengine.model.PipelineDefinition; import net.hawkengine.model.PipelineGroup; import net.hawkengine.model.TaskDefinition; import net.hawkengine.model.dto.WsContractDto; import net.hawkengine.model.enums.PermissionScope; import net.hawkengine.model.enums.PermissionType; import net.hawkengine.model.payload.Permission; import net.hawkengine.services.PipelineDefinitionService; import net.hawkengine.services.filters.PipelineDefinitionAuthorizationService; import net.hawkengine.services.filters.interfaces.IAuthorizationService; import net.hawkengine.services.interfaces.IPipelineDefinitionService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.JedisPoolConfig; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class PipelineDefinitionAuthorizationServiceTests { private PipelineDefinition firstPipeline; private PipelineDefinition secondPipeline; private PipelineDefinition thirdPipeline; private PipelineDefinition fourthPipeline; private PipelineGroup firstPipelineGroup; private PipelineGroup secondPipelineGroup; private IAuthorizationService authorizationService; private Gson jsonConverter; private IDbRepository<PipelineDefinition> mockedRepository; private IPipelineDefinitionService mockedPipeLineDefinitionService; @Before public void setUp() { this.firstPipelineGroup = new PipelineGroup(); this.secondPipelineGroup = new PipelineGroup(); this.firstPipeline = new PipelineDefinition(); this.firstPipeline.setPipelineGroupId(this.firstPipelineGroup.getId()); this.secondPipeline = new PipelineDefinition(); this.secondPipeline.setPipelineGroupId(this.firstPipelineGroup.getId()); this.thirdPipeline = new PipelineDefinition(); this.thirdPipeline.setPipelineGroupId(this.secondPipelineGroup.getId()); this.fourthPipeline = new PipelineDefinition(); this.fourthPipeline.setPipelineGroupId(this.secondPipelineGroup.getId()); this.jsonConverter = new GsonBuilder() .registerTypeAdapter(WsContractDto.class, new WsContractDeserializer()) .registerTypeAdapter(TaskDefinition.class, new TaskDefinitionAdapter()) .registerTypeAdapter(MaterialDefinition.class, new MaterialDefinitionAdapter()) .create(); MockJedisPool mockedPool = new MockJedisPool(new JedisPoolConfig(), "testPipelineDefinitionService"); ServerConfiguration.configure(); this.mockedRepository = new RedisRepository(PipelineDefinition.class, mockedPool); this.mockedPipeLineDefinitionService = new PipelineDefinitionService(this.mockedRepository); this.mockedPipeLineDefinitionService.add(this.firstPipeline); this.mockedPipeLineDefinitionService.add(this.secondPipeline); this.mockedPipeLineDefinitionService.add(this.thirdPipeline); this.mockedPipeLineDefinitionService.add(this.fourthPipeline); this.authorizationService = new PipelineDefinitionAuthorizationService(this.mockedPipeLineDefinitionService); } @Test public void getAll_withPermissionsForTwoEntities_twoEntities() { //Arrange List<Permission> permissions = this.createPermissions(); List<PipelineDefinition> entitiesToFilter = new ArrayList<>(); entitiesToFilter.add(this.firstPipeline); entitiesToFilter.add(this.secondPipeline); entitiesToFilter.add(this.thirdPipeline); entitiesToFilter.add(this.fourthPipeline); //Act List<PipelineDefinition> actualResult = this.authorizationService.getAll(permissions, entitiesToFilter); //Assert Assert.assertEquals(TestsConstants.TESTS_COLLECTION_SIZE_THREE_OBJECTS, actualResult.size()); } @Test public void getById_withPermissionToGet_true() { //Arrange List<Permission> permissions = this.createPermissions(); //Act boolean hasPermission = this.authorizationService.getById(this.firstPipeline.getId(), permissions); //Assert Assert.assertTrue(hasPermission); } @Test public void getById_withoutPermissionToGet_false() { //Arrange List<Permission> permissions = this.createPermissions(); //Act boolean hasPermission = this.authorizationService.getById(this.secondPipeline.getId(), permissions); //Assert Assert.assertFalse(hasPermission); } @Test public void add_withoutPermissionToAdd_false() { //Arrange PipelineDefinition pipelineDefinition = new PipelineDefinition(); pipelineDefinition.setPipelineGroupId(this.firstPipelineGroup.getId()); List<Permission> permissions = this.createPermissions(); String entityToAdd = this.jsonConverter.toJson(pipelineDefinition); //Act boolean hasPermission = this.authorizationService.add(entityToAdd, permissions); //Assert Assert.assertFalse(hasPermission); } @Test public void update_withPermissionToUpdate_true() { //Arrange List<Permission> permissions = this.createPermissions(); String entityToUpdate = this.jsonConverter.toJson(this.thirdPipeline); //Act boolean hasPermission = this.authorizationService.update(entityToUpdate, permissions); //Assert Assert.assertTrue(hasPermission); } @Test public void update_withoutPermissionToUpdate_false() { //Arrange List<Permission> permissions = this.createPermissions(); String entityToUpdate = this.jsonConverter.toJson(this.fourthPipeline); //Act boolean hasPermission = this.authorizationService.update(entityToUpdate, permissions); //Assert Assert.assertFalse(hasPermission); } @Test public void delete_withPermissionToDelete_true() { //Arrange List<Permission> permissions = this.createPermissions(); //Act boolean hasPermission = this.authorizationService.delete(this.thirdPipeline.getId(), permissions); //Assert Assert.assertTrue(hasPermission); } @Test public void delete_withoutPermissionToDelete_false() { //Arrange List<Permission> permissions = this.createPermissions(); //Act boolean hasPermission = this.authorizationService.delete(this.firstPipeline.getId(), permissions); //Assert Assert.assertFalse(hasPermission); } @Test public void initialize_validConstructor_notNull() { //Act this.authorizationService = new PipelineDefinitionAuthorizationService(); //Assert Assert.assertNotNull(this.authorizationService); } private List<Permission> createPermissions() { List<Permission> permissions = new ArrayList<>(); Permission firstPermission = new Permission(); firstPermission.setPermissionType(PermissionType.NONE); firstPermission.setPermissionScope(PermissionScope.PIPELINE_GROUP); firstPermission.setPermittedEntityId(this.firstPipelineGroup.getId()); Permission secondPermission = new Permission(); secondPermission.setPermissionType(PermissionType.OPERATOR); secondPermission.setPermissionScope(PermissionScope.PIPELINE); secondPermission.setPermittedEntityId(this.firstPipeline.getId()); Permission thirdPermission = new Permission(); thirdPermission.setPermissionType(PermissionType.ADMIN); thirdPermission.setPermissionScope(PermissionScope.SERVER); Permission fourthPermission = new Permission(); fourthPermission.setPermissionType(PermissionType.VIEWER); fourthPermission.setPermissionScope(PermissionScope.PIPELINE_GROUP); fourthPermission.setPermittedEntityId(this.secondPipelineGroup.getId()); Permission fifthPermission = new Permission(); fifthPermission.setPermissionType(PermissionType.ADMIN); fifthPermission.setPermissionScope(PermissionScope.PIPELINE); fifthPermission.setPermittedEntityId(this.thirdPipeline.getId()); permissions.add(firstPermission); permissions.add(secondPermission); permissions.add(thirdPermission); permissions.add(fourthPermission); permissions.add(fifthPermission); List<Permission> orderedPermissions = permissions.stream() .sorted((p1, p2) -> p1.getPermissionScope().compareTo(p2.getPermissionScope())).collect(Collectors.toList()); return orderedPermissions; } }
package de.maibornwolff.codecharta.importer.csv; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import java.util.ArrayList; import java.util.List; public class CSVImporterParameter { private final JCommander jc; @Parameter(names = {"-d", "--delimeter"}, description = "delimeter in csv file") private String csvDelimiter = ","; @Parameter(names = {"-p", "--projectName"}, description = "Project name") private String projectName = "testProject"; @Parameter(names = {"--backslash"}, description = "Backslash is used as path separator") private boolean backslashPathSeparator = false; @Parameter(description = "[file]") private List<String> files = new ArrayList<>(); @Parameter(names = {"-h", "--help"}, description = "This help text", help = true) private boolean help = false; public CSVImporterParameter(String[] args) { this.jc = new JCommander(this, args); } public char getPathSeparator() { return backslashPathSeparator ? '\\' : '/'; } public char getCsvDelimiter() { return csvDelimiter.charAt(0); } public List<String> getFiles() { return files; } public boolean isHelp() { return help; } public void printUsage() { jc.usage(); } public String getProjectName() { return projectName; } }
package org.chromium.android_webview.test; import android.os.Build; import android.os.Message; import android.test.suitebuilder.annotation.SmallTest; import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import org.apache.http.util.EncodingUtils; import org.chromium.android_webview.AwContents; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.content.browser.test.util.TestCallbackHelperContainer; import org.chromium.net.test.util.TestWebServer; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Tests if resubmission of post data is handled properly. */ @MinAndroidSdkLevel(Build.VERSION_CODES.KITKAT) public class AwContentsClientOnFormResubmissionTest extends AwTestBase { private static class TestAwContentsClient extends org.chromium.android_webview.test.TestAwContentsClient { // Number of times onFormResubmit is called. private int mResubmissions = 0; // Whether to resubmit Post data on reload. private boolean mResubmit = false; public int getResubmissions() { return mResubmissions; } public void setResubmit(boolean resubmit) { mResubmit = resubmit; } @Override public void onFormResubmission(Message dontResend, Message resend) { mResubmissions++; if (mResubmit) { resend.sendToTarget(); } else { dontResend.sendToTarget(); } } } // Server responses for load and reload of posts. private static final String LOAD_RESPONSE = "<html><head><title>Load</title></head><body>HELLO</body></html>"; private static final String RELOAD_RESPONSE = "<html><head><title>Reload</title></head><body>HELLO</body></html>"; // Server timeout in seconds. Used to detect dontResend case. private static final long TIMEOUT = scaleTimeout(3); // The web server. private TestWebServer mServer; // The mock client. private TestAwContentsClient mContentsClient; private AwContents mAwContents; @Override public void setUp() throws Exception { super.setUp(); mServer = TestWebServer.start(); mContentsClient = new TestAwContentsClient(); final AwTestContainerView testContainerView = createAwTestContainerViewOnMainSync(mContentsClient); mAwContents = testContainerView.getAwContents(); } @Override public void tearDown() throws Exception { mServer.shutdown(); super.tearDown(); } @SmallTest @Feature({"AndroidWebView", "Navigation"}) public void testResend() throws Throwable { mContentsClient.setResubmit(true); doReload(); assertEquals(1, mContentsClient.getResubmissions()); assertEquals("Reload", getTitleOnUiThread(mAwContents)); } @SmallTest @Feature({"AndroidWebView", "Navigation"}) public void testDontResend() throws Throwable { mContentsClient.setResubmit(false); doReload(); assertEquals(1, mContentsClient.getResubmissions()); assertEquals("Load", getTitleOnUiThread(mAwContents)); } protected void doReload() throws Throwable { String url = mServer.setResponse("/form", LOAD_RESPONSE, null); String postData = "content=blabla"; byte[] data = EncodingUtils.getBytes(postData, "BASE64"); postUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url, data); assertEquals(0, mContentsClient.getResubmissions()); assertEquals("Load", getTitleOnUiThread(mAwContents)); // Verify reload works as expected. mServer.setResponse("/form", RELOAD_RESPONSE, null); TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper = mContentsClient.getOnPageFinishedHelper(); int callCount = onPageFinishedHelper.getCallCount(); // Run reload on UI thread. getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { mAwContents.getNavigationController().reload(true); } }); try { // Wait for page finished callback, or a timeout. A timeout is necessary // to detect a dontResend response. onPageFinishedHelper.waitForCallback(callCount, 1, TIMEOUT, TimeUnit.SECONDS); } catch (TimeoutException e) { // Exception expected from testDontResend case. } } }
package com.ctrip.framework.apollo.metaservice.controller; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import com.ctrip.framework.apollo.metaservice.service.DiscoveryService; import com.netflix.appinfo.InstanceInfo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; @RestController @RequestMapping("/services") public class ServiceController { private final DiscoveryService discoveryService; public ServiceController(final DiscoveryService discoveryService) { this.discoveryService = discoveryService; } @RequestMapping("/meta") public List<ServiceDTO> getMetaService() { List<InstanceInfo> instances = discoveryService.getMetaServiceInstances(); List<ServiceDTO> result = instances.stream().map(InstanceInfo_To_ServiceDTO_Func).collect(Collectors.toList()); return result; } @RequestMapping("/config") public List<ServiceDTO> getConfigService( @RequestParam(value = "appId", defaultValue = "") String appId, @RequestParam(value = "ip", required = false) String clientIp) { List<InstanceInfo> instances = discoveryService.getConfigServiceInstances(); List<ServiceDTO> result = instances.stream().map(InstanceInfo_To_ServiceDTO_Func).collect(Collectors.toList()); return result; } @RequestMapping("/admin") public List<ServiceDTO> getAdminService() { List<InstanceInfo> instances = discoveryService.getAdminServiceInstances(); List<ServiceDTO> result = instances.stream().map(InstanceInfo_To_ServiceDTO_Func).collect(Collectors.toList()); return result; } private static Function<InstanceInfo, ServiceDTO> InstanceInfo_To_ServiceDTO_Func = new Function<InstanceInfo, ServiceDTO>() { @Override public ServiceDTO apply(InstanceInfo instance) { ServiceDTO service = new ServiceDTO(); service.setAppName(instance.getAppName()); service.setInstanceId(instance.getInstanceId()); service.setHomepageUrl(instance.getHomePageUrl()); return service; } }; }
package org.csstudio.ui.menu.app; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.ICoolBarManager; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.ToolBarContributionItem; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; import org.eclipse.ui.menus.IMenuService; import org.eclipse.ui.part.CoolItemGroupMarker; /** {@link ActionBarAdvisor} that can be called by CSS * application startup code to create the menu and tool bar. * * <p>The menu bar is mostly empty, only providing the "additions" * section that is used by the contributions in plugin.xml. * * <p>The toolbar also mostly defines sections used by contributions * from plugin.xml. * * <p>Some actions are created for Eclipse command names * in the help menu that have no default implementation. * * @author Kay Kasemir * @author Xihui Chen */ public class ApplicationActionBarAdvisor extends ActionBarAdvisor { /** Toolbar ID of switch user and logout toolbar */ private static final String TOOLBAR_USER = "user"; //$NON-NLS-1$ final private IWorkbenchWindow window; private IWorkbenchAction lock_toolbar, edit_actionsets, save; /** Initialize */ public ApplicationActionBarAdvisor(final IActionBarConfigurer configurer) { super(configurer); window = configurer.getWindowConfigurer().getWindow(); } /** Create actions. * * <p>Some of these actions are created to programmatically * add them to the toolbar. * Other actions like save_as are not used at all in here, * but they need to be created because the plugin.xml * registers their command ID in the menu bar, * and the action actually implements the handler. * The actions also provide the dynamic enablement. * * {@inheritDoc} */ @Override protected void makeActions(final IWorkbenchWindow window) { lock_toolbar = ActionFactory.LOCK_TOOL_BAR.create(window); register(lock_toolbar); edit_actionsets = ActionFactory.EDIT_ACTION_SETS.create(window); register(edit_actionsets); save = ActionFactory.SAVE.create(window); register(save); register(ActionFactory.SAVE_AS.create(window)); if (window.getWorkbench().getIntroManager().hasIntro()) register(ActionFactory.INTRO.create(window)); register(ActionFactory.HELP_CONTENTS.create(window)); } /** {@inheritDoc} */ @Override protected void fillMenuBar(final IMenuManager menubar) { // Placeholder for possible additions, rest filled from plugin.xml menubar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } /** {@inheritDoc} */ @Override protected void fillCoolBar(final ICoolBarManager coolbar) { // Set up the context Menu final MenuManager coolbarPopupMenuManager = new MenuManager(); coolbarPopupMenuManager.add(new ActionContributionItem(lock_toolbar)); coolbarPopupMenuManager.add(new ActionContributionItem(edit_actionsets)); coolbar.setContextMenuManager(coolbarPopupMenuManager); final IMenuService menuService = (IMenuService) window.getService(IMenuService.class); menuService.populateContributionManager(coolbarPopupMenuManager, "popup:windowCoolbarContextMenu"); //$NON-NLS-1$ // 'File' and 'User' sections of the cool bar final IToolBarManager file_bar = new ToolBarManager(); final IToolBarManager user_bar = new ToolBarManager(); coolbar.add(new ToolBarContributionItem(file_bar, IWorkbenchActionConstants.M_FILE)); coolbar.add(new ToolBarContributionItem(user_bar, TOOLBAR_USER)); // File 'new' and 'save' actions file_bar.add(ActionFactory.NEW.create(window)); file_bar.add(save); file_bar.add(new CoolItemGroupMarker(IWorkbenchActionConstants.FILE_END)); } }
package com.alibaba.otter.canal.client.adapter.es.config; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig.ESMapping; /** * ES * * @author rewerma 2018-11-01 * @version 1.0.0 */ public class SchemaItem { private Map<String, TableItem> aliasTableItems = new LinkedHashMap<>(); private Map<String, FieldItem> selectFields = new LinkedHashMap<>(); private String sql; private volatile Map<String, List<TableItem>> tableItemAliases; private volatile Map<String, List<FieldItem>> columnFields; private volatile Boolean allFieldsSimple; public void init() { this.getTableItemAliases(); this.getColumnFields(); this.isAllFieldsSimple(); aliasTableItems.values().forEach(tableItem -> { tableItem.getRelationTableFields(); tableItem.getRelationSelectFieldItems(); }); } public Map<String, TableItem> getAliasTableItems() { return aliasTableItems; } public void setAliasTableItems(Map<String, TableItem> aliasTableItems) { this.aliasTableItems = aliasTableItems; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } public Map<String, FieldItem> getSelectFields() { return selectFields; } public void setSelectFields(Map<String, FieldItem> selectFields) { this.selectFields = selectFields; } public String toSql() { // todo return null; } public Map<String, List<TableItem>> getTableItemAliases() { if (tableItemAliases == null) { synchronized (SchemaItem.class) { if (tableItemAliases == null) { tableItemAliases = new LinkedHashMap<>(); aliasTableItems.forEach((alias, tableItem) -> { List<TableItem> aliases = tableItemAliases .computeIfAbsent(tableItem.getTableName().toLowerCase(), k -> new ArrayList<>()); aliases.add(tableItem); }); } } } return tableItemAliases; } public Map<String, List<FieldItem>> getColumnFields() { if (columnFields == null) { synchronized (SchemaItem.class) { if (columnFields == null) { columnFields = new LinkedHashMap<>(); getSelectFields() .forEach((fieldName, fieldItem) -> fieldItem.getColumnItems().forEach(columnItem -> { // TableItem tableItem = getAliasTableItems().get(columnItem.getOwner()); // if (!tableItem.isSubQuery()) { //columnNameconcat('px',id) if(columnItem.getColumnName() != null) { List<FieldItem> fieldItems = columnFields.computeIfAbsent( columnItem.getOwner() + "." + columnItem.getColumnName(), k -> new ArrayList<>()); fieldItems.add(fieldItem); } // } else { // tableItem.getSubQueryFields().forEach(subQueryField -> { // List<FieldItem> fieldItems = columnFields.computeIfAbsent( // columnItem.getOwner() + "." + subQueryField.getColumn().getColumnName(), // k -> new ArrayList<>()); // fieldItems.add(fieldItem); })); } } } return columnFields; } public boolean isAllFieldsSimple() { if (allFieldsSimple == null) { synchronized (SchemaItem.class) { if (allFieldsSimple == null) { allFieldsSimple = true; for (FieldItem fieldItem : getSelectFields().values()) { if (fieldItem.isMethod() || fieldItem.isBinaryOp()) { allFieldsSimple = false; break; } } } } } return allFieldsSimple; } public TableItem getMainTable() { if (!aliasTableItems.isEmpty()) { return aliasTableItems.values().iterator().next(); } else { return null; } } public FieldItem getIdFieldItem(ESMapping mapping) { if (mapping.get_id() != null) { return getSelectFields().get(mapping.get_id()); } else { return getSelectFields().get(mapping.getPk()); } } public static class TableItem { private SchemaItem schemaItem; private String schema; private String tableName; private String alias; private String subQuerySql; private List<FieldItem> subQueryFields = new ArrayList<>(); private List<RelationFieldsPair> relationFields = new ArrayList<>(); private boolean main; private boolean subQuery; private volatile Map<FieldItem, List<FieldItem>> relationTableFields; private volatile List<FieldItem> relationSelectFieldItems; public TableItem(SchemaItem schemaItem){ this.schemaItem = schemaItem; } public SchemaItem getSchemaItem() { return schemaItem; } public void setSchemaItem(SchemaItem schemaItem) { this.schemaItem = schemaItem; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getSubQuerySql() { return subQuerySql; } public void setSubQuerySql(String subQuerySql) { this.subQuerySql = subQuerySql; } public boolean isMain() { return main; } public void setMain(boolean main) { this.main = main; } public boolean isSubQuery() { return subQuery; } public void setSubQuery(boolean subQuery) { this.subQuery = subQuery; } public List<FieldItem> getSubQueryFields() { return subQueryFields; } public void setSubQueryFields(List<FieldItem> subQueryFields) { this.subQueryFields = subQueryFields; } public List<RelationFieldsPair> getRelationFields() { return relationFields; } public void setRelationFields(List<RelationFieldsPair> relationFields) { this.relationFields = relationFields; } public Map<FieldItem, List<FieldItem>> getRelationTableFields() { if (relationTableFields == null) { synchronized (SchemaItem.class) { if (relationTableFields == null) { relationTableFields = new LinkedHashMap<>(); getRelationFields().forEach(relationFieldsPair -> { FieldItem leftFieldItem = relationFieldsPair.getLeftFieldItem(); FieldItem rightFieldItem = relationFieldsPair.getRightFieldItem(); FieldItem currentTableRelField = null; if (getAlias().equals(leftFieldItem.getOwner())) { currentTableRelField = leftFieldItem; } else if (getAlias().equals(rightFieldItem.getOwner())) { currentTableRelField = rightFieldItem; } if (currentTableRelField != null) { List<FieldItem> selectFieldItem = getSchemaItem().getColumnFields() .get(leftFieldItem.getOwner() + "." + leftFieldItem.getColumn().getColumnName()); if (selectFieldItem != null && !selectFieldItem.isEmpty()) { relationTableFields.put(currentTableRelField, selectFieldItem); } else { selectFieldItem = getSchemaItem().getColumnFields() .get(rightFieldItem.getOwner() + "." + rightFieldItem.getColumn().getColumnName()); if (selectFieldItem != null && !selectFieldItem.isEmpty()) { relationTableFields.put(currentTableRelField, selectFieldItem); } else { throw new UnsupportedOperationException( "Relation condition column must in select columns."); } } } }); } } } return relationTableFields; } public List<FieldItem> getRelationSelectFieldItems() { if (relationSelectFieldItems == null) { synchronized (SchemaItem.class) { if (relationSelectFieldItems == null) { List<FieldItem> relationSelectFieldItemsTmp = new ArrayList<>(); for (FieldItem fieldItem : schemaItem.getSelectFields().values()) { if (fieldItem.getOwners().contains(getAlias())) { relationSelectFieldItemsTmp.add(fieldItem); } } relationSelectFieldItems = relationSelectFieldItemsTmp; } } } return relationSelectFieldItems; } } public static class RelationFieldsPair { private FieldItem leftFieldItem; private FieldItem rightFieldItem; public RelationFieldsPair(FieldItem leftFieldItem, FieldItem rightFieldItem){ this.leftFieldItem = leftFieldItem; this.rightFieldItem = rightFieldItem; } public FieldItem getLeftFieldItem() { return leftFieldItem; } public void setLeftFieldItem(FieldItem leftFieldItem) { this.leftFieldItem = leftFieldItem; } public FieldItem getRightFieldItem() { return rightFieldItem; } public void setRightFieldItem(FieldItem rightFieldItem) { this.rightFieldItem = rightFieldItem; } } public static class FieldItem { private String fieldName; private String expr; private List<ColumnItem> columnItems = new ArrayList<>(); private List<String> owners = new ArrayList<>(); private boolean method; private boolean binaryOp; public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getExpr() { return expr; } public void setExpr(String expr) { this.expr = expr; } public List<ColumnItem> getColumnItems() { return columnItems; } public void setColumnItems(List<ColumnItem> columnItems) { this.columnItems = columnItems; } public boolean isMethod() { return method; } public void setMethod(boolean method) { this.method = method; } public boolean isBinaryOp() { return binaryOp; } public void setBinaryOp(boolean binaryOp) { this.binaryOp = binaryOp; } public List<String> getOwners() { return owners; } public void setOwners(List<String> owners) { this.owners = owners; } public void addColumn(ColumnItem columnItem) { columnItems.add(columnItem); } public ColumnItem getColumn() { if (!columnItems.isEmpty()) { return columnItems.get(0); } else { return null; } } public String getOwner() { if (!owners.isEmpty()) { return owners.get(0); } else { return null; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FieldItem fieldItem = (FieldItem) o; return fieldName != null ? fieldName.equals(fieldItem.fieldName) : fieldItem.fieldName == null; } @Override public int hashCode() { return fieldName != null ? fieldName.hashCode() : 0; } } public static class ColumnItem { private String owner; private String columnName; public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } } }
package com.abstratt.kirra.rest.resources; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import com.abstratt.kirra.Instance; import com.abstratt.kirra.TypeRef; import com.abstratt.kirra.rest.common.CommonHelper; import com.abstratt.kirra.rest.common.KirraContext; import com.abstratt.kirra.rest.common.Paths; @Path(Paths.INSTANCES_PATH) @Produces("application/json") @Consumes("application/json") public class InstanceListResource { @POST public Response createInstance(@PathParam("entityName") String entityName, String newInstanceRepresentation) { TypeRef entityRef = new TypeRef(entityName, TypeRef.TypeKind.Entity); AuthorizationHelper.checkInstanceCreationAuthorized(entityRef); Instance toCreate = CommonHelper.buildGson(null).create().fromJson(newInstanceRepresentation, Instance.class); toCreate.setEntityNamespace(entityRef.getNamespace()); toCreate.setEntityName(entityRef.getTypeName()); Instance created = KirraContext.getInstanceManagement().createInstance(toCreate); String json = CommonHelper.buildGson(ResourceHelper.resolve(true, Paths.ENTITIES, entityName, Paths.INSTANCES, created.getObjectId())) .create().toJson(created); return Response.status(Status.CREATED).entity(json).type(MediaType.APPLICATION_JSON).build(); } @GET public String getInstances(@PathParam("entityName") String entityName, @Context UriInfo uriInfo) { TypeRef entityRef = new TypeRef(entityName, TypeRef.TypeKind.Entity); AuthorizationHelper.checkEntityListAuthorized(entityRef); Map<String, List<Object>> criteria = new LinkedHashMap<String, List<Object>>(); List<String> builtInParameters = Arrays.asList("includesubtypes"); boolean includeSubtypes = false; for (Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) if (builtInParameters.contains(entry.getKey())) { if (entry.getKey().equals("includesubtypes")) { // carefully avoiding Restlet bug includeSubtypes = Boolean.parseBoolean(entry.getValue().stream().findAny().orElse(Boolean.FALSE.toString())); } } else criteria.put(entry.getKey(), new ArrayList<Object>(entry.getValue())); List<Instance> allInstances = KirraContext.getInstanceManagement().filterInstances(criteria, entityRef.getEntityNamespace(), entityRef.getTypeName(), true, includeSubtypes); InstanceList instanceList = new InstanceList(allInstances); return CommonHelper.buildGson(ResourceHelper.resolve(true, Paths.ENTITIES, entityName, Paths.INSTANCES)).create().toJson(instanceList); } }
/** * A set of service provider interfaces (SPI) each dealing with a separate concern within the * architecture. Each SPI is orthogonal and should not need direct dependency or interaction with * other SPI. It is the responsibility of the core to glue/mediate such communication in a * decoupled fashion. This enbles services to be developed in parallel by distributed teams * under a common and well-defined contract. * <p> * Providers are free to implement any SPI. Such third-party services can be registered * and automatically bound to core functionality when the application is loaded. * The mechanism used for this purpose is the standard {@link java.util.ServiceLoader}. * <p> * A Test Compability Kit (TCK) is available for providers to verify that their * implementation behaves correctly. * </p> * <p> * Each service have a default implementation that will be used if no other is provided. * </p> * * <p> * The following SPIs are available: * <ul> * <li> {@link org.deephacks.tools4j.config.spi.BeanManager}</li> * <li> {@link org.deephacks.tools4j.config.spi.SchemaManager}</li> * <li> {@link org.deephacks.tools4j.config.spi.ValidationManager}</li> * <li> {@link org.deephacks.tools4j.support.conversion.Converter}</li> * This interface takes care of converting configuration property types to-and-from String * (which is the format for storing property values). * </ul> * </p> * * <h2>Usage</h2> * * TODO: */ package org.deephacks.tools4j.config.spi; ;
package org.jboss.as.connector.deployers.ds.processors; import static org.jboss.as.connector.logging.ConnectorLogger.SUBSYSTEM_DATASOURCES_LOGGER; import java.sql.Driver; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.jboss.as.connector.logging.ConnectorLogger; import org.jboss.as.connector.logging.ConnectorMessages; import org.jboss.as.connector.services.driver.registry.DriverRegistry; import org.jboss.as.connector.subsystems.datasources.AbstractDataSourceService; import org.jboss.as.connector.subsystems.datasources.DataSourceReferenceFactoryService; import org.jboss.as.connector.subsystems.datasources.DataSourceStatisticsListener; import org.jboss.as.connector.subsystems.datasources.DataSourcesExtension; import org.jboss.as.connector.subsystems.datasources.DataSourcesSubsystemProviders; import org.jboss.as.connector.subsystems.datasources.LocalDataSourceService; import org.jboss.as.connector.subsystems.datasources.ModifiableDataSource; import org.jboss.as.connector.subsystems.datasources.ModifiableXaDataSource; import org.jboss.as.connector.subsystems.datasources.Util; import org.jboss.as.connector.subsystems.datasources.XMLDataSourceRuntimeHandler; import org.jboss.as.connector.subsystems.datasources.XMLXaDataSourceRuntimeHandler; import org.jboss.as.connector.subsystems.datasources.XaDataSourceService; import org.jboss.as.connector.util.ConnectorServices; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ServiceVerificationHandler; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.service.BinderService; import org.jboss.as.naming.service.NamingService; import org.jboss.as.security.service.SubjectFactoryService; import org.jboss.as.server.Services; import org.jboss.as.server.deployment.DeploymentModelUtils; 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.jca.common.api.metadata.Defaults; import org.jboss.jca.common.api.metadata.ds.DataSources; import org.jboss.jca.common.api.metadata.ds.v12.DataSource; import org.jboss.jca.common.api.metadata.ds.v12.DsXaPool; import org.jboss.jca.common.api.metadata.ds.v12.XaDataSource; import org.jboss.jca.common.metadata.ds.v12.DsXaPoolImpl; import org.jboss.jca.core.api.connectionmanager.ccm.CachedConnectionManager; import org.jboss.jca.core.api.management.ManagementRepository; import org.jboss.jca.core.spi.transaction.TransactionIntegration; import org.jboss.msc.service.AbstractServiceListener; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.security.SubjectFactory; /** * Picks up -ds.xml deployments * * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a> */ public class DsXmlDeploymentInstallProcessor implements DeploymentUnitProcessor { private static final String DATA_SOURCE = "data-source"; private static final String XA_DATA_SOURCE = "xa-data-source"; private static final String CONNECTION_PROPERTIES = "connection-properties"; private static final String XA_CONNECTION_PROPERTIES = "xa-datasource-properties"; private static final PathAddress SUBSYSTEM_ADDRESS = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, DataSourcesExtension.SUBSYSTEM_NAME)); private static final PathAddress DATASOURCE_ADDRESS; private static final PathAddress XA_DATASOURCE_ADDRESS; static { XA_DATASOURCE_ADDRESS = SUBSYSTEM_ADDRESS.append(PathElement.pathElement(XA_DATA_SOURCE)); DATASOURCE_ADDRESS = SUBSYSTEM_ADDRESS.append(PathElement.pathElement(DATA_SOURCE)); } /** * Process a deployment for standard ra deployment files. Will parse the xml * file and attach an configuration discovered during processing. * * @param phaseContext the deployment unit context * @throws org.jboss.as.server.deployment.DeploymentUnitProcessingException * */ @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final List<DataSources> dataSourcesList = deploymentUnit.getAttachmentList(DsXmlDeploymentParsingProcessor.DATA_SOURCES_ATTACHMENT_KEY); for(DataSources dataSources : dataSourcesList) { if (dataSources.getDrivers() != null && dataSources.getDrivers().size() > 0) { ConnectorLogger.DS_DEPLOYER_LOGGER.driversElementNotSupported(deploymentUnit.getName()); } ServiceTarget serviceTarget = phaseContext.getServiceTarget(); ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler(); if (dataSources.getDataSource() != null && dataSources.getDataSource().size() > 0) { for (int i = 0; i < dataSources.getDataSource().size(); i++) { DataSource ds = (DataSource)dataSources.getDataSource().get(i); if (ds.isEnabled() && ds.getDriver() != null) { try { final String jndiName = Util.cleanJndiName(ds.getJndiName(), ds.isUseJavaContext()); LocalDataSourceService lds = new LocalDataSourceService(jndiName); lds.getDataSourceConfigInjector().inject(buildDataSource(ds)); final String dsName = ds.getJndiName(); final PathAddress addr = getDataSourceAddress(dsName, deploymentUnit, false); installManagementModel(ds, deploymentUnit, addr); startDataSource(lds, jndiName, ds.getDriver(), serviceTarget, verificationHandler, getRegistration(false, deploymentUnit), getResource(dsName, false, deploymentUnit), dsName); } catch (Exception e) { throw ConnectorMessages.MESSAGES.exceptionDeployingDatasource(e, ds.getJndiName()); } } else { ConnectorLogger.DS_DEPLOYER_LOGGER.debugf("Ignoring: %s", ds.getJndiName()); } } } if (dataSources.getXaDataSource() != null && dataSources.getXaDataSource().size() > 0) { for (int i = 0; i < dataSources.getXaDataSource().size(); i++) { XaDataSource xads = (XaDataSource)dataSources.getXaDataSource().get(i); if (xads.isEnabled() && xads.getDriver() != null) { try { String jndiName = Util.cleanJndiName(xads.getJndiName(), xads.isUseJavaContext()); XaDataSourceService xds = new XaDataSourceService(jndiName); xds.getDataSourceConfigInjector().inject(buildXaDataSource(xads)); final String dsName = xads.getJndiName(); final PathAddress addr = getDataSourceAddress(dsName, deploymentUnit, true); installManagementModel(xads, deploymentUnit, addr); startDataSource(xds, jndiName, xads.getDriver(), serviceTarget, verificationHandler, getRegistration(true, deploymentUnit), getResource(dsName, true, deploymentUnit), dsName); } catch (Exception e) { throw ConnectorMessages.MESSAGES.exceptionDeployingDatasource(e, xads.getJndiName()); } } else { ConnectorLogger.DS_DEPLOYER_LOGGER.debugf("Ignoring %s", xads.getJndiName()); } } } } } private void installManagementModel(final DataSource ds, final DeploymentUnit deploymentUnit, final PathAddress addr) { XMLDataSourceRuntimeHandler.INSTANCE.registerDataSource(addr, ds); deploymentUnit.createDeploymentSubModel(DataSourcesExtension.SUBSYSTEM_NAME, addr.getLastElement()); if (ds.getConnectionProperties() != null) { for (final Map.Entry<String, String> prop : ds.getConnectionProperties().entrySet()) { PathAddress registration = PathAddress.pathAddress(addr.getLastElement(), PathElement.pathElement(CONNECTION_PROPERTIES, prop.getKey())); createDeploymentSubModel(registration, deploymentUnit); } } } private void installManagementModel(final XaDataSource ds, final DeploymentUnit deploymentUnit, final PathAddress addr) { XMLXaDataSourceRuntimeHandler.INSTANCE.registerDataSource(addr, ds); deploymentUnit.createDeploymentSubModel(DataSourcesExtension.SUBSYSTEM_NAME, addr.getLastElement()); if (ds.getXaDataSourceProperty() != null) { for (final Map.Entry<String, String> prop : ds.getXaDataSourceProperty().entrySet()) { PathAddress registration = PathAddress.pathAddress(addr.getLastElement(), PathElement.pathElement(XA_CONNECTION_PROPERTIES, prop.getKey())); createDeploymentSubModel(registration, deploymentUnit); } } } private void undeployDataSource(final DataSource ds, final DeploymentUnit deploymentUnit) { final PathAddress addr = getDataSourceAddress(ds.getJndiName(), deploymentUnit, false); XMLDataSourceRuntimeHandler.INSTANCE.unregisterDataSource(addr); } private void undeployXaDataSource(final XaDataSource ds, final DeploymentUnit deploymentUnit) { final PathAddress addr = getDataSourceAddress(ds.getJndiName(), deploymentUnit, true); XMLXaDataSourceRuntimeHandler.INSTANCE.unregisterDataSource(addr); } public void undeploy(final DeploymentUnit context) { final List<DataSources> dataSourcesList = context.getAttachmentList(DsXmlDeploymentParsingProcessor.DATA_SOURCES_ATTACHMENT_KEY); for (final DataSources dataSources : dataSourcesList) { if (dataSources.getDataSource() != null) { for (int i = 0; i < dataSources.getDataSource().size(); i++) { DataSource ds = (DataSource)dataSources.getDataSource().get(i); undeployDataSource(ds, context); } } if (dataSources.getXaDataSource() != null) { for (int i = 0; i < dataSources.getXaDataSource().size(); i++) { XaDataSource xads = (XaDataSource)dataSources.getXaDataSource().get(i); undeployXaDataSource(xads, context); } } } } private ModifiableDataSource buildDataSource(DataSource ds) throws org.jboss.jca.common.api.validator.ValidateException { return new ModifiableDataSource(ds.getConnectionUrl(), ds.getDriverClass(), ds.getDataSourceClass(), ds.getDriver(), ds.getTransactionIsolation(), ds.getConnectionProperties(), ds.getTimeOut(), ds.getSecurity(), ds.getStatement(), ds.getValidation(), ds.getUrlDelimiter(), ds.getUrlSelectorStrategyClassName(), ds.getNewConnectionSql(), ds.isUseJavaContext(), ds.getPoolName(), ds.isEnabled(), ds.getJndiName(), ds.isSpy(), ds.isUseCcm(), ds.isJTA(), ds.getPool()); } private ModifiableXaDataSource buildXaDataSource(XaDataSource xads) throws org.jboss.jca.common.api.validator.ValidateException { final DsXaPool xaPool; if (xads.getXaPool() == null) { xaPool = new DsXaPoolImpl(Defaults.MIN_POOL_SIZE, Defaults.INITIAL_POOL_SIZE, Defaults.MAX_POOL_SIZE, Defaults.PREFILL, Defaults.USE_STRICT_MIN, Defaults.FLUSH_STRATEGY, Defaults.IS_SAME_RM_OVERRIDE, Defaults.INTERLEAVING, Defaults.PAD_XID, Defaults.WRAP_XA_RESOURCE, Defaults.NO_TX_SEPARATE_POOL, Defaults.ALLOW_MULTIPLE_USERS, null, null); } else { final DsXaPool p = xads.getXaPool(); xaPool = new DsXaPoolImpl(getDef(p.getMinPoolSize(), Defaults.MIN_POOL_SIZE), getDef(p.getInitialPoolSize(), Defaults.INITIAL_POOL_SIZE), getDef(p.getMaxPoolSize(), Defaults.MAX_POOL_SIZE), getDef(p.isPrefill(), Defaults.PREFILL), getDef(p.isUseStrictMin(), Defaults.USE_STRICT_MIN), getDef(p.getFlushStrategy(), Defaults.FLUSH_STRATEGY), getDef(p.isSameRmOverride(), Defaults.IS_SAME_RM_OVERRIDE), getDef(p.isInterleaving(), Defaults.INTERLEAVING), getDef(p.isPadXid(), Defaults.PAD_XID) , getDef(p.isWrapXaResource(), Defaults.WRAP_XA_RESOURCE), getDef(p.isNoTxSeparatePool(), Defaults.NO_TX_SEPARATE_POOL), getDef(p.isAllowMultipleUsers(), Defaults.ALLOW_MULTIPLE_USERS), p.getCapacity(), p.getConnectionListener()); } return new ModifiableXaDataSource(xads.getTransactionIsolation(), xads.getTimeOut(), xads.getSecurity(), xads.getStatement(), xads.getValidation(), xads.getUrlDelimiter(), xads.getUrlProperty(), xads.getUrlSelectorStrategyClassName(), xads.isUseJavaContext(), xads.getPoolName(), xads.isEnabled(), xads.getJndiName(), xads.isSpy(), xads.isUseCcm(), xads.getXaDataSourceProperty(), xads.getXaDataSourceClass(), xads.getDriver(), xads.getNewConnectionSql(), xaPool, xads.getRecovery()); } private <T> T getDef(T value, T def) { return value != null ? value : def; } private void startDataSource(final AbstractDataSourceService dataSourceService, final String jndiName, final String driverName, final ServiceTarget serviceTarget, final ServiceVerificationHandler verificationHandler, final ManagementResourceRegistration registration, final Resource resource, final String managementName) { final ServiceName dataSourceServiceName = AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName); final ServiceBuilder<?> dataSourceServiceBuilder = Services.addServerExecutorDependency( serviceTarget.addService(dataSourceServiceName, dataSourceService), dataSourceService.getExecutorServiceInjector(), false) .addDependency(ConnectorServices.TRANSACTION_INTEGRATION_SERVICE, TransactionIntegration.class, dataSourceService.getTransactionIntegrationInjector()) .addDependency(ConnectorServices.MANAGEMENT_REPOSITORY_SERVICE, ManagementRepository.class, dataSourceService.getManagementRepositoryInjector()) .addDependency(SubjectFactoryService.SERVICE_NAME, SubjectFactory.class, dataSourceService.getSubjectFactoryInjector()) .addDependency(ConnectorServices.CCM_SERVICE, CachedConnectionManager.class, dataSourceService.getCcmInjector()) .addDependency(ConnectorServices.JDBC_DRIVER_REGISTRY_SERVICE, DriverRegistry.class, dataSourceService.getDriverRegistryInjector()).addDependency(NamingService.SERVICE_NAME); //Register an empty override model regardless of we're enabled or not - the statistics listener will add the relevant childresources if (registration.isAllowsOverride()) { ManagementResourceRegistration overrideRegistration = registration.getOverrideModel(managementName); if (overrideRegistration == null) { overrideRegistration = registration.registerOverrideModel(managementName, DataSourcesSubsystemProviders.OVERRIDE_DS_DESC); } dataSourceServiceBuilder.addListener(new DataSourceStatisticsListener(overrideRegistration, resource, managementName)); } // else should probably throw an ISE or something final ServiceName driverServiceName = ServiceName.JBOSS.append("jdbc-driver", driverName.replaceAll("\\.", "_")); if (driverServiceName != null) { dataSourceServiceBuilder.addDependency(driverServiceName, Driver.class, dataSourceService.getDriverInjector()); } final DataSourceReferenceFactoryService referenceFactoryService = new DataSourceReferenceFactoryService(); final ServiceName referenceFactoryServiceName = DataSourceReferenceFactoryService.SERVICE_NAME_BASE .append(jndiName); final ServiceBuilder<?> referenceBuilder = serviceTarget.addService(referenceFactoryServiceName, referenceFactoryService).addDependency(dataSourceServiceName, javax.sql.DataSource.class, referenceFactoryService.getDataSourceInjector()); final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName); final BinderService binderService = new BinderService(bindInfo.getBindName()); final ServiceBuilder<?> binderBuilder = serviceTarget .addService(bindInfo.getBinderServiceName(), binderService) .addDependency(referenceFactoryServiceName, ManagedReferenceFactory.class, binderService.getManagedObjectInjector()) .addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()).addListener(new AbstractServiceListener<Object>() { public void transition(final ServiceController<?> controller, final ServiceController.Transition transition) { switch (transition) { case STARTING_to_UP: { SUBSYSTEM_DATASOURCES_LOGGER.boundDataSource(jndiName); break; } case START_REQUESTED_to_DOWN: { SUBSYSTEM_DATASOURCES_LOGGER.unboundDataSource(jndiName); break; } case REMOVING_to_REMOVED: { SUBSYSTEM_DATASOURCES_LOGGER.debugf("Removed JDBC Data-source [%s]", jndiName); break; } } } }); dataSourceServiceBuilder.setInitialMode(ServiceController.Mode.ACTIVE).addListener(verificationHandler).install(); referenceBuilder.setInitialMode(ServiceController.Mode.ACTIVE).addListener(verificationHandler).install(); binderBuilder.setInitialMode(ServiceController.Mode.ACTIVE).addListener(verificationHandler).install(); } private static PathAddress getDataSourceAddress(final String jndiName, DeploymentUnit deploymentUnit, boolean xa) { List<PathElement> elements = new ArrayList<PathElement>(); if (deploymentUnit.getParent() == null) { elements.add(PathElement.pathElement(ModelDescriptionConstants.DEPLOYMENT, deploymentUnit.getName())); } else { elements.add(PathElement.pathElement(ModelDescriptionConstants.DEPLOYMENT, deploymentUnit.getParent().getName())); elements.add(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT, deploymentUnit.getName())); } elements.add(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, DataSourcesExtension.SUBSYSTEM_NAME)); if (xa) { elements.add(PathElement.pathElement(XA_DATA_SOURCE, jndiName)); } else { elements.add(PathElement.pathElement(DATA_SOURCE, jndiName)); } return PathAddress.pathAddress(elements); } static ManagementResourceRegistration createDeploymentSubModel(final PathAddress address, final DeploymentUnit unit) { final Resource root = unit.getAttachment(DeploymentModelUtils.DEPLOYMENT_RESOURCE); synchronized (root) { final ManagementResourceRegistration registration = unit.getAttachment(DeploymentModelUtils.MUTABLE_REGISTRATION_ATTACHMENT); final PathAddress subsystemAddress = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, DataSourcesExtension.SUBSYSTEM_NAME)); final Resource subsystem = getOrCreate(root, subsystemAddress); final ManagementResourceRegistration subModel = registration.getSubModel(subsystemAddress.append(address)); if (subModel == null) { throw new IllegalStateException(address.toString()); } getOrCreate(subsystem, address); return subModel; } } static Resource getOrCreate(final Resource parent, final PathAddress address) { Resource current = parent; for (final PathElement element : address) { synchronized (current) { if (current.hasChild(element)) { current = current.requireChild(element); } else { final Resource resource = Resource.Factory.create(); current.registerChild(element, resource); current = resource; } } } return current; } private Resource getResource(final String dsName, final boolean xa, final DeploymentUnit unit) { final Resource root = unit.getAttachment(DeploymentModelUtils.DEPLOYMENT_RESOURCE); final String key = xa ? XA_DATA_SOURCE : DATA_SOURCE; final PathAddress address = PathAddress.pathAddress(PathElement.pathElement(key, dsName)); synchronized (root) { final Resource subsystem = getOrCreate(root, SUBSYSTEM_ADDRESS); return getOrCreate(subsystem, address); } } private ManagementResourceRegistration getRegistration(final boolean xa, final DeploymentUnit unit) { final Resource root = unit.getAttachment(DeploymentModelUtils.DEPLOYMENT_RESOURCE); synchronized (root) { ManagementResourceRegistration registration = unit.getAttachment(DeploymentModelUtils.MUTABLE_REGISTRATION_ATTACHMENT); final PathAddress address = xa ? XA_DATASOURCE_ADDRESS : DATASOURCE_ADDRESS; ManagementResourceRegistration subModel = registration.getSubModel(address); if (subModel == null) { throw new IllegalStateException(address.toString()); } return subModel; } } }
package org.hisp.dhis.android.core.datavalue; import org.hisp.dhis.android.core.D2; import org.hisp.dhis.android.core.common.D2Factory; import org.hisp.dhis.android.core.data.database.AbsStoreTestCase; import org.hisp.dhis.android.core.data.server.RealServerMother; import org.junit.Before; import org.junit.Test; import java.io.IOException; public class AggregatedDataCallRealIntegrationShould extends AbsStoreTestCase { /** * A quick integration test that is probably flaky, but will help with finding bugs related to * the * metadataSyncCall. It works against the demo server. */ private D2 d2; @Before @Override public void setUp() throws IOException { super.setUp(); d2 = D2Factory.create(RealServerMother.url, databaseAdapter()); } /* How to extract database from tests: edit: AbsStoreTestCase.java (adding database name.) DbOpenHelper dbOpenHelper = new DbOpenHelper(InstrumentationRegistry.getTargetContext() .getApplicationContext(), "test.db"); make a debugger break point where desired (after sync complete) Then while on the breakpoint : Android/platform-tools/adb pull /data/user/0/org.hisp.dhis.android.test/databases/test.db test.db in datagrip: pragma foreign_keys = on; pragma foreign_key_check;*/ //This test is uncommented because technically it is flaky. //It depends on a live server to operate and the login is hardcoded here. //Uncomment in order to quickly test changes vs a real server, but keep it uncommented after. //@Test public void response_successful_on_sync_data_once() throws Exception { d2.logout().call(); d2.logIn("android", "Android123").call(); d2.syncMetaData().call(); d2.syncAggregatedData().call(); } //@Test public void response_successful_on_sync_data_value_two_times() throws Exception { d2.logout().call(); d2.logIn("android", "Android123").call(); d2.syncMetaData().call(); d2.syncAggregatedData().call(); d2.syncMetaData().call(); d2.syncAggregatedData().call(); } @Test public void stub() { } }
package net.sf.taverna.t2.security.credentialmanager.ui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.math.BigInteger; import java.util.HashMap; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; //import javax.swing.event.ListSelectionEvent; //import javax.swing.event.ListSelectionListener; import javax.swing.JSeparator; import java.io.IOException; import java.util.Vector; import java.util.Enumeration; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import javax.security.auth.x500.X500Principal; import net.sf.taverna.t2.security.credentialmanager.CMException; import net.sf.taverna.t2.security.credentialmanager.CMX509Util; import org.apache.log4j.Logger; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.misc.NetscapeCertType; /** * Displays the details of a X.509 certificate. * * @author Alexandra Nenadic */ public class ViewCertDetailsDialog extends JDialog { private static final long serialVersionUID = 4945018031152689088L; /** * Log4J Logger */ private static Logger logger = Logger.getLogger(ViewCertDetailsDialog.class); /** Stores certificate to display */ private X509Certificate cert; /** Stores list of serviceURLs to display */ private Vector<String> serviceURLs; /** * Creates new ViewCertDetailsDialog dialog where the parent is a frame. * * @param parent Parent frame * @param sTitle The dialog title * @param bModal Is dialog modal? * @param cert Certificate to display * @param urlList List of serviceURLs associated with this entry * @throws CMException A problem was encountered getting the * certificate's details */ public ViewCertDetailsDialog(JFrame parent, String sTitle, boolean bModal, X509Certificate crt, Vector<String> urlList) throws CMException { super(parent, sTitle, bModal); cert = crt; serviceURLs = urlList; initComponents(); } /** * Creates new ViewCertDetailsDialog dialog where the parent is a dialog. * * @param parent Parent frame * @param sTitle The dialog title * @param bModal Is dialog modal? * @param cert Certificate to display * @param urlList List of serviceURLs associated with this entry * @throws CMException A problem was encountered getting the * certificate's details */ public ViewCertDetailsDialog(JDialog parent, String sTitle, boolean bModal, X509Certificate crt, Vector<String> urlList) throws CMException { super(parent, sTitle, bModal); cert = crt; serviceURLs = urlList; initComponents(); } /** * Initialise the dialog's GUI components. * * @throws CMException A problem was encountered getting the * certificates' details */ private void initComponents() throws CMException { // Certificate details: // Grid Bag Constraints templates for labels (column 1) and // values (column 2) of certificate details GridBagConstraints gbcLabel = new GridBagConstraints(); gbcLabel.gridx = 0; gbcLabel.ipadx = 20; gbcLabel.gridwidth = 1; gbcLabel.gridheight = 1; gbcLabel.insets = new Insets(2, 15, 2, 2); gbcLabel.anchor = GridBagConstraints.LINE_START; GridBagConstraints gbcValue = new GridBagConstraints(); gbcValue.gridx = 1; gbcValue.gridwidth = 1; gbcValue.gridheight = 1; gbcValue.insets = new Insets(2, 5, 2, 2); gbcValue.anchor = GridBagConstraints.LINE_START; // Netscape Certificate Type non-critical extension (if any) // defines the intended uses of the certificate - to make it look like // firefox's view certificate dialog /** * Get the digest of a message as a formatted String. * * @param bMessage The message to digest * @param digestType The message digest algorithm * @return The message digest * @throws CMException If there was a problem generating the message * digest */ public static String getMessageDigest(byte[] bMessage, String digestType) throws CMException { // Create message digest object using the supplied algorithm MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(digestType); } catch (NoSuchAlgorithmException ex) { throw new CMException("Failed to create message digest.", ex); } // Create raw message digest byte[] bFingerPrint = messageDigest.digest(bMessage); // Place the raw message digest into a StringBuffer as a Hex number StringBuffer strBuff = new StringBuffer( new BigInteger(1, bFingerPrint).toString(16).toUpperCase()); // Odd number of characters so add in a padding "0" if ((strBuff.length() % 2) != 0) { strBuff.insert(0, '0'); } // Place colons at every two hex characters if (strBuff.length() > 2) { for (int iCnt = 2; iCnt < strBuff.length(); iCnt += 3) { strBuff.insert(iCnt, ':'); } } // Return the formatted message digest return strBuff.toString(); } /** * Gets the intended certificate uses, i.e. Netscape Certificate Type extension (2.16.840.1.113730.1.1) * value as a string * @param value Extension value as a DER-encoded OCTET string * @return Extension value as a string */ private String getIntendedUses(byte[] value) { // Netscape Certificate Types (2.16.840.1.113730.1.1) int[] INTENDED_USES = new int[] { NetscapeCertType.sslClient, NetscapeCertType.sslServer, NetscapeCertType.smime, NetscapeCertType.objectSigning, NetscapeCertType.reserved, NetscapeCertType.sslCA, NetscapeCertType.smimeCA, NetscapeCertType.objectSigningCA, }; // Netscape Certificate Type strings (2.16.840.1.113730.1.1) HashMap<String, String> INTENDED_USES_STRINGS = new HashMap<String, String> (); INTENDED_USES_STRINGS.put("128", "SSL Client"); INTENDED_USES_STRINGS.put("64", "SSL Server"); INTENDED_USES_STRINGS.put("32", "S/MIME"); INTENDED_USES_STRINGS.put("16", "Object Signing"); INTENDED_USES_STRINGS.put("8", "Reserved"); INTENDED_USES_STRINGS.put("4", "SSL CA"); INTENDED_USES_STRINGS.put("2", "S/MIME CA"); INTENDED_USES_STRINGS.put("1", "Object Signing CA"); // Get octet string from extension value ASN1OctetString fromByteArray = new DEROctetString(value); byte[] octets = fromByteArray.getOctets(); DERBitString fromByteArray2 = new DERBitString(octets); int val = new NetscapeCertType(fromByteArray2).intValue(); StringBuffer strBuff = new StringBuffer(); for (int i = 0, len = INTENDED_USES.length; i < len; i++) { int use = INTENDED_USES[i]; if ((val & use) == use) { strBuff.append(INTENDED_USES_STRINGS.get(String.valueOf(use))+", \n"); } } // remove the last ", \n" from the end of the buffer String str = strBuff.toString(); str = str.substring(0, str.length()-3); return str; } /** * OK button pressed. */ private void okPressed() { closeDialog(); } /** * Closes the View Certificate Entry dialog. */ private void closeDialog() { setVisible(false); dispose(); } }
package org.javacint.settings; import com.siemens.icm.io.file.FileConnection; import java.io.*; import java.util.*; import javax.microedition.io.Connector; import org.javacint.common.Strings; import org.javacint.logging.Logger; public class Settings { private static Hashtable settings; private static String fileName = "settings.txt"; private static final Vector consumers = new Vector(); /** * APN setting */ public static final String SETTING_APN = "apn"; public static final String SETTING_CODE = "code"; public static final String SETTING_MANAGERSPHONE = "phoneManager"; public static final String SETTING_IMSI = "imsi"; public static final String SETTING_PINCODE = "pincode"; /** * JADUrl setting */ public static final String SETTING_JADURL = "jadurl"; private static boolean madeSomeChanges = false; private static boolean loading; public static synchronized void setFilename(String filename) { fileName = filename; settings = null; } public static void loading(boolean l) { loading = l; } public static String getFilename() { return fileName; } /** * Load settings */ public static synchronized void load() { if (Logger.BUILD_DEBUG) { Logger.log("Settings.load();"); } StringBuffer buffer = new StringBuffer(); Hashtable newSettings = getDefaultSettings(); try { FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ); if (!fc.exists()) { if (Logger.BUILD_WARNING) { Logger.log("Settings.load: File \"" + fileName + "\" doesn\'t exist!"); } fc = (FileConnection) Connector.open("file:///a:/" + fileName + ".old", Connector.READ); if (fc.exists()) { if (Logger.BUILD_WARNING) { Logger.log("Settings.load: But \"" + fileName + ".old\" exists ! "); } } else { return; } } InputStream is = fc.openInputStream(); while (is.available() > 0) { int c = is.read(); if (c == '\n') { loadLine(newSettings, buffer.toString()); buffer.setLength(0); } else { buffer.append((char) c); } } is.close(); fc.close(); } catch (IOException ex) { // The exception we shoud have is at first launch : // There shouldn't be any file to read from if (Logger.BUILD_CRITICAL) { Logger.log("Settings.Load", ex); } } finally { settings = newSettings; } } /** * Treat each line of the file * * @param def Default settings * @param line Line to parse */ private static void loadLine(Hashtable settings, String line) { // if (Logger.BUILD_VERBOSE) { // Logger.log("loadTreatLine( [...], \"" + line + "\" );"); String[] spl = Strings.split('=', line); String key = spl[0]; String value = spl[1]; // If default settings hashTable contains this key // we can use this value if (settings.containsKey(key)) { settings.remove(key); settings.put(key, value); // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.loadLine: " + key + "=" + value); } } public static void onSettingsChanged(String[] names) { onSettingsChanged(names, null); } /** * Launch an event when some settings * * @param names Names of the settings */ public static void onSettingsChanged(String[] names, SettingsProvider caller) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.onSettingsChanged( String[" + names.length + "] names );"); try { synchronized (consumers) { for (Enumeration en = consumers.elements(); en.hasMoreElements();) { SettingsProvider cons = (SettingsProvider) en.nextElement(); if (cons == caller) { continue; } cons.settingsChanged(names); } } } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.OnSeettingChanged", ex); } } } /** * Get default settings * * @return Default settings Hashtable */ public static Hashtable getDefaultSettings() { Hashtable defaultSettings = new Hashtable(); // Code is mandatory defaultSettings.put(SETTING_CODE, "1234"); // APN is mandatory defaultSettings.put(SETTING_APN, "0"); // IMSI is mandatory defaultSettings.put(SETTING_IMSI, "0"); synchronized (consumers) { for (Enumeration en = consumers.elements(); en.hasMoreElements();) { SettingsProvider cons = (SettingsProvider) en.nextElement(); cons.getDefaultSettings(defaultSettings); } } return defaultSettings; } /** * Add a settings consumer class * * @param consumer Consumer of settings */ public static void addProvider(SettingsProvider consumer) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.addSettingsConsumer( " + consumer + " );"); if (!loading) { throw new RuntimeException("Settings.addSettingsConsumer: We're not loading anymore !"); } synchronized (consumers) { consumers.addElement(consumer); settings = null; } } /** * Remove a settings consumer class * * @param consumer Consumer of settings */ public static void removeSettingsConsumer(SettingsProvider consumer) { synchronized (consumers) { if (consumers.contains(consumer)) { consumers.removeElement(consumer); } settings = null; } } /** * Reset all settings */ public synchronized static void reset() { try { FileConnection fc = (FileConnection) Connector.open("file:///a:/" + fileName, Connector.READ_WRITE); if (fc.exists()) { fc.delete(); } load(); settings = null; } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.resetErything", ex); } } } /** * Save setttings */ public static synchronized void save() { synchronized (Settings.class) { // if (Logger.BUILD_DEBUG) { // Logger.log("Settings.save();", true); // If there's no settings, we shouldn't have to save anything if (settings == null) { return; } // If no changes were made, we shouldn't have to save anything if (!madeSomeChanges) { return; } try { Hashtable defSettings = getDefaultSettings(); String fileNameTmp = fileName + ".tmp"; String fileNameOld = fileName + ".old"; String settingFileUrl = "file:///a:/" + fileName; String settingFileUrlTmp = "file:///a:/" + fileNameTmp; String settingFileUrlOld = "file:///a:/" + fileNameOld; // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Opening \"" + settingFileUrlTmp + "\"..."); FileConnection fc = (FileConnection) Connector.open(settingFileUrlTmp, Connector.READ_WRITE); //fc = (FileConnection) Connector.open("file:///" + _fileName, Connector.READ_WRITE); if (fc.exists()) { fc.delete(); } fc.create(); OutputStream os = fc.openOutputStream(); Enumeration e = defSettings.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = (String) settings.get(key); String defValue = (String) defSettings.get(key); if ( // if there is a default value defValue != null && // and // the value isn't the same as the default value defValue.compareTo(value) != 0) { String line = key + "=" + value + '\n'; // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save.line: " + line); os.write(line.getBytes()); } } os.flush(); os.close(); { // We move the current setting file to the old one FileConnection currentFile = (FileConnection) Connector.open(settingFileUrl, Connector.READ_WRITE); // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Renaming \"" + settingFileUrl + "\" to \"" + fileNameOld + "\""); if (currentFile.exists()) { { // We delete the old setting file // if ( Logger.BUILD_DEBUG ) { // Logger.log("Settings.save: Deleting \"" + settingFileUrlOld + "\""); FileConnection oldFile = (FileConnection) Connector.open(settingFileUrlOld, Connector.READ_WRITE); if (oldFile.exists()) { oldFile.delete(); } } currentFile.rename(fileNameOld); } } { // We move the tmp file to the current setting file // if ( Logger.BUILD_DEBUG ) { // Logger.log("Setting.save: Renaming \"" + settingFileUrlTmp + "\" to \"" + _fileName + "\""); fc.rename(fileName); fc.close(); } // If we savec the file, we can reset the madeSomeChanges information madeSomeChanges = false; } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("Settings.Save", ex, true); } } } } /** * Init (and ReInit) method */ private static void checkLoad() { if (settings == null) { load(); } } /** * Get a setting's value as a String * * @param key Key Name of the setting * @return String value of the setting */ public static synchronized String get(String key) { return (String) getSettings().get(key); } /** * Get all the settings * * @return All the settings */ public static synchronized Hashtable getSettings() { checkLoad(); return settings; } /** * Set a setting * * @param key Setting to set * @param value Value of the setting */ public static synchronized void set(String key, String value) { if (Logger.BUILD_DEBUG) { Logger.log("Settings.setSetting( \"" + key + "\", \"" + value + "\" );"); } if (setWithoutEvent(key, value)) { onSettingsChanged(new String[]{key}); } } public void set(String key, int value) { set(key, "" + value); } /** * Set a setting without launching the onSettingsChange method * * @param key Setting to set * @param value Value of the setting * @return If setting was actually changed */ public static synchronized boolean setWithoutEvent(String key, String value) { Hashtable table = getSettings(); if (table.containsKey(key)) { String previousValue = (String) table.get(key); if (previousValue.compareTo(value) == 0) { return false; } } else { return false; } if (loading) { throw new RuntimeException("Settings.setSettingWithoutChangeEvent: You can't change a setting while loading !"); } table.put(key, value); madeSomeChanges = true; return true; } /** * Get a setting's value as an int * * @param key Key Name of the setting * @return Integer value of the setting * @throws java.lang.NumberFormatException When the int cannot be parsed */ public static int getInt(String key) throws NumberFormatException { String value = get(key); if (value == null) { return -1; } return Integer.parseInt(value); } /** * Get a setting's value as a boolean * * @param key Key name of the setting * @return The value of the setting (any value not understood will be * treated as false) */ public static boolean getBool(String key) { String value = get(key); if (value == null) { return false; } if (value.compareTo("1") == 0 || value.compareTo("true") == 0 || value.compareTo("on") == 0 || value.compareTo("yes") == 0) { return true; } return false; } }
package edu.uw.amaralmunnthorsteinson.porcelain; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { public static final String FIREBASE_URL = "https://fiery-torch-3951.firebaseio.com/"; // Keys for passing data to the AddToilet activity public static final String LONGITUDE = "longitude"; public static final String LATITUDE = "latitude"; private GoogleMap mMap; private boolean mFirstLoc = true; private HashMap<Marker, Place> mMarkerMap = new HashMap<>(); // The marker that tracks the USER location private Marker mLocationMarker; // The latLng that represents the user's most current location private LatLng mCurPos; private final String TAG = "TEST"; private final String INIT_MARKER_TITLE = "You are here!"; SharedPreferences sharedPref; private TextView mtitleText; private String mToiletGuid; private TextView mShowDetailButton; private TextView mdescriptionText; private TextView mShowIntruction; private ImageView mcleanStatus; // Google client instance GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); // Firebase setup Firebase.setAndroidContext(this); // Maps // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); // Builds a new GoogleApiClient for dealing with everything if(mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) //use location .build(); //build me the client already dammit! mGoogleApiClient.connect(); } mtitleText = (TextView) findViewById(R.id.toiletTitle); mdescriptionText = (TextView) findViewById(R.id.toiletDescription); mShowDetailButton = (TextView) findViewById(R.id.seeMoreButton); mShowIntruction = (TextView) findViewById(R.id.instruction); mToiletGuid = ""; mcleanStatus = (ImageView) findViewById(R.id.cleaninessImage); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent i = new Intent(getApplicationContext(), SettingsActivity.class); startActivity(i); return true; case R.id.action_center: moveCamera(); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } // Called when we want to start an activity to add a new toilet to our dataset public void addToilet(View v){ if (mCurPos != null) { Intent addToiletIntent = new Intent(this, AddToiletActivity.class); addToiletIntent.putExtra(LATITUDE, mCurPos.latitude); addToiletIntent.putExtra(LONGITUDE, mCurPos.longitude); startActivity(addToiletIntent); } else { // This means that the location for whatever reason is not available // Inform user with TOAST Toast.makeText(this, "Location currently unknown, try again in a few seconds", Toast.LENGTH_LONG) .show(); } } public void seeMore(View v) { Log.v(TAG, "Entered seeMore function"); Intent seeToiletDetailIntent = new Intent(this, ToiletDetail.class); seeToiletDetailIntent.putExtra("GUID", mToiletGuid); startActivity(seeToiletDetailIntent); } // Testing method to make sure firebase works as expected // and we can really read and write data void testFirebase() { Firebase rootRef = new Firebase("https://fiery-torch-3951.firebaseio.com/"); final Firebase array = rootRef.child("testArray"); array.addValueEventListener(new ValueEventListener() { boolean addedData = false; @Override // This callback get's called when the data FIRST becomes available, and then // when it changes as well. public void onDataChange(DataSnapshot snapshot) { Log.v(TAG, "Data change called"); // Prevents infinite loop, we only want to change the data once // Without this, as soon as a value changes, it would trigger another change Map<String, HashMap<String, Object>> val = (HashMap<String, HashMap<String, Object>>) snapshot.getValue(); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.toilet); Bitmap smaller = Bitmap.createScaledBitmap(icon, icon.getWidth() / 2, icon.getHeight() / 2, false); BitmapDescriptor toil = BitmapDescriptorFactory.fromBitmap(smaller); //LatLng point = new LatLng(-23,44.00); //Place p = new Place("A Bathroom", point, 3.0, "A clean and safe environment"); //Log.v(TAG, "" + val); if (val != null) { for (String s : val.keySet()) { HashMap h = val.get(s); // Log.d(TAG, "Added Marker To Map " + h.get("name")); HashMap<String, Double> coords = (HashMap) h.get("latLng"); LatLng point = new LatLng((Double) coords.get("latitude"), (Double) coords.get("longitude")); Marker mapPoint = mMap.addMarker(new MarkerOptions() .position(point) .title(s) .snippet("" + h.get("name")) .icon(toil)); Place p = new Place((String) h.get("name"), point, (Long) h.get("rating"), (String) h.get("descr"), (Boolean) h.get("isFamilyFriendly"), (Boolean) h.get("isGenderNeutral"), (Boolean) h.get("isHandicapAccessible"), (String) h.get("review"), s); boolean familyFilter = sharedPref.getBoolean("pref_family", false); boolean genderFilter = sharedPref.getBoolean("pref_gender", false); boolean handicapFilter = sharedPref.getBoolean("pref_handicap", false); mapPoint.setVisible(true); if (!((!familyFilter || (familyFilter && (Boolean) h.get("isFamilyFriendly"))) && (!genderFilter || (genderFilter && (Boolean) h.get("isGenderNeutral"))) && (!handicapFilter || (handicapFilter && (Boolean) h.get("isHandicapAccessible"))))) { mapPoint.setVisible(false); } mMarkerMap.put(mapPoint, p); } } } // This is a 'list' according to the firebase documentation // Instead of using indices, we use unique ids so to allow multiple people // to add data at the same time. Push() generates the UUID // We then use a HashMap to represent the uuid, long tuple //array.push().setValue(p); //Log.v(TAG, "" + array); @Override public void onCancelled(FirebaseError firebaseError) { Log.v(TAG, "The read failed: " + firebaseError.getMessage()); } }); } @Override protected void onResume() { super.onResume(); /*for(Marker key : mMarkerMap.keySet()) { boolean familyFilter = sharedPref.getBoolean("pref_family", false); boolean genderFilter = sharedPref.getBoolean("pref_gender", false); boolean handicapFilter = sharedPref.getBoolean("pref_handicap", false); String ratingFilter = sharedPref.getString("rating_filter", ""); Log.d(TAG, "onResume familyFilter" + familyFilter); Log.d(TAG, "onResume genderFilter" + genderFilter); Log.d(TAG, "onResume handicap" + handicapFilter); Place h = mMarkerMap.get(key); key.setVisible(true); if(!((!familyFilter || (familyFilter && h.isFamilyFriendly)) && (!genderFilter || (genderFilter && h.isGenderNeutral)) && (!handicapFilter || (handicapFilter && h.isHandicapAccessible)) && (Long.parseLong(ratingFilter) <= h.rating))) { key.setVisible(false); } }*/ Log.v(TAG, "Resume called"); if (mMap != null) { mMap.clear(); } mFirstLoc = true; testFirebase(); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady (GoogleMap googleMap){ mMap = googleMap; mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { // Don't do anything if the initial marker gets clicked // Maybe there's a better way to filter this, but whatevs if (!marker.getTitle().equals(INIT_MARKER_TITLE)) { Place pl = mMarkerMap.get(marker); mtitleText.setText(pl.name); mdescriptionText.setText(pl.descr); mToiletGuid = pl.guid; //TODO: only really need to do these four things once, could test mtitleText.setVisibility(TextView.VISIBLE); mdescriptionText.setVisibility(TextView.VISIBLE); mShowDetailButton.setVisibility(TextView.VISIBLE); mShowIntruction.setVisibility(TextView.GONE); if(pl.rating < 2){ mcleanStatus.setImageResource(R.mipmap.weepy_face); } else if(pl.rating < 3){ mcleanStatus.setImageResource(R.mipmap.sad_face); } else if(pl.rating < 4){ mcleanStatus.setImageResource(R.mipmap.neutral_face); } else { mcleanStatus.setImageResource(R.mipmap.happy_face); } } return true; } }); // run testFirebase, which should add a new child in our list testFirebase(); // Get current location and move camera there Location curLoc = getLocation(null); if (curLoc != null) { Log.v(TAG, "Adding initial marker"); LatLng curPos = new LatLng(curLoc.getLatitude(), curLoc.getLatitude()); mMap.addMarker(new MarkerOptions().position(curPos).title("You are here")); mMap.moveCamera(CameraUpdateFactory.newLatLng(curPos)); } } // Google API Connection @Override public void onConnected(Bundle bundle) { Log.v(TAG, "onConnected called"); LocationRequest request = new LocationRequest(); request.setInterval(10000); request.setFastestInterval(5000); request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, this); } // Google API Connection @Override public void onConnectionSuspended(int i) { Log.v(TAG, "onConnectedSuspended called"); } // Google API Connection @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.v(TAG, "onConnectionFailed called"); //when API hasn't connected, make toast Toast.makeText(this, "Uh oh! Can't connect to the API", Toast.LENGTH_LONG).show(); } /** Helper method for getting location **/ public Location getLocation(View v){ if(mGoogleApiClient != null) { Log.v(TAG, "Got a location, returning it"); return LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); } return null; } @Override public void onLocationChanged(Location location) { Location curLoc = getLocation(null); mCurPos = new LatLng(curLoc.getLatitude(), curLoc.getLongitude()); if (mFirstLoc) { // Set the camera to something decent //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCurPos, 15)); moveCamera(); // Don't ever touch the camera again mFirstLoc = false; // Add our initialMarker Log.v(TAG, "Adding initial marker"); mLocationMarker = mMap.addMarker(new MarkerOptions().position(mCurPos).title(INIT_MARKER_TITLE)); } else { // Update our position mLocationMarker.setPosition(mCurPos); } } public void moveCamera(){ mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCurPos, 15)); } }
package week3; import java.util.List; /** * Small helper class to provide a nice interface to store a document * @author harryscells * */ public class Document { private String name; private List<String> contents; /** * Document * @param name The filename of the document * @param contents The contents of the document as a List */ public Document(String name, List<String> contents) { this.name = name; this.contents = contents; } public Boolean contains(String term) { return contents.contains(term); } public List<String> getContents() { return this.contents; } public String toString(){ return this.name; } }
package tableview; import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.foundation.NSDictionary; import org.robovm.apple.foundation.NSString; import org.robovm.apple.uikit.UIApplication; import org.robovm.apple.uikit.UIApplicationDelegateAdapter; import org.robovm.apple.uikit.UIColor; import org.robovm.apple.uikit.UINavigationController; import org.robovm.apple.uikit.UINavigationControllerDelegateAdapter; import org.robovm.apple.uikit.UIScreen; import org.robovm.apple.uikit.UIWindow; public class RoboVMTableViewApplicationDelegate extends UIApplicationDelegateAdapter { private UIWindow window; @Override public boolean didFinishLaunching(UIApplication application, NSDictionary<NSString, ?> launchOptions) { window = new UIWindow(UIScreen.getMainScreen().getBounds()); GenderListTableViewController genderListTableViewController = new GenderListTableViewController(); UINavigationController navigationController = new UINavigationController(genderListTableViewController); navigationController.addStrongRef(genderListTableViewController); navigationController.setDelegate(new UINavigationControllerDelegateAdapter() {}); window.setRootViewController(navigationController); window.setBackgroundColor(UIColor.colorWhite()); window.makeKeyAndVisible(); return true; } public static void main(String[] args) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(args, null, RoboVMTableViewApplicationDelegate.class); pool.close(); } }
package net.wayward_realms.waywardchat; import mkremins.fanciful.FancyMessage; import net.wayward_realms.waywardlib.chat.Channel; import net.wayward_realms.waywardlib.essentials.EssentialsPlugin; import net.wayward_realms.waywardlib.util.math.MathUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.permissions.Permissible; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.scheduler.BukkitRunnable; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Random; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class AsyncPlayerChatListener implements Listener { private WaywardChat plugin; private RegisteredServiceProvider<EssentialsPlugin> essentialsPluginProvider; private YamlConfiguration pluginConfig; private YamlConfiguration emoteModeConfig; private YamlConfiguration prefixConfig; private ConcurrentHashMap<UUID, Location> uuidLocations = new ConcurrentHashMap<>(); public AsyncPlayerChatListener(WaywardChat plugin) { this.plugin = plugin; this.pluginConfig = (YamlConfiguration)plugin.getConfig(); emoteModeConfig = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "emote-mode.yml")); prefixConfig = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "prefixes.yml")); prefixConfig.set("admin", " &e[admin] "); essentialsPluginProvider = Bukkit.getServer().getServicesManager().getRegistration(EssentialsPlugin.class); // SET UP FUCKING PLAYER LOCATION GETTER SHIT COLLECTION Bukkit.getScheduler().runTaskTimer( plugin, new BukkitRunnable(){ @Override public void run() { for(Player player: Bukkit.getServer().getOnlinePlayers()) { uuidLocations.put(player.getUniqueId(), player.getLocation()); } } },100L,100L); // END THAT SHIT } @EventHandler(priority = EventPriority.HIGH) public void onAsyncPlayerChat(AsyncPlayerChatEvent event) { final Player player = event.getPlayer(); final String message = event.getMessage(); handleAsyncChat(player, message); event.setCancelled(true); } public void handleAsyncChat(final Player talking, String message) { if (!message.equals("")) { final String format; if (getEmoteMode(talking).isEmote(message)) { int emoteRadius = pluginConfig.getInt("emotes.radius"); plugin.getChannel(pluginConfig.getString("default-channel")).log(talking.getName() + "/" + talking.getDisplayName() + ": " + message); for (Player player : new ArrayList<>(talking.getWorld().getPlayers())) { if (emoteRadius < 0 || correlateUUIDtoLocation(talking.getUniqueId()).distanceSquared(correlateUUIDtoLocation(player.getUniqueId())) <= (double) (emoteRadius * emoteRadius)) formatEmote(talking, message).send(player); } } else { if (plugin.getPlayerChannel(talking) != null) { plugin.getPlayerChannel(talking).log(talking.getName() + "/" + talking.getDisplayName() + ": " + message); synchronized (plugin.getPlayerChannel(talking).getListeners()) { for (Player player : new HashSet<>(plugin.getPlayerChannel(talking).getListeners())) { if (player != null) { int radius = plugin.getPlayerChannel(talking).getRadius(); if (radius >= 0) { if (talking.getWorld().equals(player.getWorld())) { if (correlateUUIDtoLocation(talking.getUniqueId()).distanceSquared(correlateUUIDtoLocation(player.getUniqueId())) <= (double) (radius * radius)) { FancyMessage fancy = formatChannel(plugin.getPlayerChannel(talking), talking, player, message); fancy.send(player); } } } else { formatChannel(plugin.getPlayerChannel(talking), talking, player, message).send(player); } } } } if (plugin.getPlayerChannel(talking).isIrcEnabled()) { format = plugin.getPlayerChannel(talking).getFormat() .replace("%channel%", plugin.getPlayerChannel(talking).getName()) .replace("%prefix%", getPlayerPrefix(talking)) .replace("%player%", talking.getDisplayName()) .replace("%ign%", talking.getName()) .replace("&", ChatColor.COLOR_CHAR + "") .replace("%message%", message); //SCHEDULE TASK TO PASS TO IRCBOT Bukkit.getScheduler().runTask(plugin, new Runnable() { public void run() { plugin.getIrcBot().sendIRC().message(plugin.getPlayerChannel(talking).getIrcChannel(), ChatColor.stripColor(format)); } }); //TASK FUCKING PASSED } } else { talking.sendMessage(plugin.getPrefix() + ChatColor.RED + "You must talk in a channel! Use /chathelp for help."); } } } } public EmoteMode getEmoteMode(OfflinePlayer player) { if (emoteModeConfig.get(player.getName()) != null) return EmoteMode.valueOf(emoteModeConfig.getString(player.getName())); else return EmoteMode.TWO_ASTERISKS; } public String getPlayerPrefix(final Permissible player) { for (String key : prefixConfig.getKeys(false)) { if (player.hasPermission("wayward.chat.prefix." + key)) { return ChatColor.translateAlternateColorCodes('&', prefixConfig.getString(key)); } } return ""; } public FancyMessage formatChannel(Channel channel, Player talking, Player recipient, String message) { FancyMessage fancy = new FancyMessage(""); String format = channel.getFormat(); ChatColor chatColour = null; ChatColor chatFormat = null; for (int i = 0; i < format.length(); i++) { if (format.charAt(i) == '&') { ChatColor colourOrFormat = ChatColor.getByChar(format.charAt(i + 1)); if (colourOrFormat.isColor()) chatColour = colourOrFormat; if (colourOrFormat.isFormat()) chatFormat = colourOrFormat; i += 1; } else if (format.substring(i, i + ("%channel%").length()).equalsIgnoreCase("%channel%")) { fancy.then(channel.getName()); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%channel%").length() - 1; } else if (format.substring(i, i + ("%player%").length()).equalsIgnoreCase("%player%")) { fancy.then(talking.getDisplayName()); fancy.tooltip(talking.getName()); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%player%").length() - 1; } else if (format.substring(i, i + ("%prefix%").length()).equalsIgnoreCase("%prefix%")) { fancy.then(getPlayerPrefix(talking)); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%prefix%").length() - 1; } else if (format.substring(i, i + ("%ign%").length()).equalsIgnoreCase("%ign%")) { fancy.then(talking.getName()); fancy.tooltip(talking.getDisplayName()); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%ign%").length() - 1; } else if (format.substring(i, i + ("%message%").length()).equalsIgnoreCase("%message%")) { if (channel.isGarbleEnabled()) { if (recipient != null) { double distance = MathUtils.fastsqrt(correlateUUIDtoLocation(talking.getUniqueId()).distanceSquared(correlateUUIDtoLocation(recipient.getUniqueId()))); double clearRange = 0.75D * (double) channel.getRadius(); double hearingRange = (double) channel.getRadius(); double clarity = 1.0D - ((distance - clearRange) / hearingRange); String garbledMessage = garbleMessage(drunkify(talking, message), clarity); fancy.then(garbledMessage); } } else { fancy.then(message); } if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%message%").length() - 1; } else { fancy.then(format.charAt(i)); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); } } return fancy; } public FancyMessage formatEmote(Player talking, String message) { FancyMessage fancy = new FancyMessage(""); String format = pluginConfig.getString("emotes.format"); ChatColor chatColour = null; ChatColor chatFormat = null; for (int i = 0; i < format.length(); i++) { if (format.charAt(i) == '&') { ChatColor colourOrFormat = ChatColor.getByChar(format.charAt(i + 1)); if (colourOrFormat.isColor()) chatColour = colourOrFormat; if (colourOrFormat.isFormat()) chatFormat = colourOrFormat; i += 1; } else if (format.substring(i, i + ("%channel%").length()).equalsIgnoreCase("%channel%")) { fancy.then("emote"); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%channel%").length() - 1; } else if (format.substring(i, i + ("%player%").length()).equalsIgnoreCase("%player%")) { fancy.then(talking.getDisplayName()); fancy.tooltip(talking.getName()); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%player%").length() - 1; } else if (format.substring(i, i + ("%prefix%").length()).equalsIgnoreCase("%prefix%")) { fancy.then(getPlayerPrefix(talking)); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%prefix%").length() - 1; } else if (format.substring(i, i + ("%ign%").length()).equalsIgnoreCase("%ign%")) { fancy.then(talking.getName()); fancy.tooltip(talking.getDisplayName()); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%ign%").length() - 1; } else if (format.substring(i, i + ("%message%").length()).equalsIgnoreCase("%message%")) { fancy.then(message.replace("*", "")); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); i += ("%message%").length() - 1; } else { fancy.then(format.charAt(i)); if (chatColour != null) fancy.color(chatColour); if (chatFormat != null) fancy.style(chatFormat); } } return fancy; } private String drunkify(final Player player, String message) { if (essentialsPluginProvider != null) { EssentialsPlugin essentialsPlugin = essentialsPluginProvider.getProvider(); if (essentialsPlugin.getDrunkenness(player) >= 5) { return message.replaceAll("s([^h])", "sh$1"); } } return message; } public String garbleMessage(String message, double clarity) { StringBuilder newMessage = new StringBuilder(); Random random = new Random(); int i = 0; int drops = 0; while (i < message.length()) { int c = message.codePointAt(i); i += Character.charCount(c); if (random.nextDouble() < clarity) { newMessage.appendCodePoint(c); } else if (random.nextDouble() < 0.1D) { newMessage.append(ChatColor.DARK_GRAY); newMessage.appendCodePoint(c); newMessage.append(ChatColor.WHITE); } else { newMessage.append(' '); drops++; } } if (drops == message.length()) { return "~~~"; } return newMessage.toString(); } private Location correlateUUIDtoLocation(UUID in){ if(uuidLocations.containsKey(in)){ return uuidLocations.get(in); } return null; } }
package javarepl; import com.googlecode.totallylazy.Function1; import com.googlecode.totallylazy.Mapper; import com.googlecode.totallylazy.Option; import com.googlecode.totallylazy.Sequence; import com.googlecode.totallylazy.predicates.LogicalPredicate; import javarepl.console.*; import javarepl.console.rest.RestConsole; import java.io.*; import java.lang.management.ManagementPermission; import java.lang.reflect.ReflectPermission; import java.net.SocketPermission; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.security.CodeSource; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.util.Collections; import java.util.List; import java.util.PropertyPermission; import static com.googlecode.totallylazy.Callables.compose; import static com.googlecode.totallylazy.Files.fileOption; import static com.googlecode.totallylazy.Files.temporaryDirectory; import static com.googlecode.totallylazy.Option.none; import static com.googlecode.totallylazy.Option.some; import static com.googlecode.totallylazy.Predicates.not; import static com.googlecode.totallylazy.Sequences.sequence; import static com.googlecode.totallylazy.Strings.*; import static com.googlecode.totallylazy.numbers.Numbers.intValue; import static com.googlecode.totallylazy.numbers.Numbers.valueOf; import static java.lang.String.format; import static java.lang.System.getProperty; import static javarepl.Utils.applicationVersion; import static javarepl.Utils.randomServerPort; import static javarepl.console.ConsoleConfig.consoleConfig; import static javarepl.console.ConsoleLog.Type.ERROR; import static javarepl.console.ConsoleLog.Type.SUCCESS; import static javax.tools.ToolProvider.getSystemJavaCompiler; public class Repl { public static void main(String... args) throws Exception { ConsoleLogger logger = systemStreamsLogger(); boolean sandboxed = isSandboxed(args); Integer port = port(args); if (!ignoreConsole(args)) { logger.info(format("Welcome to JavaREPL version %s (%s, %s, Java %s)", applicationVersion(), sandboxed ? "sandboxed" : "unrestricted", getProperty("java.vm.name"), getProperty("java.version"))); } String[] expressions = sequence(initialExpressions(args)) .union(sequence(initialExpressionsFromFile())) .toArray(new String[0]); ConsoleConfig consoleConfig = consoleConfig() .historyFile(historyFile(!sandboxed)) .expressions(expressions) .sandboxed(sandboxed) .logger(logger); RestConsole console = new RestConsole(new TimingOutConsole(new SimpleConsole(consoleConfig), expressionTimeout(args), inactivityTimeout(args)), port); ExpressionReader reader = new ExpressionReader(ignoreConsole(args) ? ignoreConsoleInput() : readFromConsole()); if (sandboxed) sandboxApplication(logger); console.start(); do { console.execute(reader.readExpression().getOrNull()); logger.info(""); } while (true); } private static List<String> initialExpressionsFromFile() { return fileOption(new File("."), "javarepl.init") .map(readFile()) .getOrElse(Collections.EMPTY_LIST); } private static Function1<File, List<String>> readFile() { return new Function1<File, List<String>>() { @Override public List<String> call(File f) throws Exception { List<String> l = Files.readAllLines(f.toPath(), StandardCharsets.UTF_8); System.out.println(l); return l; } }; } private static boolean ignoreConsole(String[] args) { return sequence(args).contains("--ignoreConsole"); } private static Mapper<Sequence<String>, String> ignoreConsoleInput() { return new Mapper<Sequence<String>, String>() { public String call(Sequence<String> strings) throws Exception { while (true) { Thread.sleep(100); } } }; } private static Mapper<Sequence<String>, String> readFromConsole() { return new Mapper<Sequence<String>, String>() { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public String call(Sequence<String> lines) throws Exception { return reader.readLine(); } }; } private static String[] initialExpressions(String[] args) { return sequence(args) .find(startsWith("--expression=")) .map(replaceAll("--expression=", "")) .toSequence() .toArray(String.class); } private static ConsoleLogger systemStreamsLogger() { ConsoleLogger logger = new ConsoleLogger(System.out, System.err, false); LogicalPredicate<String> ignoredLogs = startsWith("POST /") .or(startsWith("GET /")) .or(startsWith("Listening on http: System.setOut(new ConsoleLoggerPrintStream(SUCCESS, ignoredLogs, logger)); System.setErr(new ConsoleLoggerPrintStream(ERROR, ignoredLogs, logger)); return logger; } private static Option<File> historyFile(boolean createFile) { return createFile ? some(new File(getProperty("user.home"), ".javarepl.history")) : none(File.class); } private static boolean isSandboxed(String[] args) { return sequence(args).contains("--sandboxed"); } private static Integer port(String[] args) { return sequence(args).find(startsWith("--port=")).map(compose(replaceAll("--port=", ""), compose(valueOf, intValue))).getOrElse(randomServerPort()); } private static Option<Integer> expressionTimeout(String[] args) { return sequence(args).find(startsWith("--expressionTimeout=")).map(compose(replaceAll("--expressionTimeout=", ""), compose(valueOf, intValue))); } private static Option<Integer> inactivityTimeout(String[] args) { return sequence(args).find(startsWith("--inactivityTimeout=")).map(compose(replaceAll("--inactivityTimeout=", ""), compose(valueOf, intValue))); } private static void sandboxApplication(ConsoleLogger logger) throws UnsupportedEncodingException { Policy.setPolicy(new Policy() { private final PermissionCollection permissions = new Permissions(); { permissions.add(new SocketPermission("*", "accept, connect, resolve")); permissions.add(new RuntimePermission("accessClassInPackage.sun.misc.*")); permissions.add(new RuntimePermission("accessClassInPackage.sun.misc")); permissions.add(new RuntimePermission("getProtectionDomain")); permissions.add(new RuntimePermission("accessDeclaredMembers")); permissions.add(new RuntimePermission("createClassLoader")); permissions.add(new RuntimePermission("closeClassLoader")); permissions.add(new RuntimePermission("modifyThreadGroup")); permissions.add(new RuntimePermission("getStackTrace")); permissions.add(new ManagementPermission("monitor")); permissions.add(new ReflectPermission("suppressAccessChecks")); permissions.add(new PropertyPermission("*", "read")); permissions.add(new FilePermission(temporaryDirectory("JavaREPL").getAbsolutePath() + "/-", "read, write, delete")); permissions.add(new FilePermission(sequence(System.getProperty("java.home").split(File.separator)). reverse(). dropWhile(not(contains("jdk1"))). reverse(). toString(File.separator) + "/-", "read")); permissions.add(new FilePermission("./-", "read")); Sequence<String> extensions = sequence(((URLClassLoader) getSystemJavaCompiler().getClass().getClassLoader()).getURLs()).map(path()). join(paths("java.ext.dirs")). join(paths("java.library.path")). append(System.getProperty("user.home")); for (String extension : extensions) { permissions.add(new FilePermission(extension, "read")); permissions.add(new FilePermission(extension + "/-", "read")); } } @Override public PermissionCollection getPermissions(CodeSource codesource) { return permissions; } }); System.setSecurityManager(new SecurityManager()); } private static Function1<URL, String> path() { return new Function1<URL, String>() { @Override public String call(URL url) throws Exception { return url.getPath(); } }; } private static Sequence<String> paths(String propertyKey) { return sequence(System.getProperty(propertyKey).split(File.pathSeparator)); } }
package soot.jimple.internal; import soot.tagkit.*; import soot.*; import soot.jimple.*; import soot.baf.*; import soot.util.*; import java.util.*; public class JimpleLocal implements Local, ConvertToBaf { String name; Type type; int fixedHashCode; boolean isHashCodeChosen; /** Constructs a JimpleLocal of the given name and type. */ public JimpleLocal(String name, Type t) { this.name = name.intern(); this.type = t; Scene.v().getLocalNumberer().add( this ); } /** Returns true if the given object is structurally equal to this one. */ public boolean equivTo(Object o) { return this.equals( o ); } /** Returns a hash code for this object, consistent with structural equality. */ public int equivHashCode() { return name.hashCode() * 101 + type.hashCode() * 17; } /** Returns a clone of the current JimpleLocal. */ public Object clone() { return new JimpleLocal(name, type); } /** Returns the name of this object. */ public String getName() { return name; } /** Sets the name of this object as given. */ public void setName(String name) { this.name = name.intern(); } /** Returns a hashCode consistent with object equality. */ public int hashCode() { if(!isHashCodeChosen) { // Set the hash code for this object if(name != null & type != null) fixedHashCode = name.hashCode() + 19 * type.hashCode(); else if(name != null) fixedHashCode = name.hashCode(); else if(type != null) fixedHashCode = type.hashCode(); else fixedHashCode = 1; isHashCodeChosen = true; } return fixedHashCode; } /** Returns the type of this local. */ public Type getType() { return type; } /** Sets the type of this local. */ public void setType(Type t) { this.type = t; } public String toString() { return getName(); } public void toString(UnitPrinter up) { up.local(this); } public List getUseBoxes() { return AbstractUnit.emptyList; } public void apply(Switch sw) { ((JimpleValueSwitch) sw).caseLocal(this); } public void convertToBaf(JimpleToBafContext context, List<Unit> out) { Unit u = Baf.v().newLoadInst(getType(),context.getBafLocalOfJimpleLocal(this)); out.add(u); Iterator it = context.getCurrentUnit().getTags().iterator(); while(it.hasNext()) { u.addTag((Tag) it.next()); } } public final int getNumber() { return number; } public final void setNumber( int number ) { this.number = number; } private int number = 0; }
package ru.stqa.ptf.addressbook; import org.openqa.selenium.firefox.FirefoxOptions; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; import java.util.concurrent.TimeUnit; import java.util.Date; import java.io.File; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; import static org.openqa.selenium.OutputType.*; public class ContactCreationTests { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { wd = new FirefoxDriver(new FirefoxOptions().setLegacy(true)); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.get("http://localhost/addressbook/"); login("admin", "secret"); } private void login(String username, String password) { wd.findElement(By.id("content")).click(); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys(username); wd.findElement(By.id("LoginForm")).click(); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys(password); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); } @Test public void ContactCreationTests() { initAddContact(); fillContactForm(); submitContactCretiopn(); returntoHomePage(); } private void submitContactCretiopn() { wd.findElement(By.xpath("//div[@id='content']/form/input[21]")).click(); } private void initAddContact() { wd.findElement(By.linkText("add new")).click(); } private void returntoHomePage() { wd.findElement(By.linkText("home page")).click(); } private void fillContactForm() { wd.findElement(By.name("firstname")).click(); wd.findElement(By.name("firstname")).clear(); wd.findElement(By.name("firstname")).sendKeys("Olga"); wd.findElement(By.name("lastname")).click(); wd.findElement(By.name("lastname")).clear(); wd.findElement(By.name("lastname")).sendKeys("Pug"); wd.findElement(By.name("company")).click(); wd.findElement(By.name("company")).clear(); wd.findElement(By.name("company")).sendKeys("HUG ME"); wd.findElement(By.name("address")).click(); wd.findElement(By.name("address")).clear(); wd.findElement(By.name("address")).sendKeys("Address 1"); wd.findElement(By.name("home")).click(); wd.findElement(By.name("home")).clear(); wd.findElement(By.name("home")).sendKeys("0987655678"); wd.findElement(By.name("email")).click(); wd.findElement(By.name("email")).clear(); wd.findElement(By.name("email")).sendKeys("totop@mail.com"); if (!wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[15]")).isSelected()) { wd.findElement(By.xpath("//div[@id='content']/form/select[1]//option[15]")).click(); } if (!wd.findElement(By.xpath("//div[@id='content']/form/select[2]//option[3]")).isSelected()) { wd.findElement(By.xpath("//div[@id='content']/form/select[2]//option[3]")).click(); } wd.findElement(By.name("byear")).click(); wd.findElement(By.name("byear")).clear(); wd.findElement(By.name("byear")).sendKeys("1987"); wd.findElement(By.name("address2")).click(); wd.findElement(By.name("address2")).clear(); wd.findElement(By.name("address2")).sendKeys("Address 2"); wd.findElement(By.name("notes")).click(); wd.findElement(By.name("notes")).clear(); wd.findElement(By.name("notes")).sendKeys("No notes"); } @AfterMethod public void tearDown() { wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
package ua.stqa.pft.addressbook; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; public class ContactCreationTests { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.get("http://localhost/addressbook/"); login("admin", "secret"); } private void login(String username, String password) { wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys(username); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys(password); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); } @Test public void testContactCreation() { addNewContactBtn(); fillNewContactForm(); submitNewContactCreationBtn(); returnToHomePage(); } private void returnToHomePage() { wd.findElement(By.linkText("home page")).click(); } private void submitNewContactCreationBtn() { wd.findElement(By.name("submit")).click(); } private void fillNewContactForm() { wd.findElement(By.name("firstname")).click(); wd.findElement(By.name("firstname")).clear(); wd.findElement(By.name("firstname")).sendKeys("first name test "); wd.findElement(By.name("lastname")).click(); wd.findElement(By.name("lastname")).clear(); wd.findElement(By.name("lastname")).sendKeys("last name test"); wd.findElement(By.name("address")).click(); wd.findElement(By.name("address")).clear(); wd.findElement(By.name("address")).sendKeys("address test"); wd.findElement(By.name("home")).click(); wd.findElement(By.name("home")).clear(); wd.findElement(By.name("home")).sendKeys("1111111"); wd.findElement(By.name("mobile")).click(); wd.findElement(By.name("mobile")).clear(); wd.findElement(By.name("mobile")).sendKeys("2222222"); wd.findElement(By.name("work")).click(); wd.findElement(By.name("work")).clear(); wd.findElement(By.name("work")).sendKeys("3333333"); wd.findElement(By.name("fax")).click(); wd.findElement(By.name("fax")).clear(); wd.findElement(By.name("fax")).sendKeys("4444444"); wd.findElement(By.name("email")).click(); wd.findElement(By.name("email")).clear(); wd.findElement(By.name("email")).sendKeys("emailtest1@test.com"); wd.findElement(By.name("email2")).click(); wd.findElement(By.name("email2")).clear(); wd.findElement(By.name("email2")).sendKeys("emailtest2@test.com"); wd.findElement(By.name("email3")).click(); wd.findElement(By.name("email3")).clear(); wd.findElement(By.name("email3")).sendKeys("emailtest3@test.com"); } private void addNewContactBtn() { wd.findElement(By.linkText("add new")).click(); } @AfterMethod public void tearDown() { wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
package ti.modules.titanium.ui.widget.listview; import java.lang.ref.WeakReference; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.UIModule; import android.app.Activity; @Kroll.proxy(creatableInModule = UIModule.class) public class ListItemProxy extends TiViewProxy { protected WeakReference<TiViewProxy> listProxy; public TiUIView createView(Activity activity) { return new TiListItem(this); } public void setListProxy(TiViewProxy list) { listProxy = new WeakReference<TiViewProxy>(list); } public TiViewProxy getListProxy() { if (listProxy != null) { return listProxy.get(); } return null; } public boolean fireEvent(final String event, final Object data, boolean bubbles) { fireItemClick(event, data); return super.fireEvent(event, data, bubbles); } private void fireItemClick(String event, Object data) { if (event.equals(TiC.EVENT_CLICK) && data instanceof HashMap) { KrollDict eventData = new KrollDict((HashMap) data); TiViewProxy source = (TiViewProxy) eventData.get(TiC.EVENT_PROPERTY_SOURCE); if (source != null && !source.equals(this) && listProxy != null) { // append bind properties if (eventData.containsKey(TiC.PROPERTY_BIND_ID) && eventData.containsKey(TiC.PROPERTY_ITEM_INDEX) && eventData.containsKey(TiC.PROPERTY_SECTION)) { int itemIndex = eventData.getInt(TiC.PROPERTY_ITEM_INDEX); String bindId = eventData.getString(TiC.PROPERTY_BIND_ID); ListSectionProxy section = (ListSectionProxy) eventData.get(TiC.PROPERTY_SECTION); KrollDict itemProperties = section.getItemAt(itemIndex); if (itemProperties != null && itemProperties.containsKey(bindId)) { KrollDict properties = itemProperties.getKrollDict(bindId); for (String key : properties.keySet()) { source.setProperty(key, properties.get(key)); } source.setProperty(TiC.PROPERTY_BIND_ID, bindId); } } TiViewProxy listViewProxy = listProxy.get(); if (listViewProxy != null) { listViewProxy.fireEvent(TiC.EVENT_ITEM_CLICK, eventData); } } } } @Override public boolean hierarchyHasListener(String event) { // In order to fire the "itemclick" event when the children views are clicked, // the children views' "click" events must be fired and bubbled up. (TIMOB-14901) if (event.equals(TiC.EVENT_CLICK)) { return true; } return super.hierarchyHasListener(event); } public void release() { super.release(); if (listProxy != null) { listProxy = null; } } @Override public String getApiName() { return "Ti.UI.ListItem"; } }
package com.samourai.wallet.paynym.paynymDetails; import android.app.AlertDialog; import android.app.Dialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.support.constraint.ConstraintLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.samourai.wallet.R; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.SendActivity; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.SendNotifTxFactory; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.bip47.rpc.SecretPoint; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.paynym.fragments.EditPaynymBottomSheet; import com.samourai.wallet.paynym.fragments.ShowPayNymQRBottomSheet; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.bech32.Bech32Util; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionInput; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.UTXOFactory; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MessageSignUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.SentToFromBIP47Util; import com.samourai.wallet.widgets.ItemDividerDecorator; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.script.Script; import org.bouncycastle.util.encoders.DecoderException; import org.bouncycastle.util.encoders.Hex; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class PayNymDetailsActivity extends AppCompatActivity { private static final int EDIT_PCODE = 2000; private static final int RECOMMENDED_PCODE = 2001; private static final int SCAN_PCODE = 2077; private String pcode = null, label = null; private ImageView userAvatar; private TextView paynymCode, followMessage, paynymLabel, confirmMessage, followsYoutext; private RecyclerView historyRecyclerView; private Button followBtn; private static final String TAG = "PayNymDetailsActivity"; private List<Tx> txesList = new ArrayList<>(); private PaynymTxListAdapter paynymTxListAdapter; private CompositeDisposable disposables = new CompositeDisposable(); private ProgressBar paynymAvatarPorgress, progressBar; private ConstraintLayout historyLayout, followLayout; private Menu menu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paynym_details); setSupportActionBar(findViewById(R.id.toolbar_paynym)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); userAvatar = findViewById(R.id.paybyn_user_avatar); paynymCode = findViewById(R.id.paynym_payment_code); followMessage = findViewById(R.id.follow_message); historyRecyclerView = findViewById(R.id.recycler_view_paynym_history); followBtn = findViewById(R.id.paynym_follow_btn); paynymAvatarPorgress = findViewById(R.id.paynym_image_progress); progressBar = findViewById(R.id.progressBar); historyLayout = findViewById(R.id.historyLayout); followLayout = findViewById(R.id.followLayout); paynymLabel = findViewById(R.id.paynym_label); confirmMessage = findViewById(R.id.confirm_message); followsYoutext = findViewById(R.id.follows_you_text); historyRecyclerView.setNestedScrollingEnabled(true); if (getIntent().hasExtra("pcode")) { pcode = getIntent().getStringExtra("pcode"); } else { finish(); } if (getIntent().hasExtra("label")) { label = getIntent().getStringExtra("label"); } paynymTxListAdapter = new PaynymTxListAdapter(txesList, getApplicationContext()); historyRecyclerView.setLayoutManager(new LinearLayoutManager(this)); historyRecyclerView.setAdapter(paynymTxListAdapter); Drawable drawable = this.getResources().getDrawable(R.drawable.divider_grey); historyRecyclerView.addItemDecoration(new ItemDividerDecorator(drawable)); setPayNym(); loadTxes(); followBtn.setOnClickListener(view -> { followPaynym(); }); paynymLabel.setOnClickListener(view -> { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("paynym", ((TextView) view).getText().toString()); clipboard.setPrimaryClip(clip); Toast.makeText(this,"Paynym id copied",Toast.LENGTH_SHORT).show(); }); } private void setPayNym() { followMessage.setText(getResources().getString(R.string.follow).concat(" ").concat(BIP47Meta.getInstance().getDisplayLabel(pcode)).concat(" ").concat(getResources().getText(R.string.paynym_follow_message_2).toString())); if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) { showFollow(); } else { showHistory(); } if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_NO_CFM) { showWaitingForConfirm(); } if (BIP47Meta.getInstance().incomingExists(pcode)) { // followsYoutext.setVisibility(View.VISIBLE); } else { // followsYoutext.setVisibility(View.GONE); } Log.i(TAG, "setPayNym: ".concat(String.valueOf(BIP47Meta.getInstance().getOutgoingStatus(pcode)))); paynymCode.setText(BIP47Meta.getInstance().getAbbreviatedPcode(pcode)); paynymLabel.setText(getLabel()); paynymAvatarPorgress.setVisibility(View.VISIBLE); Picasso.with(getApplicationContext()) .load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + pcode + "/avatar") .into(userAvatar, new Callback() { @Override public void onSuccess() { paynymAvatarPorgress.setVisibility(View.GONE); } @Override public void onError() { paynymAvatarPorgress.setVisibility(View.GONE); Toast.makeText(PayNymDetailsActivity.this, "Unable to load avatar", Toast.LENGTH_SHORT).show(); } }); if (menu != null) { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_NO_CFM) { menu.findItem(R.id.retry_notiftx).setVisible(true); } else { menu.findItem(R.id.retry_notiftx).setVisible(false); } } } private void showWaitingForConfirm() { historyLayout.setVisibility(View.VISIBLE); followLayout.setVisibility(View.VISIBLE); confirmMessage.setVisibility(View.VISIBLE); followBtn.setVisibility(View.GONE); followMessage.setVisibility(View.GONE); } private void showHistory() { historyLayout.setVisibility(View.VISIBLE); followLayout.setVisibility(View.GONE); confirmMessage.setVisibility(View.GONE); } private void showFollow() { historyLayout.setVisibility(View.GONE); followBtn.setVisibility(View.VISIBLE); followLayout.setVisibility(View.VISIBLE); confirmMessage.setVisibility(View.GONE); followMessage.setVisibility(View.VISIBLE); } private void showFollowAlert(String strAmount, View.OnClickListener onClickListener) { try { Dialog dialog = new Dialog(this, android.R.style.Theme_Dialog); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.paynym_follow_dialog); dialog.setCanceledOnTouchOutside(true); if (dialog.getWindow() != null) dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); TextView title = dialog.findViewById(R.id.follow_title_paynym_dialog); TextView oneTimeFeeMessage = dialog.findViewById(R.id.one_time_fee_message); title.setText(getResources().getText(R.string.follow).toString() .concat(" ").concat(BIP47Meta.getInstance().getLabel(pcode))); Button followBtn = dialog.findViewById(R.id.follow_paynym_btn); String message = getResources().getText(R.string.paynym_follow_fee_message).toString(); String part1 = message.substring(0, 28); String part2 = message.substring(29); oneTimeFeeMessage.setText(part1.concat(" ").concat(strAmount).concat(" ").concat(part2)); followBtn.setOnClickListener(view -> { dialog.dismiss(); if (onClickListener != null) onClickListener.onClick(view); }); dialog.findViewById(R.id.cancel_btn).setOnClickListener(view -> { dialog.dismiss(); }); dialog.setCanceledOnTouchOutside(false); dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } private void followPaynym() { Bundle bundle = new Bundle(); bundle.putString("label", getLabel()); bundle.putString("pcode", pcode); bundle.putString("buttonText", "Follow"); EditPaynymBottomSheet editPaynymBottomSheet = new EditPaynymBottomSheet(); editPaynymBottomSheet.setArguments(bundle); editPaynymBottomSheet.show(getSupportFragmentManager(), editPaynymBottomSheet.getTag()); editPaynymBottomSheet.setSaveButtonListener(view -> { updatePaynym(editPaynymBottomSheet.getLabel(), editPaynymBottomSheet.getPcode()); doNotifTx(); }); } private String getLabel() { return label == null ? BIP47Meta.getInstance().getDisplayLabel(pcode) : label; } private void loadTxes() { Disposable disposable = Observable.fromCallable(() -> { List<Tx> txesListSelected = new ArrayList<>(); List<Tx> txs = APIFactory.getInstance(this).getAllXpubTxs(); try { APIFactory.getInstance(getApplicationContext()).getXpubAmounts().get(HD_WalletFactory.getInstance(getApplicationContext()).get().getAccount(0).xpubstr()); } catch (IOException e) { e.printStackTrace(); } catch (MnemonicException.MnemonicLengthException e) { e.printStackTrace(); } if (txs != null) for (Tx tx : txs) { if (tx.getPaymentCode() != null) { if (tx.getPaymentCode().equals(pcode)) { txesListSelected.add(tx); } } List<String> hashes = SentToFromBIP47Util.getInstance().get(pcode); if (hashes != null) for (String hash : hashes) { if (hash.equals(tx.getHash())) { if (!txesListSelected.contains(tx)) { txesListSelected.add(tx); } } } } return txesListSelected; }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(txes -> { this.txesList.clear(); this.txesList.addAll(txes); paynymTxListAdapter.notifyDataSetChanged(); }); disposables.add(disposable); } @Override protected void onDestroy() { disposables.dispose(); try { PayloadUtil.getInstance(getApplicationContext()).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(getApplicationContext()).getGUID() + AccessFactory.getInstance(getApplicationContext()).getPIN())); } catch (MnemonicException.MnemonicLengthException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (DecryptionException e) { e.printStackTrace(); } super.onDestroy(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { finish(); break; } case R.id.send_menu_paynym_details: { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) { Intent intent = new Intent(this, SendActivity.class); intent.putExtra("pcode", pcode); startActivity(intent); } else { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_NOT_SENT) { followPaynym(); } else { Snackbar.make(historyLayout.getRootView(), "Follow transaction is still pending", Snackbar.LENGTH_SHORT).show(); } } break; } case R.id.edit_menu_paynym_details: { Bundle bundle = new Bundle(); bundle.putString("label", BIP47Meta.getInstance().getDisplayLabel(pcode)); bundle.putString("pcode", pcode); bundle.putString("buttonText", "Save"); EditPaynymBottomSheet editPaynymBottomSheet = new EditPaynymBottomSheet(); editPaynymBottomSheet.setArguments(bundle); editPaynymBottomSheet.show(getSupportFragmentManager(), editPaynymBottomSheet.getTag()); editPaynymBottomSheet.setSaveButtonListener(view -> { updatePaynym(editPaynymBottomSheet.getLabel(), editPaynymBottomSheet.getPcode()); }); break; } case R.id.archive_paynym: { BIP47Meta.getInstance().setArchived(pcode, true); finish(); break; } case R.id.resync_menu_paynym_details: { doSync(); break; } case R.id.view_code_paynym_details: { Bundle bundle = new Bundle(); bundle.putString("pcode", pcode); ShowPayNymQRBottomSheet showPayNymQRBottomSheet = new ShowPayNymQRBottomSheet(); showPayNymQRBottomSheet.setArguments(bundle); showPayNymQRBottomSheet.show(getSupportFragmentManager(), showPayNymQRBottomSheet.getTag()); break; } case R.id.retry_notiftx: { doNotifTx(); break; } } return super.onOptionsItemSelected(item); } private void updatePaynym(String label, String pcode) { if (pcode == null || pcode.length() < 1 || !FormatsUtil.getInstance().isValidPaymentCode(pcode)) { Snackbar.make(userAvatar.getRootView(), R.string.invalid_payment_code, Snackbar.LENGTH_SHORT).show(); } else if (label == null || label.length() < 1) { Snackbar.make(userAvatar.getRootView(), R.string.bip47_no_label_error, Snackbar.LENGTH_SHORT).show(); } else { BIP47Meta.getInstance().setLabel(pcode, label); new Thread(() -> { Looper.prepare(); try { PayloadUtil.getInstance(PayNymDetailsActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(PayNymDetailsActivity.this).getGUID() + AccessFactory.getInstance().getPIN())); } catch (MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(PayNymDetailsActivity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } catch (DecoderException de) { de.printStackTrace(); Toast.makeText(PayNymDetailsActivity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } catch (JSONException je) { je.printStackTrace(); Toast.makeText(PayNymDetailsActivity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } catch (IOException ioe) { ioe.printStackTrace(); Toast.makeText(PayNymDetailsActivity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } catch (NullPointerException npe) { npe.printStackTrace(); Toast.makeText(PayNymDetailsActivity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } catch (DecryptionException de) { de.printStackTrace(); Toast.makeText(PayNymDetailsActivity.this, R.string.decryption_error, Toast.LENGTH_SHORT).show(); } finally { ; } Looper.loop(); doUpdatePayNymInfo(pcode); }).start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.paynym_details_menu, menu); if (pcode != null) { if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_NO_CFM) { menu.findItem(R.id.retry_notiftx).setVisible(true); } else { menu.findItem(R.id.retry_notiftx).setVisible(false); } } this.menu = menu; return super.onCreateOptionsMenu(menu); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == EDIT_PCODE) { setPayNym(); } } private void doNotifTx() { // get wallet balance long balance = 0L; try { balance = APIFactory.getInstance(PayNymDetailsActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(PayNymDetailsActivity.this).get().getAccount(0).xpubstr()); } catch (IOException ioe) { balance = 0L; } catch (MnemonicException.MnemonicLengthException mle) { balance = 0L; } catch (java.lang.NullPointerException npe) { balance = 0L; } final List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalValueSelected = 0L; // long change = 0L; BigInteger fee = null; // spend dust threshold amount to notification address long amount = SendNotifTxFactory._bNotifTxValue.longValue(); // add Samourai Wallet fee to total amount amount += SendNotifTxFactory._bSWFee.longValue(); // get unspents List<UTXO> utxos = null; if (UTXOFactory.getInstance().getTotalP2SH_P2WPKH() > amount + FeeUtil.getInstance().estimatedFeeSegwit(0, 1, 4).longValue()) { utxos = new ArrayList<UTXO>(); utxos.addAll(UTXOFactory.getInstance().getP2SH_P2WPKH().values()); } else { utxos = APIFactory.getInstance(PayNymDetailsActivity.this).getUtxos(true); } // sort in ascending order by value final List<UTXO> _utxos = utxos; Collections.sort(_utxos, new UTXO.UTXOComparator()); Collections.reverse(_utxos); // get smallest 1 UTXO > than spend + fee + sw fee + dust for (UTXO u : _utxos) { if (u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(1, 4).longValue())) { selectedUTXO.add(u); totalValueSelected += u.getValue(); Log.d("PayNymDetailsActivity", "single output"); Log.d("PayNymDetailsActivity", "value selected:" + u.getValue()); Log.d("PayNymDetailsActivity", "total value selected:" + totalValueSelected); Log.d("PayNymDetailsActivity", "nb inputs:" + u.getOutpoints().size()); break; } } // use normal fee settings SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); long lo = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L; long mi = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L; long hi = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L; if (lo == mi && mi == hi) { SuggestedFee hi_sf = new SuggestedFee(); hi_sf.setDefaultPerKB(BigInteger.valueOf((long) (hi * 1.15 * 1000.0))); FeeUtil.getInstance().setSuggestedFee(hi_sf); } else if (lo == mi) { FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); } else { FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); } if (selectedUTXO.size() == 0) { // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); int selected = 0; // get largest UTXOs > than spend + fee + dust for (UTXO u : _utxos) { selectedUTXO.add(u); totalValueSelected += u.getValue(); selected += u.getOutpoints().size(); if (totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 4).longValue())) { Log.d("PayNymDetailsActivity", "multiple outputs"); Log.d("PayNymDetailsActivity", "total value selected:" + totalValueSelected); Log.d("PayNymDetailsActivity", "nb inputs:" + u.getOutpoints().size()); break; } } // fee = FeeUtil.getInstance().estimatedFee(selected, 4); fee = FeeUtil.getInstance().estimatedFee(selected, 7); } else { // fee = FeeUtil.getInstance().estimatedFee(1, 4); fee = FeeUtil.getInstance().estimatedFee(1, 7); } // reset fee to previous setting FeeUtil.getInstance().setSuggestedFee(suggestedFee); // total amount to spend including fee if ((amount + fee.longValue()) >= balance) { String message = getText(R.string.bip47_notif_tx_insufficient_funds_1) + " "; BigInteger biAmount = SendNotifTxFactory._bSWFee.add(SendNotifTxFactory._bNotifTxValue.add(FeeUtil.getInstance().estimatedFee(1, 4, FeeUtil.getInstance().getLowFee().getDefaultPerKB()))); String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) biAmount.longValue()) / 1e8) + " BTC "; message += strAmount; message += " " + getText(R.string.bip47_notif_tx_insufficient_funds_2); AlertDialog.Builder dlg = new AlertDialog.Builder(PayNymDetailsActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.help, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/article/58-connecting-to-a-paynym-contact")); startActivity(browserIntent); } }) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if (!isFinishing()) { dlg.show(); } return; } // payment code to be notified PaymentCode payment_code; try { payment_code = new PaymentCode(pcode); } catch (AddressFormatException afe) { payment_code = null; } if (payment_code == null) { return; } // create outpoints for spend later final List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>(); for (UTXO u : selectedUTXO) { outpoints.addAll(u.getOutpoints()); } // create inputs from outpoints List<MyTransactionInput> inputs = new ArrayList<MyTransactionInput>(); for (MyTransactionOutPoint o : outpoints) { Script script = new Script(o.getScriptBytes()); if (script.getScriptType() == Script.ScriptType.NO_TYPE) { continue; } MyTransactionInput input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], o, o.getTxHash().toString(), o.getTxOutputN()); inputs.add(input); } // sort inputs Collections.sort(inputs, new SendFactory.BIP69InputComparator()); // find outpoint that corresponds to 0th input MyTransactionOutPoint outPoint = null; for (MyTransactionOutPoint o : outpoints) { if (o.getTxHash().toString().equals(inputs.get(0).getTxHash()) && o.getTxOutputN() == inputs.get(0).getTxPos()) { outPoint = o; break; } } if (outPoint == null) { Toast.makeText(PayNymDetailsActivity.this, R.string.bip47_cannot_identify_outpoint, Toast.LENGTH_SHORT).show(); return; } byte[] op_return = null; // get private key corresponding to outpoint try { // Script inputScript = new Script(outPoint.getConnectedPubKeyScript()); byte[] scriptBytes = outPoint.getConnectedPubKeyScript(); String address = null; if (Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) { address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes)); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } // String address = inputScript.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); ECKey ecKey = SendFactory.getPrivKey(address); if (ecKey == null || !ecKey.hasPrivKey()) { Toast.makeText(PayNymDetailsActivity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show(); return; } // use outpoint for payload masking byte[] privkey = ecKey.getPrivKeyBytes(); byte[] pubkey = payment_code.notificationAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).getPubKey(); byte[] outpoint = outPoint.bitcoinSerialize(); // Log.i("PayNymDetailsActivity", "outpoint:" + Hex.toHexString(outpoint)); // Log.i("PayNymDetailsActivity", "payer shared secret:" + Hex.toHexString(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes())); byte[] mask = PaymentCode.getMask(new SecretPoint(privkey, pubkey).ECDHSecretAsBytes(), outpoint); // Log.i("PayNymDetailsActivity", "mask:" + Hex.toHexString(mask)); // Log.i("PayNymDetailsActivity", "mask length:" + mask.length); // Log.i("PayNymDetailsActivity", "payload0:" + Hex.toHexString(BIP47Util.getInstance(context).getPaymentCode().getPayload())); op_return = PaymentCode.blind(BIP47Util.getInstance(PayNymDetailsActivity.this).getPaymentCode().getPayload(), mask); // Log.i("PayNymDetailsActivity", "payload1:" + Hex.toHexString(op_return)); } catch (InvalidKeyException ike) { Toast.makeText(PayNymDetailsActivity.this, ike.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (InvalidKeySpecException ikse) { Toast.makeText(PayNymDetailsActivity.this, ikse.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (NoSuchAlgorithmException nsae) { Toast.makeText(PayNymDetailsActivity.this, nsae.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (NoSuchProviderException nspe) { Toast.makeText(PayNymDetailsActivity.this, nspe.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (Exception e) { Toast.makeText(PayNymDetailsActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(Hex.toHexString(op_return), BigInteger.ZERO); receivers.put(payment_code.notificationAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).getAddressString(), SendNotifTxFactory._bNotifTxValue); receivers.put(SamouraiWallet.getInstance().isTestNet() ? SendNotifTxFactory.TESTNET_SAMOURAI_NOTIF_TX_FEE_ADDRESS : SendNotifTxFactory.SAMOURAI_NOTIF_TX_FEE_ADDRESS, SendNotifTxFactory._bSWFee); final long change = totalValueSelected - (amount + fee.longValue()); if (change > 0L) { String change_address = BIP84Util.getInstance(PayNymDetailsActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(PayNymDetailsActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString(); receivers.put(change_address, BigInteger.valueOf(change)); } Log.d("PayNymDetailsActivity", "outpoints:" + outpoints.size()); Log.d("PayNymDetailsActivity", "totalValueSelected:" + BigInteger.valueOf(totalValueSelected).toString()); Log.d("PayNymDetailsActivity", "amount:" + BigInteger.valueOf(amount).toString()); Log.d("PayNymDetailsActivity", "change:" + BigInteger.valueOf(change).toString()); Log.d("PayNymDetailsActivity", "fee:" + fee.toString()); if (change < 0L) { Toast.makeText(PayNymDetailsActivity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show(); return; } final MyTransactionOutPoint _outPoint = outPoint; String strNotifTxMsg = getText(R.string.bip47_setup4_text1) + " "; long notifAmount = amount; String strAmount = MonetaryUtil.getInstance().getBTCFormat().format(((double) notifAmount + fee.longValue()) / 1e8) + " BTC "; strNotifTxMsg += strAmount + getText(R.string.bip47_setup4_text2); showFollowAlert(strAmount, view -> { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); Transaction tx = SendFactory.getInstance(PayNymDetailsActivity.this).makeTransaction(0, outpoints, receivers); if (tx != null) { String input0hash = tx.getInput(0L).getOutpoint().getHash().toString(); Log.d("PayNymDetailsActivity", "input0 hash:" + input0hash); Log.d("PayNymDetailsActivity", "_outPoint hash:" + _outPoint.getTxHash().toString()); int input0index = (int) tx.getInput(0L).getOutpoint().getIndex(); Log.d("PayNymDetailsActivity", "input0 index:" + input0index); Log.d("PayNymDetailsActivity", "_outPoint index:" + _outPoint.getTxOutputN()); if (!input0hash.equals(_outPoint.getTxHash().toString()) || input0index != _outPoint.getTxOutputN()) { Toast.makeText(PayNymDetailsActivity.this, R.string.bip47_cannot_compose_notif_tx, Toast.LENGTH_SHORT).show(); return; } tx = SendFactory.getInstance(PayNymDetailsActivity.this).signTransaction(tx); final String hexTx = new String(org.bouncycastle.util.encoders.Hex.encode(tx.bitcoinSerialize())); Log.d("SendActivity", tx.getHashAsString()); Log.d("SendActivity", hexTx); boolean isOK = false; String response = null; try { response = PushTx.getInstance(PayNymDetailsActivity.this).samourai(hexTx); Log.d("SendActivity", "pushTx:" + response); if (response != null) { org.json.JSONObject jsonObject = new org.json.JSONObject(response); if (jsonObject.has("status")) { if (jsonObject.getString("status").equals("ok")) { isOK = true; } } } else { Toast.makeText(PayNymDetailsActivity.this, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show(); return; } if (isOK) { Toast.makeText(PayNymDetailsActivity.this, R.string.payment_channel_init, Toast.LENGTH_SHORT).show(); // set outgoing index for payment code to 0 BIP47Meta.getInstance().setOutgoingIdx(pcode, 0); // Log.i("SendNotifTxFactory", "tx hash:" + tx.getHashAsString()); // status to NO_CFM BIP47Meta.getInstance().setOutgoingStatus(pcode, tx.getHashAsString(), BIP47Meta.STATUS_SENT_NO_CFM); // increment change index if (change > 0L) { BIP49Util.getInstance(PayNymDetailsActivity.this).getWallet().getAccount(0).getChange().incAddrIdx(); } savePayLoad(); } else { Toast.makeText(PayNymDetailsActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } runOnUiThread(() -> { setPayNym(); }); } catch (JSONException je) { Toast.makeText(PayNymDetailsActivity.this, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (MnemonicException.MnemonicLengthException mle) { Toast.makeText(PayNymDetailsActivity.this, "pushTx:" + mle.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (DecoderException de) { Toast.makeText(PayNymDetailsActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (IOException ioe) { Toast.makeText(PayNymDetailsActivity.this, "pushTx:" + ioe.getMessage(), Toast.LENGTH_SHORT).show(); return; } catch (DecryptionException de) { Toast.makeText(PayNymDetailsActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); return; } } Looper.loop(); } }).start(); }); } private void savePayLoad() throws MnemonicException.MnemonicLengthException, DecryptionException, JSONException, IOException { PayloadUtil.getInstance(PayNymDetailsActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(PayNymDetailsActivity.this).getGUID() + AccessFactory.getInstance(PayNymDetailsActivity.this).getPIN())); Log.i(TAG, "savePayLoad: "); } private void doUpdatePayNymInfo(final String pcode) { Disposable disposable = Observable.fromCallable(() -> { JSONObject obj = new JSONObject(); obj.put("nym", pcode); String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym", obj.toString()); // Log.d("PayNymDetailsActivity", res); JSONObject responseObj = new JSONObject(res); if (responseObj.has("nymName")) { final String strNymName = responseObj.getString("nymName"); if (FormatsUtil.getInstance().isValidPaymentCode(BIP47Meta.getInstance().getLabel(pcode))) { BIP47Meta.getInstance().setLabel(pcode, strNymName); } } if (responseObj.has("segwit") && responseObj.getBoolean("segwit")) { BIP47Meta.getInstance().setSegwit(pcode, true); } return true; }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(success -> { if (success) { setPayNym(); savePayLoad(); } }, errror -> { Log.i(TAG, "doUpdatePayNymInfo: ".concat(errror.getMessage())); Toast.makeText(this, "Unable to update paynym", Toast.LENGTH_SHORT).show(); }); disposables.add(disposable); } private void doUploadFollow(final boolean isTrust) { progressBar.setVisibility(View.VISIBLE); Disposable disposable = Observable.fromCallable(() -> { try { JSONObject obj = new JSONObject(); obj.put("code", BIP47Util.getInstance(this).getPaymentCode().toString()); // Log.d("PayNymDetailsActivity", obj.toString()); String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/token", obj.toString()); // Log.d("PayNymDetailsActivity", res); JSONObject responseObj = new JSONObject(res); if (responseObj.has("token")) { String token = responseObj.getString("token"); String sig = MessageSignUtil.getInstance(this).signMessage(BIP47Util.getInstance(this).getNotificationAddress().getECKey(), token); // Log.d("PayNymDetailsActivity", sig); obj = new JSONObject(); obj.put("target", pcode); obj.put("signature", sig); // Log.d("PayNymDetailsActivity", "follow:" + obj.toString()); String endPoint = isTrust ? "api/v1/trust" : "api/v1/follow"; res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(this).postURL("application/json", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + endPoint, obj.toString()); // Log.d("PayNymDetailsActivity", res); responseObj = new JSONObject(res); if (responseObj.has("following")) { responseObj.has("token"); } savePayLoad(); } } catch (JSONException je) { je.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } return true; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(success -> { progressBar.setVisibility(View.INVISIBLE); setPayNym(); doUpdatePayNymInfo(pcode); }, error -> { progressBar.setVisibility(View.INVISIBLE); Log.i(TAG, "doUploadFollow: Error-> ".concat(error.getMessage())); setPayNym(); }); disposables.add(disposable); } private void doSync() { progressBar.setVisibility(View.VISIBLE); Disposable disposable = Observable.fromCallable(() -> { PaymentCode payment_code = new PaymentCode(pcode); int idx = 0; boolean loop = true; ArrayList<String> addrs = new ArrayList<String>(); while (loop) { addrs.clear(); for (int i = idx; i < (idx + 20); i++) { // Log.i("PayNymDetailsActivity", "sync receive from " + i + ":" + BIP47Util.getInstance(PayNymDetailsActivity.this).getReceivePubKey(payment_code, i)); BIP47Meta.getInstance().getIdx4AddrLookup().put(BIP47Util.getInstance(this).getReceivePubKey(payment_code, i), i); BIP47Meta.getInstance().getPCode4AddrLookup().put(BIP47Util.getInstance(this).getReceivePubKey(payment_code, i), payment_code.toString()); addrs.add(BIP47Util.getInstance(this).getReceivePubKey(payment_code, i)); // Log.i("PayNymDetailsActivity", "p2pkh " + i + ":" + BIP47Util.getInstance(PayNymDetailsActivity.this).getReceiveAddress(payment_code, i).getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); } String[] s = addrs.toArray(new String[addrs.size()]); int nb = APIFactory.getInstance(this).syncBIP47Incoming(s); // Log.i("PayNymDetailsActivity", "sync receive idx:" + idx + ", nb == " + nb); if (nb == 0) { loop = false; } idx += 20; } idx = 0; loop = true; BIP47Meta.getInstance().setOutgoingIdx(pcode, 0); while (loop) { addrs.clear(); for (int i = idx; i < (idx + 20); i++) { PaymentAddress sendAddress = BIP47Util.getInstance(this).getSendAddress(payment_code, i); // Log.i("PayNymDetailsActivity", "sync send to " + i + ":" + sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); // BIP47Meta.getInstance().setOutgoingIdx(payment_code.toString(), i); BIP47Meta.getInstance().getIdx4AddrLookup().put(BIP47Util.getInstance(this).getSendPubKey(payment_code, i), i); BIP47Meta.getInstance().getPCode4AddrLookup().put(BIP47Util.getInstance(this).getSendPubKey(payment_code, i), payment_code.toString()); addrs.add(BIP47Util.getInstance(this).getSendPubKey(payment_code, i)); } String[] s = addrs.toArray(new String[addrs.size()]); int nb = APIFactory.getInstance(this).syncBIP47Outgoing(s); // Log.i("PayNymDetailsActivity", "sync send idx:" + idx + ", nb == " + nb); if (nb == 0) { loop = false; } idx += 20; } BIP47Meta.getInstance().pruneIncoming(); PayloadUtil.getInstance(this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(this).getGUID() + AccessFactory.getInstance(this).getPIN())); return true; }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aBoolean -> { progressBar.setVisibility(View.INVISIBLE); setPayNym(); }, error -> { error.printStackTrace(); progressBar.setVisibility(View.INVISIBLE); }); disposables.add(disposable); } }
package de.fau.cs.mad.kwikshop.android.viewmodel; import android.widget.Toast; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import javax.inject.Inject; import de.fau.cs.mad.kwikshop.android.R; import de.fau.cs.mad.kwikshop.android.model.*; import de.fau.cs.mad.kwikshop.android.model.interfaces.ListManager; import de.fau.cs.mad.kwikshop.android.model.interfaces.SimpleStorage; import de.fau.cs.mad.kwikshop.android.model.messages.*; import de.fau.cs.mad.kwikshop.android.util.ItemComparator; import de.fau.cs.mad.kwikshop.android.view.DisplayHelper; import de.fau.cs.mad.kwikshop.android.view.ItemSortType; import de.fau.cs.mad.kwikshop.android.viewmodel.common.*; import de.fau.cs.mad.kwikshop.common.Group; import de.fau.cs.mad.kwikshop.common.Item; import de.fau.cs.mad.kwikshop.common.ShoppingList; import de.fau.cs.mad.kwikshop.common.Unit; public class ShoppingListViewModel extends ListViewModel<ShoppingList> { private final ResourceProvider resourceProvider; //private final ObservableArrayList<Item, Integer> boughtItems = new ObservableArrayList<>(new ItemIdExtractor()); private ItemSortType itemSortType = ItemSortType.MANUAL; private final Command<Integer> toggleIsBoughtCommand = new Command<Integer>() { @Override public void execute(Integer parameter) { toggleIsBoughtCommandExecute(parameter); } }; private final Command<Integer> deleteItemCommand = new Command<Integer>() { @Override public void execute(Integer parameter) { deleteItemCommandExecute(parameter);} }; @Inject public ShoppingListViewModel(ViewLauncher viewLauncher, ListManager<ShoppingList> shoppingListManager, SimpleStorage<Unit> unitStorage, SimpleStorage<Group> groupStorage, ItemParser itemParser, DisplayHelper displayHelper, AutoCompletionHelper autoCompletionHelper, LocationFinderHelper locationFinderHelper, ResourceProvider resourceProvider) { super(viewLauncher, shoppingListManager, unitStorage, groupStorage, itemParser, displayHelper, autoCompletionHelper, locationFinderHelper); if (resourceProvider == null) { throw new IllegalArgumentException("'resourceProvider' must not be null"); } this.resourceProvider = resourceProvider; } /** * Gets the shopping list items that have already been bought */ /*public ObservableArrayList<Item, Integer> getBoughtItems() { return boughtItems; }*/ /** * Gets how items are supposed to be sorted for the current shopping list */ public ItemSortType getItemSortType() { return this.itemSortType; } /** * Sets how items are supposed to be sorted for the current shopping list */ public void setItemSortType(ItemSortType value) { this.itemSortType = value; } public void sortItems() { Collections.sort(getItems(), new ItemComparator(displayHelper, getItemSortType())); moveBoughtItemsToEnd(); updateOrderOfItems(); listener.onItemSortTypeChanged(); } /** * Gets the command to be executed when a item in the view is swiped */ public Command<Integer> getToggleIsBoughtCommand() { return toggleIsBoughtCommand; } /** * Gets the command to be executed when an item's delete-button is pressed */ public Command<Integer> getDeleteItemCommand() { return deleteItemCommand; } @Override public void itemsSwapped(int position1, int position2) { Item item1 = items.get(position1); Item item2 = items.get(position2); item1.setOrder(position1); item2.setOrder(position2); listManager.saveListItem(listId, item1); listManager.saveListItem(listId, item2); } @SuppressWarnings("unused") public void onEventMainThread(ShoppingListChangedEvent event) { if(event.getListId() == this.listId) { if(event.getChangeType() == ListChangeType.Deleted) { finish(); } else if(event.getChangeType() == ListChangeType.PropertiesModified) { loadList(); } } } @SuppressWarnings("unused") public void onEventMainThread(ItemChangedEvent event) { if(event.getListId() == this.listId) { switch (event.getChangeType()) { case Added: // TODO: New Items are moved to the top of the list, maybe we want to change this Item item = listManager.getListItem(listId, event.getItemId()); updateItem(item); sortItems(); updateOrderOfItems(); break; case PropertiesModified: Item item1 = listManager.getListItem(listId, event.getItemId()); updateItem(item1); updateOrderOfItems(); break; case Deleted: items.removeById(event.getItemId()); break; } } } @SuppressWarnings("unused") public void onEventBackgroundThread(MoveAllItemsEvent event) { boolean isBoughtNew = event.isMoveAllToBought(); ShoppingList list = listManager.getList(listId); List<Item> changedItems = new LinkedList<>(); for(Item item : list.getItems()) { if(item.isBought() != isBoughtNew) { item.setBought(isBoughtNew); changedItems.add(item); } } for(Item item : changedItems) { listManager.saveListItem(listId, item); } } @SuppressWarnings("unused") public void onEventMainThread(ItemSortType sortType) { setItemSortType(sortType); sortItems(); } @Override protected void addItemCommandExecute() { ensureIsInitialized(); getItems().enableEvents(); viewLauncher.showItemDetailsView(this.listId); } @Override protected void selectItemCommandExecute(int itemId) { ensureIsInitialized(); viewLauncher.showItemDetailsView(this.listId, itemId); } @Override protected void loadList() { ShoppingList shoppingList = listManager.getList(this.listId); for(Item item : shoppingList.getItems()) { updateItem(item); } int sortTypeInt = shoppingList.getSortTypeInt(); switch (sortTypeInt) { case 1: setItemSortType(ItemSortType.GROUP); break; case 2: setItemSortType(ItemSortType.ALPHABETICALLY); break; default: setItemSortType(ItemSortType.MANUAL); break; } sortItems(); //moveBoughtItemsToEnd(); this.setName(shoppingList.getName()); } private void toggleIsBoughtCommandExecute(final int id) { Item item = items.getById(id); if(item != null) { item.setBought(!item.isBought()); if (item.isBought()) { if (item.isRegularlyRepeatItem() && item.isRemindFromNextPurchaseOn() && item.getLastBought() == null) { Calendar now = Calendar.getInstance(); item.setLastBought(now.getTime()); RegularlyRepeatHelper repeatHelper = RegularlyRepeatHelper.getInstance(); Calendar remindDate = Calendar.getInstance(); switch (item.getPeriodType()) { case DAYS: remindDate.add(Calendar.DAY_OF_MONTH, item.getSelectedRepeatTime()); break; case WEEKS: remindDate.add(Calendar.DAY_OF_MONTH, item.getSelectedRepeatTime() * 7); break; case MONTHS: remindDate.add(Calendar.MONTH, item.getSelectedRepeatTime()); break; } item.setRemindAtDate(remindDate.getTime()); repeatHelper.offerRepeatData(item); DateFormat dateFormat = new SimpleDateFormat(resourceProvider.getString(R.string.time_format)); String message = resourceProvider.getString(R.string.reminder_set_msg) + " " + dateFormat.format(remindDate.getTime()); viewLauncher.showToast(message, Toast.LENGTH_LONG); } } listManager.saveListItem(listId, item); } } private void deleteItemCommandExecute(final int id) { listManager.deleteItem(listId, id); } public int getBoughtItemsCount() { ListIterator li = items.listIterator(items.size()); int i = 0; while(li.hasPrevious()) { Item item = (Item)li.previous(); if(item.isBought()) i++; else break; } return i; } public void moveBoughtItemsToEnd() { Collections.sort(getItems(), new ItemComparator(displayHelper, ItemSortType.BOUGHTITEMS)); } private void updateItem(Item item) { if(item.isBought()) { // Add bought items at the end of the list if (items.size() - 1 >= 0) { items.setOrAddById(items.size() - 1, item); } else { items.setOrAddById(item); } } else { items.setOrAddById(item); } items.notifyItemModified(item); } }