diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/sobiohazardous/minestrappolation/extradecor/block/BlockGoblet.java b/sobiohazardous/minestrappolation/extradecor/block/BlockGoblet.java index 07d6dcd3..8582c526 100644 --- a/sobiohazardous/minestrappolation/extradecor/block/BlockGoblet.java +++ b/sobiohazardous/minestrappolation/extradecor/block/BlockGoblet.java @@ -1,117 +1,119 @@ package sobiohazardous.minestrappolation.extradecor.block; import java.util.List; import java.util.Random; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import sobiohazardous.minestrappolation.extradecor.lib.EDBlockManager; import sobiohazardous.minestrappolation.extradecor.lib.EDItemManager; import sobiohazardous.minestrappolation.extradecor.tileentity.TileEntityGoblet; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.World; public class BlockGoblet extends BlockContainer{ public static final String[] g = new String[] {"0", "1", "2", "3","4","5","6","7"}; public BlockGoblet(int par1, Material par2Material) { super(par1, Material.grass); this.setBlockBounds(1F/16F*5F, 0F, 1F/16F*5F, 1F-1F/16F*5F, 1F-1F/16F*5F, 1F-1F/16F*5F); } @SideOnly(Side.CLIENT) public void registerIcon(IconRegister iconRegister){ this.blockIcon = iconRegister.registerIcon("Minestrappolation:block_CardboardBlock.png"); } public Icon getIcon(int i,int j){ return this.blockIcon; } public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { int meta = par1World.getBlockMetadata(par2, par3, par4); switch(meta){ case 0: if(par5EntityPlayer.getCurrentEquippedItem() == null){ return false; }else if (par5EntityPlayer.getCurrentEquippedItem() != null && par5EntityPlayer.inventory.getCurrentItem().itemID == Item.bucketWater.itemID) { - par5EntityPlayer.inventory.getCurrentItem().stackSize--; + par5EntityPlayer.inventory.getCurrentItem().stackSize --; + par5EntityPlayer.inventory.addItemStackToInventory(new ItemStack(Item.bucketEmpty)); par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 1,2); return true; } else if (par5EntityPlayer.getCurrentEquippedItem() != null && par5EntityPlayer.inventory.getCurrentItem().itemID == Item.bucketMilk.itemID) { - par5EntityPlayer.inventory.getCurrentItem().stackSize--; + par5EntityPlayer.inventory.getCurrentItem().stackSize --; + par5EntityPlayer.inventory.addItemStackToInventory(new ItemStack(Item.bucketEmpty)); par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 2,2); return true; } case 1: par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 0,2); if(par5EntityPlayer.isBurning()){ par5EntityPlayer.extinguish(); } return true; case 2: par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 0,2); par5EntityPlayer.curePotionEffects(new ItemStack(Item.bucketMilk)); return true; } return true; } @Override public TileEntity createNewTileEntity(World world) { return new TileEntityGoblet(); } public int getRenderType(){ return -1; } public boolean isOpaqueCube(){ return false; } public boolean renderAsNormalBlock(){ return false; } public void getSubBlocks(int par1, CreativeTabs par2CreativeTabs, List par3List) { par3List.add(new ItemStack(par1, 1, 0)); par3List.add(new ItemStack(par1, 1, 1)); par3List.add(new ItemStack(par1, 1, 2)); } public int idPicked(World par1World, int par2, int par3, int par4) { return EDItemManager.gobletItem.itemID; } @Override public int idDropped(int par1, Random par2Random, int par3) { return EDItemManager.gobletItem.itemID; } }
false
true
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { int meta = par1World.getBlockMetadata(par2, par3, par4); switch(meta){ case 0: if(par5EntityPlayer.getCurrentEquippedItem() == null){ return false; }else if (par5EntityPlayer.getCurrentEquippedItem() != null && par5EntityPlayer.inventory.getCurrentItem().itemID == Item.bucketWater.itemID) { par5EntityPlayer.inventory.getCurrentItem().stackSize--; par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 1,2); return true; } else if (par5EntityPlayer.getCurrentEquippedItem() != null && par5EntityPlayer.inventory.getCurrentItem().itemID == Item.bucketMilk.itemID) { par5EntityPlayer.inventory.getCurrentItem().stackSize--; par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 2,2); return true; } case 1: par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 0,2); if(par5EntityPlayer.isBurning()){ par5EntityPlayer.extinguish(); } return true; case 2: par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 0,2); par5EntityPlayer.curePotionEffects(new ItemStack(Item.bucketMilk)); return true; } return true; }
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9) { int meta = par1World.getBlockMetadata(par2, par3, par4); switch(meta){ case 0: if(par5EntityPlayer.getCurrentEquippedItem() == null){ return false; }else if (par5EntityPlayer.getCurrentEquippedItem() != null && par5EntityPlayer.inventory.getCurrentItem().itemID == Item.bucketWater.itemID) { par5EntityPlayer.inventory.getCurrentItem().stackSize --; par5EntityPlayer.inventory.addItemStackToInventory(new ItemStack(Item.bucketEmpty)); par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 1,2); return true; } else if (par5EntityPlayer.getCurrentEquippedItem() != null && par5EntityPlayer.inventory.getCurrentItem().itemID == Item.bucketMilk.itemID) { par5EntityPlayer.inventory.getCurrentItem().stackSize --; par5EntityPlayer.inventory.addItemStackToInventory(new ItemStack(Item.bucketEmpty)); par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 2,2); return true; } case 1: par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 0,2); if(par5EntityPlayer.isBurning()){ par5EntityPlayer.extinguish(); } return true; case 2: par1World.setBlock(par2, par3, par4, EDBlockManager.Goblet.blockID, 0,2); par5EntityPlayer.curePotionEffects(new ItemStack(Item.bucketMilk)); return true; } return true; }
diff --git a/org.eclipse.help/src/org/eclipse/help/internal/toc/HrefUtil.java b/org.eclipse.help/src/org/eclipse/help/internal/toc/HrefUtil.java index 2f03bbdca..495e59b3e 100644 --- a/org.eclipse.help/src/org/eclipse/help/internal/toc/HrefUtil.java +++ b/org.eclipse.help/src/org/eclipse/help/internal/toc/HrefUtil.java @@ -1,125 +1,125 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.help.internal.toc; import org.eclipse.core.runtime.Path; public class HrefUtil { /** * Creates /pluginid/directory from directory name */ public static String normalizeDirectoryHref(String pluginID, String dir) { // "" is treated as if extra directory was not provided if (dir == null || dir.length() <= 0) return null; // "." means all the files in the plugin if (".".equals(dir)) //$NON-NLS-1$ dir = ""; //$NON-NLS-1$ // remove not needed trailing separator if (dir.length() > 0 && dir.lastIndexOf('/') == dir.length() - 1) { dir = dir.substring(0, dir.length() - 1); } return normalizeHref(pluginID, dir); } /** * Creates /pluginid/href from href relative to the current plugin * * @param pluginID * id of a plugin to which href is relative * @param href * relative href ex: path[#anchorID] ex: * ../pluginID/path[#anchorID] * @return String representation of href, formatted as * /pluginID/path[#anchorID] */ public final static String normalizeHref(String pluginID, String href) { if (href == null) return null; - href = normalizeDirectoryPath(href); - if (href.startsWith("/")) //$NON-NLS-1$ - // already normalized - return href; if (href.startsWith("http:") //$NON-NLS-1$ || href.startsWith("https:") //$NON-NLS-1$ || href.startsWith("file:") //$NON-NLS-1$ || href.startsWith("jar:")) //$NON-NLS-1$ // external doc return href; + href = normalizeDirectoryPath(href); + if (href.startsWith("/")) //$NON-NLS-1$ + // already normalized + return href; if (href.startsWith("../")) { //$NON-NLS-1$ return href.substring(2); } if (href.length() > 0) { StringBuffer buf = new StringBuffer(2 + pluginID.length() + href.length()); buf.append('/').append(pluginID); buf.append('/').append(href); return buf.toString(); } return "/" + pluginID; //$NON-NLS-1$ } /** * Parses href and obtains plugin id * * @param href * String in format /string1[/string2] * @return plugin ID, or null */ public static String getPluginIDFromHref(String href) { if (href == null || href.length() < 2 || href.charAt(0) != '/') return null; int secondSlashIx = href.indexOf("/", 1); //$NON-NLS-1$ if (secondSlashIx < 0) // href is /pluginID return href.substring(1); // href is /pluginID/path[#anchorID] return href.substring(1, secondSlashIx); } /** * Parses href and obtains resource path relative to the plugin * * @param href * String in format /string1[/[string2]][#string3] * @return relative resource path, or null */ public static String getResourcePathFromHref(String href) { if (href == null) return null; // drop anchor id int anchorIx = href.lastIndexOf("#"); //$NON-NLS-1$ if (anchorIx >= 0) //anchor exists, drop it href = href.substring(0, anchorIx); if (href.length() < 2 || href.charAt(0) != '/') return null; int secondSlashIx = href.indexOf("/", 1); //$NON-NLS-1$ if (secondSlashIx < 0) // href is /pluginID return null; if (secondSlashIx + 1 < href.length()) // href is /pluginID/path return href.substring(secondSlashIx + 1); // href is /pluginID/ return ""; //$NON-NLS-1$ } /** * Parses directory path and obtains simple form path * * @param href * directory path in format a/../c/1 or a//b/c * to /c/1 and a/b/c * @return normalized directory path, or null */ public static String normalizeDirectoryPath(String href) { if (href != null) { return new Path(href).toString(); } return null; } }
false
true
public final static String normalizeHref(String pluginID, String href) { if (href == null) return null; href = normalizeDirectoryPath(href); if (href.startsWith("/")) //$NON-NLS-1$ // already normalized return href; if (href.startsWith("http:") //$NON-NLS-1$ || href.startsWith("https:") //$NON-NLS-1$ || href.startsWith("file:") //$NON-NLS-1$ || href.startsWith("jar:")) //$NON-NLS-1$ // external doc return href; if (href.startsWith("../")) { //$NON-NLS-1$ return href.substring(2); } if (href.length() > 0) { StringBuffer buf = new StringBuffer(2 + pluginID.length() + href.length()); buf.append('/').append(pluginID); buf.append('/').append(href); return buf.toString(); } return "/" + pluginID; //$NON-NLS-1$ }
public final static String normalizeHref(String pluginID, String href) { if (href == null) return null; if (href.startsWith("http:") //$NON-NLS-1$ || href.startsWith("https:") //$NON-NLS-1$ || href.startsWith("file:") //$NON-NLS-1$ || href.startsWith("jar:")) //$NON-NLS-1$ // external doc return href; href = normalizeDirectoryPath(href); if (href.startsWith("/")) //$NON-NLS-1$ // already normalized return href; if (href.startsWith("../")) { //$NON-NLS-1$ return href.substring(2); } if (href.length() > 0) { StringBuffer buf = new StringBuffer(2 + pluginID.length() + href.length()); buf.append('/').append(pluginID); buf.append('/').append(href); return buf.toString(); } return "/" + pluginID; //$NON-NLS-1$ }
diff --git a/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/AbstractChannel.java b/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/AbstractChannel.java index 818f59139..680360a81 100644 --- a/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/AbstractChannel.java +++ b/plugins/org.eclipse.tm.tcf.core/src/org/eclipse/tm/tcf/core/AbstractChannel.java @@ -1,1046 +1,1046 @@ /******************************************************************************* * Copyright (c) 2007, 2010 Wind River Systems, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tm.tcf.core; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.eclipse.tm.internal.tcf.core.ServiceManager; import org.eclipse.tm.internal.tcf.core.Token; import org.eclipse.tm.internal.tcf.core.TransportManager; import org.eclipse.tm.internal.tcf.services.local.LocatorService; import org.eclipse.tm.internal.tcf.services.remote.GenericProxy; import org.eclipse.tm.tcf.protocol.IChannel; import org.eclipse.tm.tcf.protocol.IErrorReport; import org.eclipse.tm.tcf.protocol.IPeer; import org.eclipse.tm.tcf.protocol.IService; import org.eclipse.tm.tcf.protocol.IToken; import org.eclipse.tm.tcf.protocol.JSON; import org.eclipse.tm.tcf.protocol.Protocol; import org.eclipse.tm.tcf.services.ILocator; /** * Abstract implementation of IChannel interface. * * AbstractChannel implements communication link connecting two end points (peers). * The channel asynchronously transmits messages: commands, results and events. * * Clients can subclass AbstractChannel to support particular transport (wire) protocol. * Also, see StreamChannel for stream oriented transport protocols. */ public abstract class AbstractChannel implements IChannel { public interface TraceListener { public void onMessageReceived(char type, String token, String service, String name, byte[] data); public void onMessageSent(char type, String token, String service, String name, byte[] data); public void onChannelClosed(Throwable error); } public interface Proxy { public void onCommand(IToken token, String service, String name, byte[] data); public void onEvent(String service, String name, byte[] data); public void onChannelClosed(Throwable error); } private static class Message { final char type; Token token; String service; String name; byte[] data; boolean is_sent; boolean is_canceled; Collection<TraceListener> trace; Message(char type) { this.type = type; } @Override public String toString() { try { StringBuffer bf = new StringBuffer(); bf.append('[');; bf.append(type); if (token != null) { bf.append(' '); bf.append(token.getID()); } if (service != null) { bf.append(' '); bf.append(service); } if (name != null) { bf.append(' '); bf.append(name); } if (data != null) { int i = 0; while (i < data.length) { int j = i; while (j < data.length && data[j] != 0) j++; bf.append(' '); bf.append(new String(data, i, j - i, "UTF8")); if (j < data.length && data[j] == 0) j++; i = j; } } bf.append(']'); return bf.toString(); } catch (Exception x) { return x.toString(); } } } private static IChannelListener[] listeners_array = new IChannelListener[4]; private final LinkedList<Map<String,String>> redirect_queue = new LinkedList<Map<String,String>>(); private final Map<Class<?>,IService> local_service_by_class = new HashMap<Class<?>,IService>(); private final Map<Class<?>,IService> remote_service_by_class = new HashMap<Class<?>,IService>(); private final Map<String,IService> local_service_by_name = new HashMap<String,IService>(); private final Map<String,IService> remote_service_by_name = new HashMap<String,IService>(); private final LinkedList<Message> out_queue = new LinkedList<Message>(); private final Collection<IChannelListener> channel_listeners = new ArrayList<IChannelListener>(); private final Map<String,IChannel.IEventListener[]> event_listeners = new HashMap<String,IChannel.IEventListener[]>(); private final Map<String,IChannel.ICommandServer> command_servers = new HashMap<String,IChannel.ICommandServer>(); private final Map<String,Message> out_tokens = new HashMap<String,Message>(); private final Thread inp_thread; private final Thread out_thread; private boolean notifying_channel_opened; private boolean registered_with_trasport; private int state = STATE_OPENING; private IToken redirect_command; private final IPeer local_peer; private IPeer remote_peer; private Proxy proxy; private boolean zero_copy; private static final int pending_command_limit = 32; private int local_congestion_level = -100; private int remote_congestion_level = -100; private long local_congestion_time; private int local_congestion_cnt; private Collection<TraceListener> trace_listeners; public static final int EOS = -1, // End Of Stream EOM = -2; // End Of Message protected AbstractChannel(IPeer remote_peer) { this(LocatorService.getLocalPeer(), remote_peer); } protected AbstractChannel(IPeer local_peer, IPeer remote_peer) { assert Protocol.isDispatchThread(); this.remote_peer = remote_peer; this.local_peer = local_peer; inp_thread = new Thread() { final byte[] empty_byte_array = new byte[0]; byte[] buf = new byte[1024]; byte[] eos_err_report; private void error() throws IOException { throw new IOException("Protocol syntax error"); } private byte[] readBytes(int end) throws IOException { int len = 0; for (;;) { int n = read(); if (n <= 0) { if (n == end) break; if (n == EOM) throw new IOException("Unexpected end of message"); if (n < 0) throw new IOException("Communication channel is closed by remote peer"); } if (len >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, len); buf = tmp; } buf[len++] = (byte)n; } if (len == 0) return empty_byte_array; byte[] res = new byte[len]; System.arraycopy(buf, 0, res, 0, len); return res; } private String readString() throws IOException { int len = 0; for (;;) { int n = read(); if (n <= 0) { if (n == 0) break; if (n == EOM) throw new IOException("Unexpected end of message"); if (n < 0) throw new IOException("Communication channel is closed by remote peer"); } if (len >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, len); buf = tmp; } buf[len++] = (byte)n; } return new String(buf, 0, len, "UTF8"); } @Override public void run() { try { while (true) { int n = read(); if (n == EOM) continue; if (n == EOS) { try { eos_err_report = readBytes(EOM); if (eos_err_report.length == 0 || eos_err_report.length == 1 && eos_err_report[0] == 0) eos_err_report = null; } catch (Exception x) { } break; } final Message msg = new Message((char)n); if (read() != 0) error(); switch (msg.type) { case 'C': msg.token = new Token(readBytes(0)); msg.service = readString(); msg.name = readString(); msg.data = readBytes(EOM); break; case 'P': case 'R': case 'N': msg.token = new Token(readBytes(0)); msg.data = readBytes(EOM); break; case 'E': msg.service = readString(); msg.name = readString(); msg.data = readBytes(EOM); break; case 'F': msg.data = readBytes(EOM); break; default: error(); } Protocol.invokeLater(new Runnable() { public void run() { handleInput(msg); } }); int delay = local_congestion_level; if (delay > 0) sleep(delay); } Protocol.invokeLater(new Runnable() { public void run() { - if (out_tokens.isEmpty() && eos_err_report == null) { + if (out_tokens.isEmpty() && eos_err_report == null && state != STATE_OPENING) { close(); } else { IOException x = new IOException("Communication channel is closed by remote peer"); if (eos_err_report != null) { try { Object[] args = JSON.parseSequence(eos_err_report); if (args.length > 0 && args[0] != null) { x.initCause(new Exception(Command.toErrorString(args[0]))); } } catch (IOException e) { } } terminate(x); } } }); } catch (final Throwable x) { try { Protocol.invokeLater(new Runnable() { public void run() { terminate(x); } }); } catch (IllegalStateException y) { // TCF event dispatcher has shut down } } } }; out_thread = new Thread() { @Override public void run() { try { while (true) { Message msg = null; boolean last = false; synchronized (out_queue) { while (out_queue.isEmpty()) out_queue.wait(); msg = out_queue.removeFirst(); if (msg == null) break; last = out_queue.isEmpty(); if (msg.is_canceled) { if (last) flush(); continue; } msg.is_sent = true; } if (msg.trace != null) { final Message m = msg; Protocol.invokeLater(new Runnable() { public void run() { for (TraceListener l : m.trace) { try { l.onMessageSent(m.type, m.token == null ? null : m.token.getID(), m.service, m.name, m.data); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } } }); } write(msg.type); write(0); if (msg.token != null) { write(msg.token.getBytes()); write(0); } if (msg.service != null) { write(msg.service.getBytes("UTF8")); write(0); } if (msg.name != null) { write(msg.name.getBytes("UTF8")); write(0); } if (msg.data != null) { write(msg.data); } write(EOM); int delay = 0; int level = remote_congestion_level; if (level > 0) delay = level * 10; if (last || delay > 0) flush(); if (delay > 0) sleep(delay); else yield(); } write(EOS); write(EOM); flush(); } catch (final Throwable x) { try { Protocol.invokeLater(new Runnable() { public void run() { terminate(x); } }); } catch (IllegalStateException y) { // TCF event dispatcher has shut down } } } }; inp_thread.setName("TCF Channel Receiver"); out_thread.setName("TCF Channel Transmitter"); } protected void start() { assert Protocol.isDispatchThread(); Protocol.invokeLater(new Runnable() { public void run() { try { if (proxy != null) return; if (state == STATE_CLOSED) return; ServiceManager.onChannelCreated(AbstractChannel.this, local_service_by_name); makeServiceByClassMap(local_service_by_name, local_service_by_class); Object[] args = new Object[]{ local_service_by_name.keySet() }; sendEvent(Protocol.getLocator(), "Hello", JSON.toJSONSequence(args)); } catch (IOException x) { terminate(x); } } }); inp_thread.start(); out_thread.start(); } /** * Redirect this channel to given peer using this channel remote peer locator service as a proxy. * @param peer_id - peer that will become new remote communication endpoint of this channel */ public void redirect(String peer_id) { Map<String,String> map = new HashMap<String,String>(); map.put(IPeer.ATTR_ID, peer_id); redirect(map); } /** * Redirect this channel to given peer using this channel remote peer locator service as a proxy. * @param peer_attrs - peer that will become new remote communication endpoint of this channel */ public void redirect(final Map<String,String> peer_attrs) { assert Protocol.isDispatchThread(); if (state == STATE_OPENING) { redirect_queue.add(peer_attrs); } else { assert state == STATE_OPEN; assert redirect_command == null; try { final ILocator l = (ILocator)remote_service_by_class.get(ILocator.class); if (l == null) throw new IOException("Cannot redirect channel: peer " + remote_peer.getID() + " has no locator service"); final String peer_id = peer_attrs.get(IPeer.ATTR_ID); if (peer_id != null && peer_attrs.size() == 1) { final IPeer peer = l.getPeers().get(peer_id); if (peer == null) { // Peer not found, must wait for a while until peer is discovered or time out final boolean[] found = new boolean[1]; Protocol.invokeLater(ILocator.DATA_RETENTION_PERIOD / 3, new Runnable() { public void run() { if (found[0]) return; terminate(new Exception("Peer " + peer_id + " not found")); } }); l.addListener(new ILocator.LocatorListener() { public void peerAdded(IPeer peer) { if (peer.getID().equals(peer_id)) { found[0] = true; state = STATE_OPEN; l.removeListener(this); redirect(peer_id); } } public void peerChanged(IPeer peer) { } public void peerHeartBeat(String id) { } public void peerRemoved(String id) { } }); } else { redirect_command = l.redirect(peer_id, new ILocator.DoneRedirect() { public void doneRedirect(IToken token, Exception x) { assert redirect_command == token; redirect_command = null; if (state != STATE_OPENING) return; if (x != null) terminate(x); remote_peer = peer; remote_service_by_class.clear(); remote_service_by_name.clear(); event_listeners.clear(); } }); } } else { redirect_command = l.redirect(peer_attrs, new ILocator.DoneRedirect() { public void doneRedirect(IToken token, Exception x) { assert redirect_command == token; redirect_command = null; if (state != STATE_OPENING) return; if (x != null) terminate(x); final IPeer parent = remote_peer; remote_peer = new TransientPeer(peer_attrs) { public IChannel openChannel() { IChannel c = parent.openChannel(); c.redirect(peer_attrs); return c; } }; remote_service_by_class.clear(); remote_service_by_name.clear(); event_listeners.clear(); } }); } state = STATE_OPENING; } catch (Throwable x) { terminate(x); } } } private void makeServiceByClassMap(Map<String,IService> by_name, Map<Class<?>,IService> by_class) { for (IService service : by_name.values()) { for (Class<?> fs : service.getClass().getInterfaces()) { if (fs.equals(IService.class)) continue; if (!IService.class.isAssignableFrom(fs)) continue; by_class.put(fs, service); } } } public final int getState() { return state; } public void addChannelListener(IChannelListener listener) { assert Protocol.isDispatchThread(); assert listener != null; channel_listeners.add(listener); } public void removeChannelListener(IChannelListener listener) { assert Protocol.isDispatchThread(); channel_listeners.remove(listener); } public void addTraceListener(TraceListener listener) { if (trace_listeners == null) { trace_listeners = new ArrayList<TraceListener>(); } else { trace_listeners = new ArrayList<TraceListener>(trace_listeners); } trace_listeners.add(listener); } public void removeTraceListener(TraceListener listener) { trace_listeners = new ArrayList<TraceListener>(trace_listeners); trace_listeners.remove(listener); if (trace_listeners.isEmpty()) trace_listeners = null; } public void addEventListener(IService service, IChannel.IEventListener listener) { assert Protocol.isDispatchThread(); IChannel.IEventListener[] list = event_listeners.get(service.getName()); IChannel.IEventListener[] next = new IChannel.IEventListener[list == null ? 1 : list.length + 1]; if (list != null) System.arraycopy(list, 0, next, 0, list.length); next[next.length - 1] = listener; event_listeners.put(service.getName(), next); } public void removeEventListener(IService service, IChannel.IEventListener listener) { assert Protocol.isDispatchThread(); IChannel.IEventListener[] list = event_listeners.get(service.getName()); for (int i = 0; i < list.length; i++) { if (list[i] == listener) { if (list.length == 1) { event_listeners.remove(service.getName()); } else { IChannel.IEventListener[] next = new IChannel.IEventListener[list.length - 1]; System.arraycopy(list, 0, next, 0, i); System.arraycopy(list, i + 1, next, i, next.length - i); event_listeners.put(service.getName(), next); } return; } } } public void addCommandServer(IService service, IChannel.ICommandServer listener) { assert Protocol.isDispatchThread(); if (command_servers.put(service.getName(), listener) != null) { throw new Error("Only one command server per service is allowed"); } } public void removeCommandServer(IService service, IChannel.ICommandServer listener) { assert Protocol.isDispatchThread(); if (command_servers.remove(service.getName()) != listener) { throw new Error("Invalid command server"); } } public void close() { assert Protocol.isDispatchThread(); if (state == STATE_CLOSED) return; try { sendEndOfStream(10000); close(null); } catch (Exception x) { close(x); } } public void terminate(Throwable error) { assert Protocol.isDispatchThread(); if (state == STATE_CLOSED) return; try { sendEndOfStream(500); close(error); } catch (Exception x) { if (error == null) error = x; close(error); } } private void sendEndOfStream(long timeout) throws Exception { synchronized (out_queue) { out_queue.clear(); out_queue.add(null); out_queue.notify(); } out_thread.join(timeout); } private void close(final Throwable error) { assert state != STATE_CLOSED; state = STATE_CLOSED; // Closing channel underlying streams can block for a long time, // so it needs to be done by a background thread. Thread thread = new Thread() { @Override public void run() { try { AbstractChannel.this.stop(); } catch (Exception x) { Protocol.log("Cannot close channel streams", x); } } }; thread.setName("TCF Channel Cleanup"); thread.setDaemon(true); thread.start(); if (error != null && remote_peer instanceof AbstractPeer) { ((AbstractPeer)remote_peer).onChannelTerminated(); } if (registered_with_trasport) { registered_with_trasport = false; TransportManager.channelClosed(this, error); } if (proxy != null) { try { proxy.onChannelClosed(error); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } Protocol.invokeLater(new Runnable() { public void run() { if (!out_tokens.isEmpty()) { Exception x = null; if (error instanceof Exception) x = (Exception)error; else if (error != null) x = new Exception(error); else x = new IOException("Channel is closed"); for (Message msg : out_tokens.values()) { try { String s = msg.toString(); if (s.length() > 72) s = s.substring(0, 72) + "...]"; IOException y = new IOException("Command " + s + " aborted"); y.initCause(x); msg.token.getListener().terminated(msg.token, y); } catch (Throwable e) { Protocol.log("Exception in command listener", e); } } out_tokens.clear(); } if (!channel_listeners.isEmpty()) { listeners_array = channel_listeners.toArray(listeners_array); for (IChannelListener l : listeners_array) { if (l == null) break; try { l.onChannelClosed(error); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } } else if (error != null) { Protocol.log("TCF channel terminated", error); } if (trace_listeners != null) { for (TraceListener l : trace_listeners) { try { l.onChannelClosed(error); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } } } }); } public int getCongestion() { assert Protocol.isDispatchThread(); int level = out_tokens.size() * 100 / pending_command_limit - 100; if (remote_congestion_level > level) level = remote_congestion_level; if (level > 100) level = 100; return level; } public IPeer getLocalPeer() { assert Protocol.isDispatchThread(); return local_peer; } public IPeer getRemotePeer() { assert Protocol.isDispatchThread(); return remote_peer; } public Collection<String> getLocalServices() { assert Protocol.isDispatchThread(); assert state != STATE_OPENING; return local_service_by_name.keySet(); } public Collection<String> getRemoteServices() { assert Protocol.isDispatchThread(); assert state != STATE_OPENING; return remote_service_by_name.keySet(); } @SuppressWarnings("unchecked") public <V extends IService> V getLocalService(Class<V> cls) { assert Protocol.isDispatchThread(); assert state != STATE_OPENING; return (V)local_service_by_class.get(cls); } @SuppressWarnings("unchecked") public <V extends IService> V getRemoteService(Class<V> cls) { assert Protocol.isDispatchThread(); assert state != STATE_OPENING; return (V)remote_service_by_class.get(cls); } public <V extends IService> void setServiceProxy(Class<V> service_interface, IService service_proxy) { if (!notifying_channel_opened) new Error("setServiceProxe() can be called only from channel open call-back"); if (!(remote_service_by_name.get(service_proxy.getName()) instanceof GenericProxy)) throw new Error("Proxy already set"); if (remote_service_by_class.get(service_interface) != null) throw new Error("Proxy already set"); remote_service_by_class.put(service_interface, service_proxy); remote_service_by_name.put(service_proxy.getName(), service_proxy); } public IService getLocalService(String service_name) { assert Protocol.isDispatchThread(); assert state != STATE_OPENING; return local_service_by_name.get(service_name); } public IService getRemoteService(String service_name) { assert Protocol.isDispatchThread(); assert state != STATE_OPENING; return remote_service_by_name.get(service_name); } public void setProxy(Proxy proxy, Collection<String> services) throws IOException { this.proxy = proxy; sendEvent(Protocol.getLocator(), "Hello", JSON.toJSONSequence(new Object[]{ services })); local_service_by_class.clear(); local_service_by_name.clear(); } private void addToOutQueue(Message msg) { msg.trace = trace_listeners; synchronized (out_queue) { out_queue.add(msg); out_queue.notify(); } } public IToken sendCommand(IService service, String name, byte[] args, ICommandListener listener) { assert Protocol.isDispatchThread(); if (state == STATE_OPENING) throw new Error("Channel is waiting for Hello message"); if (state == STATE_CLOSED) throw new Error("Channel is closed"); final Message msg = new Message('C'); msg.service = service.getName(); msg.name = name; msg.data = args; Token token = new Token(listener) { @Override public boolean cancel() { assert Protocol.isDispatchThread(); if (state != STATE_OPEN) return false; synchronized (out_queue) { if (msg.is_sent) return false; msg.is_canceled = true; } out_tokens.remove(msg.token.getID()); return true; } }; msg.token = token; out_tokens.put(token.getID(), msg); addToOutQueue(msg); return token; } public void sendProgress(IToken token, byte[] results) { assert Protocol.isDispatchThread(); if (state != STATE_OPEN) throw new Error("Channel is closed"); Message msg = new Message('P'); msg.data = results; msg.token = (Token)token; addToOutQueue(msg); } public void sendResult(IToken token, byte[] results) { assert Protocol.isDispatchThread(); if (state != STATE_OPEN) throw new Error("Channel is closed"); Message msg = new Message('R'); msg.data = results; msg.token = (Token)token; addToOutQueue(msg); } public void rejectCommand(IToken token) { assert Protocol.isDispatchThread(); if (state != STATE_OPEN) throw new Error("Channel is closed"); Message msg = new Message('N'); msg.token = (Token)token; addToOutQueue(msg); } public void sendEvent(IService service, String name, byte[] args) { assert Protocol.isDispatchThread(); if (!(state == STATE_OPEN || state == STATE_OPENING && service instanceof ILocator)) { throw new Error("Channel is closed"); } Message msg = new Message('E'); msg.service = service.getName(); msg.name = name; msg.data = args; addToOutQueue(msg); } public boolean isZeroCopySupported() { return zero_copy; } @SuppressWarnings("unchecked") private void handleInput(Message msg) { assert Protocol.isDispatchThread(); if (state == STATE_CLOSED) return; if (trace_listeners != null) { for (TraceListener l : trace_listeners) { try { l.onMessageReceived(msg.type, msg.token != null ? msg.token.getID() : null, msg.service, msg.name, msg.data); } catch (Throwable x) { Protocol.log("Exception in trace listener", x); } } } try { Token token = null; switch (msg.type) { case 'P': case 'R': case 'N': String token_id = msg.token.getID(); Message cmd = msg.type == 'P' ? out_tokens.get(token_id) : out_tokens.remove(token_id); if (cmd == null) throw new Exception("Invalid token received: " + token_id); token = cmd.token; break; } switch (msg.type) { case 'C': if (state == STATE_OPENING) { throw new IOException("Received command " + msg.service + "." + msg.name + " before Hello message"); } if (proxy != null) { proxy.onCommand(msg.token, msg.service, msg.name, msg.data); } else { token = msg.token; IChannel.ICommandServer cmds = command_servers.get(msg.service); if (cmds != null) { cmds.command(token, msg.name, msg.data); } else { rejectCommand(token); } } break; case 'P': token.getListener().progress(token, msg.data); sendCongestionLevel(); break; case 'R': token.getListener().result(token, msg.data); sendCongestionLevel(); break; case 'N': token.getListener().terminated(token, new ErrorReport( "Command is not recognized", IErrorReport.TCF_ERROR_INV_COMMAND)); break; case 'E': boolean hello = msg.service.equals(ILocator.NAME) && msg.name.equals("Hello"); if (hello) { remote_service_by_name.clear(); remote_service_by_class.clear(); ServiceManager.onChannelOpened(this, (Collection<String>)JSON.parseSequence(msg.data)[0], remote_service_by_name); makeServiceByClassMap(remote_service_by_name, remote_service_by_class); zero_copy = remote_service_by_name.containsKey("ZeroCopy"); } if (proxy != null && state == STATE_OPEN) { proxy.onEvent(msg.service, msg.name, msg.data); } else if (hello) { assert state == STATE_OPENING; state = STATE_OPEN; assert redirect_command == null; if (redirect_queue.size() > 0) { redirect(redirect_queue.removeFirst()); } else { notifying_channel_opened = true; if (!registered_with_trasport) { TransportManager.channelOpened(this); registered_with_trasport = true; } listeners_array = channel_listeners.toArray(listeners_array); for (IChannelListener l : listeners_array) { if (l == null) break; try { l.onChannelOpened(); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } notifying_channel_opened = false; } } else { IChannel.IEventListener[] list = event_listeners.get(msg.service); if (list != null) { for (int i = 0; i < list.length; i++) { list[i].event(msg.name, msg.data); } } sendCongestionLevel(); } break; case 'F': int len = msg.data.length; if (len > 0 && msg.data[len - 1] == 0) len--; remote_congestion_level = Integer.parseInt(new String(msg.data, 0, len, "ASCII")); break; default: assert false; break; } } catch (Throwable x) { terminate(x); } } private void sendCongestionLevel() throws IOException { if (++local_congestion_cnt < 8) return; local_congestion_cnt = 0; if (state != STATE_OPEN) return; long time = System.currentTimeMillis(); if (time - local_congestion_time < 500) return; assert Protocol.isDispatchThread(); int level = Protocol.getCongestionLevel(); if (level == local_congestion_level) return; int i = (level - local_congestion_level) / 8; if (i != 0) level = local_congestion_level + i; local_congestion_time = time; synchronized (out_queue) { Message msg = out_queue.isEmpty() ? null : out_queue.get(0); if (msg == null || msg.type != 'F') { msg = new Message('F'); out_queue.add(0, msg); out_queue.notify(); } StringBuilder buffer = new StringBuilder(); buffer.append(local_congestion_level); buffer.append((char)0); // 0 terminate msg.data = buffer.toString().getBytes("ASCII"); msg.trace = trace_listeners; local_congestion_level = level; } } /** * Read one byte from the channel input stream. * @return next data byte or EOS (-1) if end of stream is reached, * or EOM (-2) if end of message is reached. * @throws IOException */ protected abstract int read() throws IOException; /** * Write one byte into the channel output stream. * The method argument can be one of two special values: * EOS (-1) end of stream marker; * EOM (-2) end of message marker. * The stream can put the byte into a buffer instead of transmitting it right away. * @param n - the data byte. * @throws IOException */ protected abstract void write(int n) throws IOException; /** * Flush the channel output stream. * All buffered data should be transmitted immediately. * @throws IOException */ protected abstract void flush() throws IOException; /** * Stop (close) channel underlying streams. * If a thread is blocked by read() or write(), it should be * resumed (or interrupted). * @throws IOException */ protected abstract void stop() throws IOException; /** * Write array of bytes into the channel output stream. * The stream can put bytes into a buffer instead of transmitting it right away. * @param buf * @throws IOException */ protected void write(byte[] buf) throws IOException { assert Thread.currentThread() == out_thread; for (int i = 0; i < buf.length; i++) write(buf[i] & 0xff); } }
true
true
protected AbstractChannel(IPeer local_peer, IPeer remote_peer) { assert Protocol.isDispatchThread(); this.remote_peer = remote_peer; this.local_peer = local_peer; inp_thread = new Thread() { final byte[] empty_byte_array = new byte[0]; byte[] buf = new byte[1024]; byte[] eos_err_report; private void error() throws IOException { throw new IOException("Protocol syntax error"); } private byte[] readBytes(int end) throws IOException { int len = 0; for (;;) { int n = read(); if (n <= 0) { if (n == end) break; if (n == EOM) throw new IOException("Unexpected end of message"); if (n < 0) throw new IOException("Communication channel is closed by remote peer"); } if (len >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, len); buf = tmp; } buf[len++] = (byte)n; } if (len == 0) return empty_byte_array; byte[] res = new byte[len]; System.arraycopy(buf, 0, res, 0, len); return res; } private String readString() throws IOException { int len = 0; for (;;) { int n = read(); if (n <= 0) { if (n == 0) break; if (n == EOM) throw new IOException("Unexpected end of message"); if (n < 0) throw new IOException("Communication channel is closed by remote peer"); } if (len >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, len); buf = tmp; } buf[len++] = (byte)n; } return new String(buf, 0, len, "UTF8"); } @Override public void run() { try { while (true) { int n = read(); if (n == EOM) continue; if (n == EOS) { try { eos_err_report = readBytes(EOM); if (eos_err_report.length == 0 || eos_err_report.length == 1 && eos_err_report[0] == 0) eos_err_report = null; } catch (Exception x) { } break; } final Message msg = new Message((char)n); if (read() != 0) error(); switch (msg.type) { case 'C': msg.token = new Token(readBytes(0)); msg.service = readString(); msg.name = readString(); msg.data = readBytes(EOM); break; case 'P': case 'R': case 'N': msg.token = new Token(readBytes(0)); msg.data = readBytes(EOM); break; case 'E': msg.service = readString(); msg.name = readString(); msg.data = readBytes(EOM); break; case 'F': msg.data = readBytes(EOM); break; default: error(); } Protocol.invokeLater(new Runnable() { public void run() { handleInput(msg); } }); int delay = local_congestion_level; if (delay > 0) sleep(delay); } Protocol.invokeLater(new Runnable() { public void run() { if (out_tokens.isEmpty() && eos_err_report == null) { close(); } else { IOException x = new IOException("Communication channel is closed by remote peer"); if (eos_err_report != null) { try { Object[] args = JSON.parseSequence(eos_err_report); if (args.length > 0 && args[0] != null) { x.initCause(new Exception(Command.toErrorString(args[0]))); } } catch (IOException e) { } } terminate(x); } } }); } catch (final Throwable x) { try { Protocol.invokeLater(new Runnable() { public void run() { terminate(x); } }); } catch (IllegalStateException y) { // TCF event dispatcher has shut down } } } }; out_thread = new Thread() { @Override public void run() { try { while (true) { Message msg = null; boolean last = false; synchronized (out_queue) { while (out_queue.isEmpty()) out_queue.wait(); msg = out_queue.removeFirst(); if (msg == null) break; last = out_queue.isEmpty(); if (msg.is_canceled) { if (last) flush(); continue; } msg.is_sent = true; } if (msg.trace != null) { final Message m = msg; Protocol.invokeLater(new Runnable() { public void run() { for (TraceListener l : m.trace) { try { l.onMessageSent(m.type, m.token == null ? null : m.token.getID(), m.service, m.name, m.data); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } } }); } write(msg.type); write(0); if (msg.token != null) { write(msg.token.getBytes()); write(0); } if (msg.service != null) { write(msg.service.getBytes("UTF8")); write(0); } if (msg.name != null) { write(msg.name.getBytes("UTF8")); write(0); } if (msg.data != null) { write(msg.data); } write(EOM); int delay = 0; int level = remote_congestion_level; if (level > 0) delay = level * 10; if (last || delay > 0) flush(); if (delay > 0) sleep(delay); else yield(); } write(EOS); write(EOM); flush(); } catch (final Throwable x) { try { Protocol.invokeLater(new Runnable() { public void run() { terminate(x); } }); } catch (IllegalStateException y) { // TCF event dispatcher has shut down } } } }; inp_thread.setName("TCF Channel Receiver"); out_thread.setName("TCF Channel Transmitter"); }
protected AbstractChannel(IPeer local_peer, IPeer remote_peer) { assert Protocol.isDispatchThread(); this.remote_peer = remote_peer; this.local_peer = local_peer; inp_thread = new Thread() { final byte[] empty_byte_array = new byte[0]; byte[] buf = new byte[1024]; byte[] eos_err_report; private void error() throws IOException { throw new IOException("Protocol syntax error"); } private byte[] readBytes(int end) throws IOException { int len = 0; for (;;) { int n = read(); if (n <= 0) { if (n == end) break; if (n == EOM) throw new IOException("Unexpected end of message"); if (n < 0) throw new IOException("Communication channel is closed by remote peer"); } if (len >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, len); buf = tmp; } buf[len++] = (byte)n; } if (len == 0) return empty_byte_array; byte[] res = new byte[len]; System.arraycopy(buf, 0, res, 0, len); return res; } private String readString() throws IOException { int len = 0; for (;;) { int n = read(); if (n <= 0) { if (n == 0) break; if (n == EOM) throw new IOException("Unexpected end of message"); if (n < 0) throw new IOException("Communication channel is closed by remote peer"); } if (len >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, len); buf = tmp; } buf[len++] = (byte)n; } return new String(buf, 0, len, "UTF8"); } @Override public void run() { try { while (true) { int n = read(); if (n == EOM) continue; if (n == EOS) { try { eos_err_report = readBytes(EOM); if (eos_err_report.length == 0 || eos_err_report.length == 1 && eos_err_report[0] == 0) eos_err_report = null; } catch (Exception x) { } break; } final Message msg = new Message((char)n); if (read() != 0) error(); switch (msg.type) { case 'C': msg.token = new Token(readBytes(0)); msg.service = readString(); msg.name = readString(); msg.data = readBytes(EOM); break; case 'P': case 'R': case 'N': msg.token = new Token(readBytes(0)); msg.data = readBytes(EOM); break; case 'E': msg.service = readString(); msg.name = readString(); msg.data = readBytes(EOM); break; case 'F': msg.data = readBytes(EOM); break; default: error(); } Protocol.invokeLater(new Runnable() { public void run() { handleInput(msg); } }); int delay = local_congestion_level; if (delay > 0) sleep(delay); } Protocol.invokeLater(new Runnable() { public void run() { if (out_tokens.isEmpty() && eos_err_report == null && state != STATE_OPENING) { close(); } else { IOException x = new IOException("Communication channel is closed by remote peer"); if (eos_err_report != null) { try { Object[] args = JSON.parseSequence(eos_err_report); if (args.length > 0 && args[0] != null) { x.initCause(new Exception(Command.toErrorString(args[0]))); } } catch (IOException e) { } } terminate(x); } } }); } catch (final Throwable x) { try { Protocol.invokeLater(new Runnable() { public void run() { terminate(x); } }); } catch (IllegalStateException y) { // TCF event dispatcher has shut down } } } }; out_thread = new Thread() { @Override public void run() { try { while (true) { Message msg = null; boolean last = false; synchronized (out_queue) { while (out_queue.isEmpty()) out_queue.wait(); msg = out_queue.removeFirst(); if (msg == null) break; last = out_queue.isEmpty(); if (msg.is_canceled) { if (last) flush(); continue; } msg.is_sent = true; } if (msg.trace != null) { final Message m = msg; Protocol.invokeLater(new Runnable() { public void run() { for (TraceListener l : m.trace) { try { l.onMessageSent(m.type, m.token == null ? null : m.token.getID(), m.service, m.name, m.data); } catch (Throwable x) { Protocol.log("Exception in channel listener", x); } } } }); } write(msg.type); write(0); if (msg.token != null) { write(msg.token.getBytes()); write(0); } if (msg.service != null) { write(msg.service.getBytes("UTF8")); write(0); } if (msg.name != null) { write(msg.name.getBytes("UTF8")); write(0); } if (msg.data != null) { write(msg.data); } write(EOM); int delay = 0; int level = remote_congestion_level; if (level > 0) delay = level * 10; if (last || delay > 0) flush(); if (delay > 0) sleep(delay); else yield(); } write(EOS); write(EOM); flush(); } catch (final Throwable x) { try { Protocol.invokeLater(new Runnable() { public void run() { terminate(x); } }); } catch (IllegalStateException y) { // TCF event dispatcher has shut down } } } }; inp_thread.setName("TCF Channel Receiver"); out_thread.setName("TCF Channel Transmitter"); }
diff --git a/src/newbieprotect/Storage.java b/src/newbieprotect/Storage.java index 28507a1..5e1730e 100644 --- a/src/newbieprotect/Storage.java +++ b/src/newbieprotect/Storage.java @@ -1,106 +1,107 @@ package newbieprotect; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.sk89q.worldguard.bukkit.BukkitUtil; import com.sk89q.worldguard.bukkit.WGBukkit; public class Storage { private Nprotect plugin; private Config config; private File configfile; public Storage(Nprotect plugin, Config config) { this.plugin = plugin; this.config = config; configfile = new File(plugin.getDataFolder(),"playerdata.yml"); } private ConcurrentHashMap<String,Long> playerprotecttime = new ConcurrentHashMap<String,Long>(); protected void protectPlayer(String playername, long starttimestamp) { playerprotecttime.put(playername, starttimestamp); } protected void unprotectPlayer(String playername) { playerprotecttime.remove(playername); } protected boolean isPlayerProtected(String playername) { if (playerprotecttime.containsKey(playername) && System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime) { unprotectPlayer(playername); } Player player = Bukkit.getPlayerExact(playername); - try { + if (Bukkit.getPluginManager().getPlugin("WorldGuard") != null) + { List<String> aregions = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(player.getLocation())); for (String region : aregions) { if (config.disabledegions.contains(region)) { return false; } } - } catch (Exception e) {} + } return playerprotecttime.containsKey(playername); } protected void loadTimeConfig() { FileConfiguration config = YamlConfiguration.loadConfiguration(configfile); ConfigurationSection cs = config.getConfigurationSection(""); if (cs != null) { for (String playername : cs.getKeys(false)) { playerprotecttime.put(playername, config.getLong(playername)); } } } protected void saveTimeConfig() { FileConfiguration config = new YamlConfiguration(); for (String playername : playerprotecttime.keySet()) { config.set(playername, playerprotecttime.get(playername)); } try { config.save(configfile); } catch (IOException e) {} } private int taskid; protected void startCheck() { Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable(){ public void run() { for (String playername : playerprotecttime.keySet()) { if (System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime) { unprotectPlayer(playername); } } } }, 0, 20*60); } protected void stopCheck() { Bukkit.getScheduler().cancelTask(taskid); } }
false
true
protected boolean isPlayerProtected(String playername) { if (playerprotecttime.containsKey(playername) && System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime) { unprotectPlayer(playername); } Player player = Bukkit.getPlayerExact(playername); try { List<String> aregions = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(player.getLocation())); for (String region : aregions) { if (config.disabledegions.contains(region)) { return false; } } } catch (Exception e) {} return playerprotecttime.containsKey(playername); }
protected boolean isPlayerProtected(String playername) { if (playerprotecttime.containsKey(playername) && System.currentTimeMillis() - playerprotecttime.get(playername) > config.protecttime) { unprotectPlayer(playername); } Player player = Bukkit.getPlayerExact(playername); if (Bukkit.getPluginManager().getPlugin("WorldGuard") != null) { List<String> aregions = WGBukkit.getRegionManager(player.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(player.getLocation())); for (String region : aregions) { if (config.disabledegions.contains(region)) { return false; } } } return playerprotecttime.containsKey(playername); }
diff --git a/src/main/java/net/praqma/hudson/scm/PucmScm.java b/src/main/java/net/praqma/hudson/scm/PucmScm.java index e2af37d..0d13151 100644 --- a/src/main/java/net/praqma/hudson/scm/PucmScm.java +++ b/src/main/java/net/praqma/hudson/scm/PucmScm.java @@ -1,736 +1,736 @@ package net.praqma.hudson.scm; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.FilePath.FileCallable; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.FreeStyleBuild; import hudson.model.ParameterValue; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Job; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.VariableResolver; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.praqma.clearcase.ucm.UCMException; import net.praqma.clearcase.ucm.entities.Cool; import net.praqma.clearcase.ucm.entities.Project; import net.praqma.clearcase.ucm.entities.Baseline; import net.praqma.clearcase.ucm.entities.Activity; import net.praqma.clearcase.ucm.entities.Component; import net.praqma.clearcase.ucm.entities.UCM; import net.praqma.clearcase.ucm.utils.BaselineList; import net.praqma.clearcase.ucm.entities.Stream; import net.praqma.clearcase.ucm.entities.UCMEntity; import net.praqma.clearcase.ucm.entities.Version; import net.praqma.clearcase.ucm.view.SnapshotView; import net.praqma.clearcase.ucm.view.SnapshotView.COMP; import net.praqma.clearcase.ucm.view.UCMView; import net.praqma.clearcase.ucm.utils.BaselineDiff; import net.praqma.hudson.Config; import net.praqma.hudson.exception.ScmException; import net.praqma.hudson.scm.PucmState.State; import net.praqma.util.debug.PraqmaLogger; import net.praqma.util.debug.PraqmaLogger.Logger; import net.praqma.util.structure.Tuple; import net.sf.json.JSONObject; //import net.praqma.hudson.Version; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.export.Exported; /** * CC4HClass is responsible for everything regarding Hudsons connection to * ClearCase pre-build. This class defines all the files required by the user. * The information can be entered on the config page. * * @author Troels Selch S�rensen * @author Margit Bennetzen * */ public class PucmScm extends SCM { private String levelToPoll; private String loadModule; private String component; private String stream; private boolean newest; private Baseline bl; private List<String> levels = null; private List<String> loadModules = null; // private BaselineList baselines; private boolean compRevCalled; private StringBuffer pollMsgs = new StringBuffer(); private Stream integrationstream; private Component comp; private SnapshotView sv = null; private boolean doPostBuild = true; private String buildProject; private String jobName = ""; private Integer jobNumber; private String id = ""; private Logger logger = null; public static PucmState pucm = new PucmState(); /** * The constructor is used by Hudson to create the instance of the plugin * needed for a connection to ClearCase. It is annotated with * <code>@DataBoundConstructor</code> to tell Hudson where to put the * information retrieved from the configuration page in the WebUI. * * @param component * defines the component needed to find baselines. * @param levelToPoll * defines the level to poll ClearCase for. * @param loadModule * tells if we should load all modules or only the ones that are * modifiable. * @param stream * defines the stream needed to find baselines. * @param newest * tells whether we should build only the newest baseline. * @param newerThanRecommended * tells whether we should look at all baselines or only ones * newer than the recommended baseline */ @DataBoundConstructor public PucmScm( String component, String levelToPoll, String loadModule, String stream, boolean newest, boolean testing, String buildProject ) { this.logger = PraqmaLogger.getLogger(); logger.trace_function(); logger.debug( "PucmSCM constructor" ); this.component = component; this.levelToPoll = levelToPoll; this.loadModule = loadModule; this.stream = stream; this.newest = newest; this.buildProject = buildProject; } @Override public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger = PraqmaLogger.getLogger(); File rdir = build.getRootDir(); File pdir = build.getProject().getRootDir(); logger.setLocalLog( new File( rdir + System.getProperty( "file.separator" ) + "log.log" ) ); if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.subscribe( i.trim() ); } } Cool.setLogger( logger ); logger.debug( "pdir=" + pdir ); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName().replace(' ','_'); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); state.setLogger( logger ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.subscribe( i.trim() ); } } String baselinevalue = ""; Collection c = build.getBuildVariables().keySet(); Iterator i = c.iterator(); while ( i.hasNext() ) { String next = i.next().toString(); if ( next.equalsIgnoreCase( "pucm_baseline" ) ) baselinevalue = next; } if ( build.getBuildVariables().get(baselinevalue)!=null ) { String baselinename = (String) build.getBuildVariables().get( baselinevalue ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\n[PUCM] Using baseline: " + baselinename + " from integrationstream " + state.getStream().GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter '"+baselinename+"'." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { // baselinesToBuild( component, stream, build.getProject(), // build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( "[PUCM] " + e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { state.getBaseline().Load(); } catch ( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if ( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if ( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if ( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if ( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if ( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if ( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } - CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject, logger ); + CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), state.getStream().GetFQName(), loadModule, state.getBaseline().GetFQName(), buildProject, logger ); //String changelog = workspace.act( ct ); Tuple<String, String> ctresult = workspace.act( ct ); String changelog = ctresult.t1; logger.empty( ctresult.t2 ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch ( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } // doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); logger.warning( e ); e.printStackTrace( consoleOutput ); doPostBuild = false; result = false; } } // pucm.add( new PucmState( build.getParent().getDisplayName(), // build.getNumber(), bl, null, comp, doPostBuild ) ); // state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; } @Override public ChangeLogParser createChangeLogParser() { logger.trace_function(); return new ChangeLogParserImpl(); } @Override public PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline ) throws IOException, InterruptedException { logger = PraqmaLogger.getLogger(); this.id = "[" + project.getDisplayName() + "::" + project.getNextBuildNumber() + "]"; logger.trace_function(); logger.debug( id + "PucmSCM Pollingresult" ); /* Make a state object, which is only temporary, only to determine if there's baselines to build this object will be stored in checkout */ jobName = project.getDisplayName().replace(' ','_'); jobNumber = project.getNextBuildNumber(); /* This number is not the final job number */ State state = pucm.getState( jobName, jobNumber ); PollingResult p; try { // baselinesToBuild( component, stream, project, // project.getDisplayName(), project.getNextBuildNumber() ); baselinesToBuild( project, state ); compRevCalled = true; logger.info( id + "Polling result = BUILD NOW" ); p = PollingResult.BUILD_NOW; } catch ( ScmException e ) { logger.info( id + "Polling result = NO CHANGES" ); p = PollingResult.NO_CHANGES; PrintStream consoleOut = listener.getLogger(); consoleOut.println( pollMsgs + "\n[PUCM] " + e.getMessage() ); pollMsgs = new StringBuffer(); logger.debug( id + "Removed job " + state.getJobNumber() + " from list" ); state.remove(); } logger.debug( id + "FINAL Polling result = " + p.change.toString() ); return p; } @Override public SCMRevisionState calcRevisionsFromBuild( AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( id + "PucmSCM calcRevisionsFromBuild" ); // PrintStream hudsonOut = listener.getLogger(); SCMRevisionStateImpl scmRS = null; if ( !( bl == null ) ) { scmRS = new SCMRevisionStateImpl(); } return scmRS; } private void baselinesToBuild( AbstractProject<?, ?> project, State state ) throws ScmException { logger.trace_function(); /* Store the component to the state */ try { state.setComponent( UCMEntity.GetComponent( component, false ) ); } catch ( UCMException e ) { throw new ScmException( "Could not get component. " + e.getMessage() ); } /* Store the stream to the state */ try { state.setStream( UCMEntity.GetStream( stream, false ) ); } catch ( UCMException e ) { throw new ScmException( "Could not get stream. " + e.getMessage() ); } state.setPlevel( Project.Plevel.valueOf( levelToPoll ) ); /* The baseline list */ BaselineList baselines = null; try { pollMsgs.append( "[PUCM] Getting all baselines for :\n[PUCM] * Stream: " ); pollMsgs.append( stream ); pollMsgs.append( "\n[PUCM] * Component: " ); pollMsgs.append( component ); pollMsgs.append( "\n[PUCM] * Promotionlevel: " ); pollMsgs.append( levelToPoll ); pollMsgs.append( "\n" ); baselines = state.getComponent().GetBaselines( state.getStream(), state.getPlevel() ); } catch ( UCMException e ) { throw new ScmException( "Could not retrieve baselines from repository. " + e.getMessage() ); } if ( baselines.size() > 0 ) { printBaselines( baselines ); logger.debug( id + "PUCM=" + pucm.stringify() ); try { List<Baseline> baselinelist = state.getStream().GetRecommendedBaselines(); pollMsgs.append( "[PUCM] Recommended baseline(s):" ); for ( Baseline b : baselinelist ) { pollMsgs.append( "\n[PUCM] " + b.GetShortname() ); } pollMsgs.append( "\n" ); /* Determine the baseline to build */ bl = null; state.setBaseline( null ); /* For each baseline retrieved from ClearCase */ // for ( Baseline b : baselinelist ) int start = 0; int stop = baselines.size(); int increment = 1; if ( newest ) { start = baselines.size() - 1; // stop = 0; increment = -1; } /* Find the Baseline to build */ for ( int i = start ; i < stop && i >= 0 ; i += increment ) { /* The current baseline */ Baseline b = baselines.get( i ); State cstate = pucm.getStateByBaseline( jobName, b.GetFQName() ); /* * The baseline is in progress, determine if the job is * still running */ // if( thisJob.containsKey( b.GetFQName() ) ) if ( cstate != null ) { // Integer bnum = thisJob.get( b.GetFQName() ); // State Integer bnum = cstate.getJobNumber(); Object o = project.getBuildByNumber( bnum ); Build bld = (Build) o; /* The job is not running */ if ( !bld.isLogUpdated() ) { logger.debug( id + "Job " + bld.getNumber() + " is not building, using baseline: " + b ); bl = b; // thisJob.put( b.GetFQName(), state.getJobNumber() // ); break; } else { logger.debug( id + "Job " + bld.getNumber() + " is building " + cstate.getBaseline().GetFQName() ); } } /* The baseline is available */ else { bl = b; // thisJob.put( b.GetFQName(), state.getJobNumber() ); logger.debug( id + "The baseline " + b + " is available" ); break; } } if ( bl == null ) { logger.log( id + "No baselines available on chosen parameters." ); throw new ScmException( "No baselines available on chosen parameters." ); } pollMsgs.append( "\n[PUCM] Building baseline: " + bl + "\n" ); state.setBaseline( bl ); /* Store the baseline to build */ // thisJob.put( bl.GetFQName(), state.getJobNumber() ); } catch ( UCMException e ) { throw new ScmException( "Could not get recommended baselines. " + e.getMessage() ); } } else { throw new ScmException( "No baselines on chosen parameters." ); } // logger.debug( id + "PRINTING THIS JOB:" ); // logger.debug( net.praqma.util.structure.Printer.mapPrinterToString( // thisJob ) ); } private void printBaselines( BaselineList baselines ) { pollMsgs.append( "[PUCM] Retrieved baselines:" ); if ( !( baselines.size() > 20 ) ) { for ( Baseline b : baselines ) { pollMsgs.append( "\n[PUCM]" + b.GetShortname() ); } } else { int i = baselines.size(); pollMsgs.append( "\n[PUCM] " + baselines.get( 0 ).GetShortname() + "\n[PUCM] " ); pollMsgs.append( baselines.get( 1 ).GetShortname() + "\n[PUCM] " ); pollMsgs.append( baselines.get( 2 ).GetShortname() + "\n[PUCM] " ); pollMsgs.append( "...("+ (i-6) +" baselines not shown)...\n[PUCM] " ); pollMsgs.append( baselines.get( i - 3 ).GetShortname() + "\n[PUCM] " ); pollMsgs.append( baselines.get( i - 2 ).GetShortname() + "\n[PUCM] " ); pollMsgs.append( baselines.get( i - 1 ).GetShortname() + "\n" ); } } /* * The following getters and booleans (six in all) are used to display saved * userdata in Hudsons gui */ public String getLevelToPoll() { logger.trace_function(); return levelToPoll; } public String getComponent() { logger.trace_function(); return component; } public String getStream() { logger.trace_function(); return stream; } public String getLoadModule() { logger.trace_function(); return loadModule; } public boolean isNewest() { logger.trace_function(); return newest; } /* * getStreamObject() and getBaseline() are used by PucmNotifier to get the * Baseline and Stream in use */ public Stream getStreamObject() { logger.trace_function(); return integrationstream; } @Exported public Baseline getBaseline() { logger.trace_function(); return bl; } @Exported public boolean doPostbuild() { logger.trace_function(); return doPostBuild; } public String getBuildProject() { logger.trace_function(); return buildProject; } /** * This class is used to describe the plugin to Hudson * * @author Troels Selch S�rensen * @author Margit Bennetzen * */ @Extension public static class PucmScmDescriptor extends SCMDescriptor<PucmScm> { private String cleartool; private List<String> loadModules; public PucmScmDescriptor() { super( PucmScm.class, null ); loadModules = getLoadModules(); load(); Config.setContext(); } /** * This method is called, when the user saves the global Hudson * configuration. */ @Override public boolean configure( org.kohsuke.stapler.StaplerRequest req, JSONObject json ) throws FormException { cleartool = req.getParameter( "PUCM.cleartool" ).trim(); save(); return true; } /** * This is called by Hudson to discover the plugin name */ @Override public String getDisplayName() { return "Praqmatic UCM"; } /** * This method is called by the scm/Pucm/global.jelly to validate the * input without reloading the global configuration page * * @param value * @return */ public FormValidation doExecutableCheck( @QueryParameter String value ) { return FormValidation.validateExecutable( value ); } /** * Called by Hudson. If the user does not input a command for Hudson to * use when polling, default value is returned * * @return */ public String getCleartool() { if ( cleartool == null || cleartool.equals( "" ) ) { return "cleartool"; } return cleartool; } /** * Used by Hudson to display a list of valid promotion levels to build * from. The list of promotion levels is hard coded in * net.praqma.hudson.Config.java * * @return */ public List<String> getLevels() { return Config.getLevels(); } /** * Used by Hudson to display a list of loadModules (whether to poll all * or only modifiable elements * * @return */ public List<String> getLoadModules() { loadModules = new ArrayList<String>(); loadModules.add( "All" ); loadModules.add( "Modifiable" ); return loadModules; } } }
true
true
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger = PraqmaLogger.getLogger(); File rdir = build.getRootDir(); File pdir = build.getProject().getRootDir(); logger.setLocalLog( new File( rdir + System.getProperty( "file.separator" ) + "log.log" ) ); if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.subscribe( i.trim() ); } } Cool.setLogger( logger ); logger.debug( "pdir=" + pdir ); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName().replace(' ','_'); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); state.setLogger( logger ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.subscribe( i.trim() ); } } String baselinevalue = ""; Collection c = build.getBuildVariables().keySet(); Iterator i = c.iterator(); while ( i.hasNext() ) { String next = i.next().toString(); if ( next.equalsIgnoreCase( "pucm_baseline" ) ) baselinevalue = next; } if ( build.getBuildVariables().get(baselinevalue)!=null ) { String baselinename = (String) build.getBuildVariables().get( baselinevalue ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\n[PUCM] Using baseline: " + baselinename + " from integrationstream " + state.getStream().GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter '"+baselinename+"'." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { // baselinesToBuild( component, stream, build.getProject(), // build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( "[PUCM] " + e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { state.getBaseline().Load(); } catch ( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if ( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if ( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if ( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if ( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if ( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if ( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject, logger ); //String changelog = workspace.act( ct ); Tuple<String, String> ctresult = workspace.act( ct ); String changelog = ctresult.t1; logger.empty( ctresult.t2 ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch ( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } // doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); logger.warning( e ); e.printStackTrace( consoleOutput ); doPostBuild = false; result = false; } } // pucm.add( new PucmState( build.getParent().getDisplayName(), // build.getNumber(), bl, null, comp, doPostBuild ) ); // state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; }
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger = PraqmaLogger.getLogger(); File rdir = build.getRootDir(); File pdir = build.getProject().getRootDir(); logger.setLocalLog( new File( rdir + System.getProperty( "file.separator" ) + "log.log" ) ); if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.subscribe( i.trim() ); } } Cool.setLogger( logger ); logger.debug( "pdir=" + pdir ); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName().replace(' ','_'); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); state.setLogger( logger ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.subscribe( i.trim() ); } } String baselinevalue = ""; Collection c = build.getBuildVariables().keySet(); Iterator i = c.iterator(); while ( i.hasNext() ) { String next = i.next().toString(); if ( next.equalsIgnoreCase( "pucm_baseline" ) ) baselinevalue = next; } if ( build.getBuildVariables().get(baselinevalue)!=null ) { String baselinename = (String) build.getBuildVariables().get( baselinevalue ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\n[PUCM] Using baseline: " + baselinename + " from integrationstream " + state.getStream().GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter '"+baselinename+"'." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { // baselinesToBuild( component, stream, build.getProject(), // build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( "[PUCM] " + e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { state.getBaseline().Load(); } catch ( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if ( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if ( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if ( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if ( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if ( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if ( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), state.getStream().GetFQName(), loadModule, state.getBaseline().GetFQName(), buildProject, logger ); //String changelog = workspace.act( ct ); Tuple<String, String> ctresult = workspace.act( ct ); String changelog = ctresult.t1; logger.empty( ctresult.t2 ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch ( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } // doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); logger.warning( e ); e.printStackTrace( consoleOutput ); doPostBuild = false; result = false; } } // pucm.add( new PucmState( build.getParent().getDisplayName(), // build.getNumber(), bl, null, comp, doPostBuild ) ); // state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; }
diff --git a/src/java/org/apache/cassandra/db/CollationController.java b/src/java/org/apache/cassandra/db/CollationController.java index b59e52616..95042d9d7 100644 --- a/src/java/org/apache/cassandra/db/CollationController.java +++ b/src/java/org/apache/cassandra/db/CollationController.java @@ -1,259 +1,259 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.cassandra.db; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import com.google.common.collect.Iterables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.db.columniterator.IColumnIterator; import org.apache.cassandra.db.columniterator.SimpleAbstractColumnIterator; import org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy; import org.apache.cassandra.db.filter.NamesQueryFilter; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.db.marshal.CounterColumnType; import org.apache.cassandra.io.sstable.SSTable; import org.apache.cassandra.io.sstable.SSTableReader; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.utils.CloseableIterator; public class CollationController { private static Logger logger = LoggerFactory.getLogger(CollationController.class); private final ColumnFamilyStore cfs; private final boolean mutableColumns; private final QueryFilter filter; private final int gcBefore; private int sstablesIterated = 0; public CollationController(ColumnFamilyStore cfs, boolean mutableColumns, QueryFilter filter, int gcBefore) { this.cfs = cfs; this.mutableColumns = mutableColumns; this.filter = filter; this.gcBefore = gcBefore; } public ColumnFamily getTopLevelColumns() { return filter.filter instanceof NamesQueryFilter && (cfs.metadata.cfType == ColumnFamilyType.Standard || filter.path.superColumnName != null) && cfs.metadata.getDefaultValidator() != CounterColumnType.instance ? collectTimeOrderedData() : collectAllData(); } /** * Collects data in order of recency, using the sstable maxtimestamp data. * Once we have data for all requests columns that is newer than the newest remaining maxtimestamp, * we stop. */ private ColumnFamily collectTimeOrderedData() { logger.debug("collectTimeOrderedData"); ISortedColumns.Factory factory = mutableColumns ? ThreadSafeSortedColumns.factory() : TreeMapBackedSortedColumns.factory(); ColumnFamily container = ColumnFamily.create(cfs.metadata, factory, filter.filter.isReversed()); List<IColumnIterator> iterators = new ArrayList<IColumnIterator>(); ColumnFamilyStore.ViewFragment view = cfs.markReferenced(filter.key); try { for (Memtable memtable : view.memtables) { IColumnIterator iter = filter.getMemtableColumnIterator(memtable, cfs.metadata.comparator); if (iter != null) { iterators.add(iter); container.delete(iter.getColumnFamily()); while (iter.hasNext()) container.addColumn(iter.next()); } } // avoid changing the filter columns of the original filter // (reduceNameFilter removes columns that are known to be irrelevant) TreeSet<ByteBuffer> filterColumns = new TreeSet<ByteBuffer>(((NamesQueryFilter) filter.filter).columns); QueryFilter reducedFilter = new QueryFilter(filter.key, filter.path, new NamesQueryFilter(filterColumns)); /* add the SSTables on disk */ Collections.sort(view.sstables, SSTable.maxTimestampComparator); // read sorted sstables for (SSTableReader sstable : view.sstables) { long currentMaxTs = sstable.getMaxTimestamp(); reduceNameFilter(reducedFilter, container, currentMaxTs); if (((NamesQueryFilter) reducedFilter.filter).columns.isEmpty()) break; IColumnIterator iter = reducedFilter.getSSTableColumnIterator(sstable); iterators.add(iter); if (iter.getColumnFamily() != null) { container.delete(iter.getColumnFamily()); sstablesIterated++; while (iter.hasNext()) container.addColumn(iter.next()); } } // we need to distinguish between "there is no data at all for this row" (BF will let us rebuild that efficiently) // and "there used to be data, but it's gone now" (we should cache the empty CF so we don't need to rebuild that slower) if (iterators.isEmpty()) return null; // do a final collate. toCollate is boilerplate required to provide a CloseableIterator final ColumnFamily c2 = container; CloseableIterator<IColumn> toCollate = new SimpleAbstractColumnIterator() { final Iterator<IColumn> iter = c2.iterator(); protected IColumn computeNext() { return iter.hasNext() ? iter.next() : endOfData(); } public ColumnFamily getColumnFamily() { return c2; } public DecoratedKey getKey() { return filter.key; } }; ColumnFamily returnCF = container.cloneMeShallow(); filter.collateColumns(returnCF, Collections.singletonList(toCollate), cfs.metadata.comparator, gcBefore); // "hoist up" the requested data into a more recent sstable if (sstablesIterated >= cfs.getMinimumCompactionThreshold() && cfs.getCompactionStrategy() instanceof SizeTieredCompactionStrategy) { - RowMutation rm = new RowMutation(cfs.table.name, new Row(filter.key, returnCF)); + RowMutation rm = new RowMutation(cfs.table.name, new Row(filter.key, returnCF.cloneMe())); try { rm.applyUnsafe(); // skipping commitlog is fine since we're just de-fragmenting existing data } catch (IOException e) { // log and allow the result to be returned logger.error("Error re-writing read results", e); } } // Caller is responsible for final removeDeletedCF. This is important for cacheRow to work correctly: return returnCF; } finally { for (IColumnIterator iter : iterators) FileUtils.closeQuietly(iter); SSTableReader.releaseReferences(view.sstables); } } /** * remove columns from @param filter where we already have data in @param returnCF newer than @param sstableTimestamp */ private void reduceNameFilter(QueryFilter filter, ColumnFamily returnCF, long sstableTimestamp) { AbstractColumnContainer container = filter.path.superColumnName == null ? returnCF : (SuperColumn) returnCF.getColumn(filter.path.superColumnName); if (container == null) return; for (Iterator<ByteBuffer> iterator = ((NamesQueryFilter) filter.filter).columns.iterator(); iterator.hasNext(); ) { ByteBuffer filterColumn = iterator.next(); IColumn column = container.getColumn(filterColumn); if (column != null && column.timestamp() > sstableTimestamp) iterator.remove(); } } /** * Collects data the brute-force way: gets an iterator for the filter in question * from every memtable and sstable, then merges them together. */ private ColumnFamily collectAllData() { logger.debug("collectAllData"); ISortedColumns.Factory factory = mutableColumns ? ThreadSafeSortedColumns.factory() : ArrayBackedSortedColumns.factory(); List<IColumnIterator> iterators = new ArrayList<IColumnIterator>(); ColumnFamily returnCF = ColumnFamily.create(cfs.metadata, factory, filter.filter.isReversed()); ColumnFamilyStore.ViewFragment view = cfs.markReferenced(filter.key); try { for (Memtable memtable : view.memtables) { IColumnIterator iter = filter.getMemtableColumnIterator(memtable, cfs.metadata.comparator); if (iter != null) { returnCF.delete(iter.getColumnFamily()); iterators.add(iter); } } for (SSTableReader sstable : view.sstables) { IColumnIterator iter = filter.getSSTableColumnIterator(sstable); iterators.add(iter); if (iter.getColumnFamily() != null) { returnCF.delete(iter.getColumnFamily()); sstablesIterated++; } } // we need to distinguish between "there is no data at all for this row" (BF will let us rebuild that efficiently) // and "there used to be data, but it's gone now" (we should cache the empty CF so we don't need to rebuild that slower) if (iterators.isEmpty()) return null; filter.collateColumns(returnCF, iterators, cfs.metadata.comparator, gcBefore); // Caller is responsible for final removeDeletedCF. This is important for cacheRow to work correctly: return returnCF; } finally { for (IColumnIterator iter : iterators) FileUtils.closeQuietly(iter); SSTableReader.releaseReferences(view.sstables); } } public int getSstablesIterated() { return sstablesIterated; } }
true
true
private ColumnFamily collectTimeOrderedData() { logger.debug("collectTimeOrderedData"); ISortedColumns.Factory factory = mutableColumns ? ThreadSafeSortedColumns.factory() : TreeMapBackedSortedColumns.factory(); ColumnFamily container = ColumnFamily.create(cfs.metadata, factory, filter.filter.isReversed()); List<IColumnIterator> iterators = new ArrayList<IColumnIterator>(); ColumnFamilyStore.ViewFragment view = cfs.markReferenced(filter.key); try { for (Memtable memtable : view.memtables) { IColumnIterator iter = filter.getMemtableColumnIterator(memtable, cfs.metadata.comparator); if (iter != null) { iterators.add(iter); container.delete(iter.getColumnFamily()); while (iter.hasNext()) container.addColumn(iter.next()); } } // avoid changing the filter columns of the original filter // (reduceNameFilter removes columns that are known to be irrelevant) TreeSet<ByteBuffer> filterColumns = new TreeSet<ByteBuffer>(((NamesQueryFilter) filter.filter).columns); QueryFilter reducedFilter = new QueryFilter(filter.key, filter.path, new NamesQueryFilter(filterColumns)); /* add the SSTables on disk */ Collections.sort(view.sstables, SSTable.maxTimestampComparator); // read sorted sstables for (SSTableReader sstable : view.sstables) { long currentMaxTs = sstable.getMaxTimestamp(); reduceNameFilter(reducedFilter, container, currentMaxTs); if (((NamesQueryFilter) reducedFilter.filter).columns.isEmpty()) break; IColumnIterator iter = reducedFilter.getSSTableColumnIterator(sstable); iterators.add(iter); if (iter.getColumnFamily() != null) { container.delete(iter.getColumnFamily()); sstablesIterated++; while (iter.hasNext()) container.addColumn(iter.next()); } } // we need to distinguish between "there is no data at all for this row" (BF will let us rebuild that efficiently) // and "there used to be data, but it's gone now" (we should cache the empty CF so we don't need to rebuild that slower) if (iterators.isEmpty()) return null; // do a final collate. toCollate is boilerplate required to provide a CloseableIterator final ColumnFamily c2 = container; CloseableIterator<IColumn> toCollate = new SimpleAbstractColumnIterator() { final Iterator<IColumn> iter = c2.iterator(); protected IColumn computeNext() { return iter.hasNext() ? iter.next() : endOfData(); } public ColumnFamily getColumnFamily() { return c2; } public DecoratedKey getKey() { return filter.key; } }; ColumnFamily returnCF = container.cloneMeShallow(); filter.collateColumns(returnCF, Collections.singletonList(toCollate), cfs.metadata.comparator, gcBefore); // "hoist up" the requested data into a more recent sstable if (sstablesIterated >= cfs.getMinimumCompactionThreshold() && cfs.getCompactionStrategy() instanceof SizeTieredCompactionStrategy) { RowMutation rm = new RowMutation(cfs.table.name, new Row(filter.key, returnCF)); try { rm.applyUnsafe(); // skipping commitlog is fine since we're just de-fragmenting existing data } catch (IOException e) { // log and allow the result to be returned logger.error("Error re-writing read results", e); } } // Caller is responsible for final removeDeletedCF. This is important for cacheRow to work correctly: return returnCF; } finally { for (IColumnIterator iter : iterators) FileUtils.closeQuietly(iter); SSTableReader.releaseReferences(view.sstables); } }
private ColumnFamily collectTimeOrderedData() { logger.debug("collectTimeOrderedData"); ISortedColumns.Factory factory = mutableColumns ? ThreadSafeSortedColumns.factory() : TreeMapBackedSortedColumns.factory(); ColumnFamily container = ColumnFamily.create(cfs.metadata, factory, filter.filter.isReversed()); List<IColumnIterator> iterators = new ArrayList<IColumnIterator>(); ColumnFamilyStore.ViewFragment view = cfs.markReferenced(filter.key); try { for (Memtable memtable : view.memtables) { IColumnIterator iter = filter.getMemtableColumnIterator(memtable, cfs.metadata.comparator); if (iter != null) { iterators.add(iter); container.delete(iter.getColumnFamily()); while (iter.hasNext()) container.addColumn(iter.next()); } } // avoid changing the filter columns of the original filter // (reduceNameFilter removes columns that are known to be irrelevant) TreeSet<ByteBuffer> filterColumns = new TreeSet<ByteBuffer>(((NamesQueryFilter) filter.filter).columns); QueryFilter reducedFilter = new QueryFilter(filter.key, filter.path, new NamesQueryFilter(filterColumns)); /* add the SSTables on disk */ Collections.sort(view.sstables, SSTable.maxTimestampComparator); // read sorted sstables for (SSTableReader sstable : view.sstables) { long currentMaxTs = sstable.getMaxTimestamp(); reduceNameFilter(reducedFilter, container, currentMaxTs); if (((NamesQueryFilter) reducedFilter.filter).columns.isEmpty()) break; IColumnIterator iter = reducedFilter.getSSTableColumnIterator(sstable); iterators.add(iter); if (iter.getColumnFamily() != null) { container.delete(iter.getColumnFamily()); sstablesIterated++; while (iter.hasNext()) container.addColumn(iter.next()); } } // we need to distinguish between "there is no data at all for this row" (BF will let us rebuild that efficiently) // and "there used to be data, but it's gone now" (we should cache the empty CF so we don't need to rebuild that slower) if (iterators.isEmpty()) return null; // do a final collate. toCollate is boilerplate required to provide a CloseableIterator final ColumnFamily c2 = container; CloseableIterator<IColumn> toCollate = new SimpleAbstractColumnIterator() { final Iterator<IColumn> iter = c2.iterator(); protected IColumn computeNext() { return iter.hasNext() ? iter.next() : endOfData(); } public ColumnFamily getColumnFamily() { return c2; } public DecoratedKey getKey() { return filter.key; } }; ColumnFamily returnCF = container.cloneMeShallow(); filter.collateColumns(returnCF, Collections.singletonList(toCollate), cfs.metadata.comparator, gcBefore); // "hoist up" the requested data into a more recent sstable if (sstablesIterated >= cfs.getMinimumCompactionThreshold() && cfs.getCompactionStrategy() instanceof SizeTieredCompactionStrategy) { RowMutation rm = new RowMutation(cfs.table.name, new Row(filter.key, returnCF.cloneMe())); try { rm.applyUnsafe(); // skipping commitlog is fine since we're just de-fragmenting existing data } catch (IOException e) { // log and allow the result to be returned logger.error("Error re-writing read results", e); } } // Caller is responsible for final removeDeletedCF. This is important for cacheRow to work correctly: return returnCF; } finally { for (IColumnIterator iter : iterators) FileUtils.closeQuietly(iter); SSTableReader.releaseReferences(view.sstables); } }
diff --git a/app/controllers/Execution.java b/app/controllers/Execution.java index a70002a..45b1a90 100644 --- a/app/controllers/Execution.java +++ b/app/controllers/Execution.java @@ -1,327 +1,325 @@ package controllers; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Query; import controllers.deadbolt.Deadbolt; import controllers.tabularasa.TableController; import models.tm.User; import models.tm.approach.Release; import models.tm.test.ExecutionStatus; import models.tm.test.Instance; import models.tm.test.InstanceParam; import models.tm.test.Run; import models.tm.test.RunParam; import models.tm.test.RunStep; import models.tm.test.ScriptStep; import org.apache.commons.lang.StringUtils; import play.db.jpa.GenericModel; import play.mvc.With; import util.FilterQuery; /** * TODO security * * @author Manuel Bernhardt <[email protected]> */ @With(Deadbolt.class) public class Execution extends TMController { public static final String ACTUAL_RESULT = "actualResult_"; public static final String STATUS = "status_"; public static final String PARAM = "param_"; public static void index() { List<Release> releases = Release.find("from Release r where r.project = ?", getActiveProject()).fetch(); List<User> users = User.listByProject(getActiveProject().getId()); render(releases, users); } public static void allUsers() { Lookups.allUsers(); } public static void allTags(String q) { Lookups.allTags(getActiveProject(), q); } public static void instances(String tableId, Integer iDisplayStart, Integer iDisplayLength, String sColumns, String sEcho, Long cycle, Integer status, String tags, Long responsible, Date dateFrom, Date dateTo) { FilterQuery fq = new FilterQuery(Instance.class); Map<String, Object> filters = new HashMap<String, Object>(); fq.addFilter("project", "=", getActiveProject()); if (cycle != null) { fq.addFilter("testCycle.id", "=", cycle); } if (status != null) { fq.addFilter("status", "=", status); } if (tags != null && !StringUtils.isEmpty(tags)) { fq.addJoin("tags", "o", "t"); fq.setDistinct(true); // Hibernate has a nasty bug that will yield in a ClassCastException when passing a String[], so we need to cast here fq.addWhere("t.name in (:tags)", "tags", Arrays.asList(tags.split(","))); fq.addAfterWhere("group by o.id having count(t.id) = " + tags.split(",").length); } if (responsible != null) { fq.addFilter("responsible.id", "=", responsible); } if (dateFrom != null) { fq.addWhere("o.plannedExecution >= :dateFrom", "dateFrom", dateFrom); } if (dateTo != null) { fq.addWhere("o.plannedExecution <= :dateTo", "dateTo", dateTo); } Query query = fq.build(); if (iDisplayStart != null) { query.setFirstResult(iDisplayStart); } if (iDisplayLength != null) { query.setMaxResults(iDisplayLength); } List instances = query.getResultList(); long totalRecords = instances.size(); TableController.renderJSON(instances, Instance.class, totalRecords, sColumns, sEcho); } public static void runs(String tableId, Long instanceId, Integer iDisplayStart, Integer iDisplayLength, String sColumns, String sEcho, String sSearch) { Instance instance = Lookups.getInstance(instanceId); GenericModel.JPAQuery query = null; String q = "from Run r where r.instance = ? and r.project = ? and r.temporary = false order by r.executionDate desc"; if (sSearch != null && sSearch.length() > 0) { // TODO implement the search query = Run.find(q, instance, TMController.getActiveProject()); } else { query = Run.find(q, instance, TMController.getActiveProject()).from(iDisplayStart == null ? 0 : iDisplayStart); } List<Run> runs = query.fetch(iDisplayLength == null ? 10 : iDisplayLength); long totalRecords = Run.count(); TableController.renderJSON(runs, Run.class, totalRecords, sColumns, sEcho); } public static void runSteps(String tableId, Long runId, Integer iDisplayStart, Integer iDisplayLength, String sColumns, String sEcho, String sSearch) { Run run = Lookups.getRun(runId); GenericModel.JPAQuery query = null; // TODO implement the search if (sSearch != null && sSearch.length() > 0) { query = RunStep.find("from RunStep s where s.run = ? and s.project = ? order by s.position asc", run, TMController.getActiveProject()); } else { query = RunStep.find("from RunStep s where s.run = ? and s.project = ? order by s.position asc", run, TMController.getActiveProject()).from(iDisplayStart == null ? 0 : iDisplayStart); } List<RunStep> runSteps = query.fetch(iDisplayLength == null ? 10 : iDisplayLength); long totalRecords = runSteps.size(); TableController.renderJSON(runSteps, RunStep.class, totalRecords, sColumns, sEcho); } public static void createRunDialog(Long instanceId) { Instance instance = Lookups.getInstance(instanceId); if (instance == null) { notFound(); } // create the run Run run = new Run(); run.project = instance.project; run.instance = instance; run.tester = getConnectedUser(); run.executionDate = new Date(); run.executionStatus = ExecutionStatus.NOT_RUN; // for now this run is temporary, it will be a permanent one when the user actually saves the run. run.temporary = true; run.create(); // copy the steps for (ScriptStep step : instance.script.getSteps()) { RunStep runStep = new RunStep(); runStep.project = instance.project; runStep.run = run; runStep.executionStatus = ExecutionStatus.NOT_RUN; runStep.name = step.name; runStep.position = step.position; runStep.description = step.description; runStep.expectedResult = step.expectedResult; runStep.create(); } // copy the parameters for (InstanceParam param : instance.getParams()) { RunParam runParam = new RunParam(); runParam.project = instance.project; runParam.run = run; runParam.name = param.scriptParam.name; runParam.value = param.value; runParam.create(); } render("Execution/runExecution.html", run); } public static void updateRunDialog(Long runId) { Run run = Lookups.getRun(runId); render("Execution/runExecution.html", run); } public static void updateRun(Long runId) { Run run = Lookups.getRun(runId); if (run == null) { notFound(); } // Play can bind Lists of entities as well, using as form input name things like step[id].status and then in the action method List<RunStep> step (make sure it's the same name - no plural!) // that is, this automatic binding is sort of buggy: it generates a lot of null elements in the list and also does not pre-load the JPA entity, so this is sort of broken // TODO rewrite this once we have proper binding for (String param : params.all().keySet()) { String paramValue = params.all().get(param)[0]; if (param.startsWith(ACTUAL_RESULT)) { String id = param.substring(ACTUAL_RESULT.length()); RunStep step = getRunStep(id, run); - if (paramValue != null && paramValue.length() > 0) { - step.actualResult = paramValue; - step.save(); - } + step.actualResult = paramValue; + step.save(); } else if (param.startsWith(STATUS)) { String id = param.substring(STATUS.length()); RunStep step = getRunStep(id, run); if (paramValue != null && paramValue.length() > 0) { try { Integer status = Integer.parseInt(paramValue); if (status != null) { step.executionStatus = ExecutionStatus.fromPosition(status); // �$%&/()= Play/Hibernate bug!! we shouldn't have to invoke that bloody PreUpdate handler ourselves! // TODO watch play.lighthouseapp.com/projects/57987-play-framework/tickets/731-jpa-preupdate-lifecycle-handler-does-not-work-in-play-controllers step.doSave(); step.save(); } } catch (NumberFormatException nfe) { // TODO logging nfe.printStackTrace(); error(); } catch (IllegalArgumentException iae) { // TODO logging iae.printStackTrace(); error(); } } else { // no status picked step.executionStatus = ExecutionStatus.NOT_RUN; // �$%&/()= Play/Hibernate bug!! we shouldn't have to invoke that bloody PreUpdate handler ourselves! // TODO watch play.lighthouseapp.com/projects/57987-play-framework/tickets/731-jpa-preupdate-lifecycle-handler-does-not-work-in-play-controllers step.doSave(); step.save(); } } } // run is not temporary anymore run.temporary = false; // re-compute Run and Instance status run.updateStatus(); run.instance.updateStatus(); ok(); } public static void deleteRun(Long runId) { Run run = Lookups.getRun(runId); if (run == null) { notFound(); } else { try { run.delete(); } catch (Throwable t) { // TODO logging t.printStackTrace(); error(); } } ok(); } public static void updateParameter(Long runId, String id, String value) { Run run = Lookups.getRun(runId); if (run == null) { notFound("Could not find run " + runId); } if (id.startsWith(PARAM)) { try { // param_id_UUID String param = id.substring(PARAM.length()); param = param.substring(0, param.indexOf("_")); Long pId = Long.parseLong(param); RunParam runParam = Lookups.getRunParam(pId); if (runParam == null) { notFound("Could not find parameter " + pId); } runParam.value = value; runParam.save(); renderText(value); } catch (NumberFormatException nfe) { // TODO logging nfe.printStackTrace(); error(); } } else { error("Wrong parameter id"); } } private static RunStep getRunStep(String id, Run run) { if (id != null && id.length() > 0) { RunStep step = null; try { Long lid = Long.parseLong(id); step = RunStep.find("from RunStep step where step.id = ? and step.project = ? and step.run = ?", lid, getActiveProject(), run).first(); if (step != null) { checkInAccount(step); } } catch (NumberFormatException nfe) { // TODO log this and report (security) nfe.printStackTrace(); } return step; } return null; } }
true
true
public static void updateRun(Long runId) { Run run = Lookups.getRun(runId); if (run == null) { notFound(); } // Play can bind Lists of entities as well, using as form input name things like step[id].status and then in the action method List<RunStep> step (make sure it's the same name - no plural!) // that is, this automatic binding is sort of buggy: it generates a lot of null elements in the list and also does not pre-load the JPA entity, so this is sort of broken // TODO rewrite this once we have proper binding for (String param : params.all().keySet()) { String paramValue = params.all().get(param)[0]; if (param.startsWith(ACTUAL_RESULT)) { String id = param.substring(ACTUAL_RESULT.length()); RunStep step = getRunStep(id, run); if (paramValue != null && paramValue.length() > 0) { step.actualResult = paramValue; step.save(); } } else if (param.startsWith(STATUS)) { String id = param.substring(STATUS.length()); RunStep step = getRunStep(id, run); if (paramValue != null && paramValue.length() > 0) { try { Integer status = Integer.parseInt(paramValue); if (status != null) { step.executionStatus = ExecutionStatus.fromPosition(status); // �$%&/()= Play/Hibernate bug!! we shouldn't have to invoke that bloody PreUpdate handler ourselves! // TODO watch play.lighthouseapp.com/projects/57987-play-framework/tickets/731-jpa-preupdate-lifecycle-handler-does-not-work-in-play-controllers step.doSave(); step.save(); } } catch (NumberFormatException nfe) { // TODO logging nfe.printStackTrace(); error(); } catch (IllegalArgumentException iae) { // TODO logging iae.printStackTrace(); error(); } } else { // no status picked step.executionStatus = ExecutionStatus.NOT_RUN; // �$%&/()= Play/Hibernate bug!! we shouldn't have to invoke that bloody PreUpdate handler ourselves! // TODO watch play.lighthouseapp.com/projects/57987-play-framework/tickets/731-jpa-preupdate-lifecycle-handler-does-not-work-in-play-controllers step.doSave(); step.save(); } } } // run is not temporary anymore run.temporary = false; // re-compute Run and Instance status run.updateStatus(); run.instance.updateStatus(); ok(); }
public static void updateRun(Long runId) { Run run = Lookups.getRun(runId); if (run == null) { notFound(); } // Play can bind Lists of entities as well, using as form input name things like step[id].status and then in the action method List<RunStep> step (make sure it's the same name - no plural!) // that is, this automatic binding is sort of buggy: it generates a lot of null elements in the list and also does not pre-load the JPA entity, so this is sort of broken // TODO rewrite this once we have proper binding for (String param : params.all().keySet()) { String paramValue = params.all().get(param)[0]; if (param.startsWith(ACTUAL_RESULT)) { String id = param.substring(ACTUAL_RESULT.length()); RunStep step = getRunStep(id, run); step.actualResult = paramValue; step.save(); } else if (param.startsWith(STATUS)) { String id = param.substring(STATUS.length()); RunStep step = getRunStep(id, run); if (paramValue != null && paramValue.length() > 0) { try { Integer status = Integer.parseInt(paramValue); if (status != null) { step.executionStatus = ExecutionStatus.fromPosition(status); // �$%&/()= Play/Hibernate bug!! we shouldn't have to invoke that bloody PreUpdate handler ourselves! // TODO watch play.lighthouseapp.com/projects/57987-play-framework/tickets/731-jpa-preupdate-lifecycle-handler-does-not-work-in-play-controllers step.doSave(); step.save(); } } catch (NumberFormatException nfe) { // TODO logging nfe.printStackTrace(); error(); } catch (IllegalArgumentException iae) { // TODO logging iae.printStackTrace(); error(); } } else { // no status picked step.executionStatus = ExecutionStatus.NOT_RUN; // �$%&/()= Play/Hibernate bug!! we shouldn't have to invoke that bloody PreUpdate handler ourselves! // TODO watch play.lighthouseapp.com/projects/57987-play-framework/tickets/731-jpa-preupdate-lifecycle-handler-does-not-work-in-play-controllers step.doSave(); step.save(); } } } // run is not temporary anymore run.temporary = false; // re-compute Run and Instance status run.updateStatus(); run.instance.updateStatus(); ok(); }
diff --git a/expenditure-tracking/src/main/java/module/mission/domain/activity/UnCommitFundsActivity.java b/expenditure-tracking/src/main/java/module/mission/domain/activity/UnCommitFundsActivity.java index 046ac028..324477d7 100644 --- a/expenditure-tracking/src/main/java/module/mission/domain/activity/UnCommitFundsActivity.java +++ b/expenditure-tracking/src/main/java/module/mission/domain/activity/UnCommitFundsActivity.java @@ -1,52 +1,52 @@ package module.mission.domain.activity; import module.mission.domain.MissionProcess; import module.mission.domain.util.MissionState; import module.workflow.activities.ActivityInformation; import pt.ist.bennu.core.domain.User; import pt.ist.bennu.core.util.BundleUtil; public class UnCommitFundsActivity extends MissionProcessActivity<MissionProcess, UnCommitFundsActivityInformation> { @Override public String getLocalizedName() { return BundleUtil.getStringFromResourceBundle("resources/MissionResources", "activity." + getClass().getSimpleName()); } @Override public boolean isActive(final MissionProcess missionProcess, final User user) { if (!super.isActive(missionProcess, user)) { return false; } if (missionProcess.isCanceled()) { return false; } if (!MissionState.FUND_ALLOCATION.isPending(missionProcess) && !MissionState.PARTICIPATION_AUTHORIZATION.isPending(missionProcess)) { return false; } if (!missionProcess.hasCommitmentNumber()) { return false; } - if (missionProcess.hasAnyAuthorization()) { + if (missionProcess.hasAnyAuthorizedParticipants()) { return false; } return missionProcess.isAccountingEmployee(user.getExpenditurePerson()); } @Override protected void process(final UnCommitFundsActivityInformation unCommitFundsActivityInformation) { unCommitFundsActivityInformation.getMissionFinancer().setCommitmentNumber(null); } @Override public ActivityInformation<MissionProcess> getActivityInformation(final MissionProcess process) { return new UnCommitFundsActivityInformation(process, this); } @Override public boolean isVisible() { return false; } }
true
true
public boolean isActive(final MissionProcess missionProcess, final User user) { if (!super.isActive(missionProcess, user)) { return false; } if (missionProcess.isCanceled()) { return false; } if (!MissionState.FUND_ALLOCATION.isPending(missionProcess) && !MissionState.PARTICIPATION_AUTHORIZATION.isPending(missionProcess)) { return false; } if (!missionProcess.hasCommitmentNumber()) { return false; } if (missionProcess.hasAnyAuthorization()) { return false; } return missionProcess.isAccountingEmployee(user.getExpenditurePerson()); }
public boolean isActive(final MissionProcess missionProcess, final User user) { if (!super.isActive(missionProcess, user)) { return false; } if (missionProcess.isCanceled()) { return false; } if (!MissionState.FUND_ALLOCATION.isPending(missionProcess) && !MissionState.PARTICIPATION_AUTHORIZATION.isPending(missionProcess)) { return false; } if (!missionProcess.hasCommitmentNumber()) { return false; } if (missionProcess.hasAnyAuthorizedParticipants()) { return false; } return missionProcess.isAccountingEmployee(user.getExpenditurePerson()); }
diff --git a/applications/secore/secore-core/src/java/secore/util/StringUtil.java b/applications/secore/secore-core/src/java/secore/util/StringUtil.java index 9f451013..6281c6b0 100644 --- a/applications/secore/secore-core/src/java/secore/util/StringUtil.java +++ b/applications/secore/secore-core/src/java/secore/util/StringUtil.java @@ -1,302 +1,302 @@ /* * This file is part of rasdaman community. * * Rasdaman community is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rasdaman community is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with rasdaman community. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2003 - 2012 Peter Baumann / rasdaman GmbH. * * For more information please see <http://www.rasdaman.org> * or contact Peter Baumann via <[email protected]>. */ package secore.util; import secore.ResolveRequest; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static secore.util.Constants.*; /** * String utilities. * * @author Dimitar Misev */ public class StringUtil { private static Logger log = LoggerFactory.getLogger(StringUtil.class); private static final String HTTP_PREFIX = "http://"; private static final String JAVA_SCRIPT_ENGINE = "JavaScript"; private static final String UTF_ENCODING = "UTF-8"; private static final String DEF = "/def/"; private static final ScriptEngineManager engineManager; private static final ScriptEngine engine; static { engineManager = new ScriptEngineManager(); engine = engineManager.getEngineByName(JAVA_SCRIPT_ENGINE); } /** * Evaluate a JavaScript expression * @param expr JavaScript expression * @return the value of the expression as string * @throws ScriptException */ public static String evaluate(String expr) throws ScriptException { log.trace("Evaluating expression: " + expr); Object res = engine.eval(expr); if (res != null) { return res.toString(); } return null; } /** URL-decode a string, if needed */ public static String urldecode(String encodedText) { if (encodedText == null) { return null; } String decoded = encodedText; if (encodedText.indexOf(WHITESPACE) == -1) { try { decoded = URLDecoder.decode(encodedText, UTF_ENCODING); } catch (UnsupportedEncodingException ex) { decoded = URLDecoder.decode(encodedText); } } return decoded; } public static String stripDef(String s) { if (s.contains(DEF)) { return s.substring(s.indexOf(DEF) + DEF.length()); } return s.substring(1); } public static String removeDuplicateDef(String s) { int ind = s.indexOf("/def"); return s.substring(0, ind) + s.substring(ind + "/def".length()); } public static String getServiceUrl(String s) { if (s.contains(DEF)) { return s.substring(0, s.indexOf(DEF) + DEF.length()); } return s; } public static ResolveRequest buildRequest(String uri) throws SecoreException { log.trace("Building request for URI: " + uri); uri = StringUtil.urldecode(uri); String fullUri = uri; log.trace("Decoded URI: " + uri); String serviceUri = StringUtil.getServiceUrl(uri); uri = StringUtil.stripDef(uri); log.trace("Parameters: " + uri); // set operation int ind1 = uri.indexOf(REST_SEPARATOR); int ind2 = uri.indexOf(FRAGMENT_SEPARATOR); int ind = -1; if (ind1 != -1 && (ind2 == -1 || ind1 < ind2)) { ind = ind1; } else if (ind2 != -1 && (ind1 == -1 || ind2 < ind1)) { ind = ind2; } else { log.error("Couldn't determine request operation in " + uri); - throw new SecoreException(ExceptionCode.InvalidRequest, "Mallformed request: " + uri); + throw new SecoreException(ExceptionCode.InvalidRequest, "Malformed request: " + uri); } String operation = uri.substring(0, ind); uri = uri.substring(ind + 1); ResolveRequest ret = new ResolveRequest(operation, serviceUri, fullUri); // set params String[] pairs = null; if (uri.contains(HTTP_PREFIX)) { // special case for crs-compound/equal while ((ind = uri.indexOf(HTTP_PREFIX, HTTP_PREFIX.length() + 5)) != -1) { String key = uri.substring(0, ind); if (key.matches(".+&\\d+=")) { key = key.substring(0, key.lastIndexOf(PAIR_SEPARATOR)); uri = uri.substring(key.length() + 1); } else { uri = uri.substring(ind); } addParam(ret, key); } addParam(ret, uri); } else { // all other cases pairs = uri.split("[/\\?&]"); for (String pair : pairs) { if (!pair.equals(EMPTY)) { String key = pair; String val = null; if (pair.contains(KEY_VALUE_SEPARATOR)) { String[] tmp = pair.split(KEY_VALUE_SEPARATOR); key = tmp[0]; if (tmp.length > 1) { val = tmp[1]; } } ret.addParam(key, val); } } } log.trace("Built request: " + ret); return ret; } private static void addParam(ResolveRequest req, String param) throws SecoreException { if (param.matches("\\d+=.+")) { String[] tmp = param.split(KEY_VALUE_SEPARATOR); // In case of compounding or equality testing && 1+ URLs are KV-paired, // then need to *re-merge* the remaining components of the split, otherwise // only the first KV pair is added as parameter. req.addParam(tmp[0], join(tmp, 1, tmp.length, KEY_VALUE_SEPARATOR)); } else { req.addParam(param, null); } } /** * Joins strings of an array in a specified range (within the size of the array) and with a specified separator. * @param array Array of Strings * @param start Lower bound of the range * @param end Upper bound of the range * @param separator The separator String * @return The joined String */ private static String join(String[] array, int start, int end, String separator) { String joined = ""; for (int i = Math.max(start, 0); i < Math.min(end, array.length); i++) { joined += (joined.isEmpty() ? "" : separator) + array[i]; } return joined; } /** * Get the text content of an element in given xml. * @param xml xml * @param elname element name * @return the text content of elname */ public static String getElementValue(String xml, String elname) { String ret = null; Pattern pattern = Pattern.compile("<(.+:)?" + elname + "[^>]*>([^<]+)</(.+:)?" + elname + ">.*"); Matcher matcher = pattern.matcher(xml); if (matcher.find()) { ret = matcher.group(2); } return ret; } /** * Get the root element name of the given xml document. * @param xml an XML document * @return the root name, or null in case of an error */ public static String getRootElementName(String xml) { int start = 0; while (start < xml.length()) { start = xml.indexOf("<", start); if (start == -1) { return null; } if (xml.charAt(start + 1) != '?') { int end = start + 1; while (end < xml.length() && xml.charAt(end) != ' ' && xml.charAt(end) != '>') { if (xml.charAt(end) == ':') { start = end; } ++end; } if (end == -1) { return null; } ++start; return xml.substring(start, end); } else { ++start; } } return null; } /** * Converts a collection to a string, separating the elements by c * * @param l The StringList * @param c The delimiter * @return A String of the ListElements separated by c. */ public static <T> String ltos(Collection<T> l, Character c) { String s = EMPTY; for (Iterator<T> iter = l.iterator(); iter.hasNext();) { if (!s.equalsIgnoreCase(EMPTY)) { s = s + c + iter.next().toString(); } else { s = s + iter.next().toString(); } } return s; } /** * Converts a string to a list * * @param s The StringList * @return A String of the ListElements separated by c. */ public static List<String> stol(String s) { List<String> l = new LinkedList<String>(); if (s == null) { return l; } String[] sl = s.split(","); for (int i = 0; i < sl.length; i++) { l.add(sl[i]); } return l; } /** * Replace all URNs in s with URLs in REST format. * * @param s a GML definition * @return the definition with the fixed links */ public static String fixLinks(String s) { // $1 = operation // $2 = authority // $3 = code // TODO fix handling of version, 0 is assumed now return s.replaceAll(URN_PREFIX + ":(.+):(.+)::(.+)", Config.getInstance().getServiceUrl() + "/$1/$2/0/$3"); } }
true
true
public static ResolveRequest buildRequest(String uri) throws SecoreException { log.trace("Building request for URI: " + uri); uri = StringUtil.urldecode(uri); String fullUri = uri; log.trace("Decoded URI: " + uri); String serviceUri = StringUtil.getServiceUrl(uri); uri = StringUtil.stripDef(uri); log.trace("Parameters: " + uri); // set operation int ind1 = uri.indexOf(REST_SEPARATOR); int ind2 = uri.indexOf(FRAGMENT_SEPARATOR); int ind = -1; if (ind1 != -1 && (ind2 == -1 || ind1 < ind2)) { ind = ind1; } else if (ind2 != -1 && (ind1 == -1 || ind2 < ind1)) { ind = ind2; } else { log.error("Couldn't determine request operation in " + uri); throw new SecoreException(ExceptionCode.InvalidRequest, "Mallformed request: " + uri); } String operation = uri.substring(0, ind); uri = uri.substring(ind + 1); ResolveRequest ret = new ResolveRequest(operation, serviceUri, fullUri); // set params String[] pairs = null; if (uri.contains(HTTP_PREFIX)) { // special case for crs-compound/equal while ((ind = uri.indexOf(HTTP_PREFIX, HTTP_PREFIX.length() + 5)) != -1) { String key = uri.substring(0, ind); if (key.matches(".+&\\d+=")) { key = key.substring(0, key.lastIndexOf(PAIR_SEPARATOR)); uri = uri.substring(key.length() + 1); } else { uri = uri.substring(ind); } addParam(ret, key); } addParam(ret, uri); } else { // all other cases pairs = uri.split("[/\\?&]"); for (String pair : pairs) { if (!pair.equals(EMPTY)) { String key = pair; String val = null; if (pair.contains(KEY_VALUE_SEPARATOR)) { String[] tmp = pair.split(KEY_VALUE_SEPARATOR); key = tmp[0]; if (tmp.length > 1) { val = tmp[1]; } } ret.addParam(key, val); } } } log.trace("Built request: " + ret); return ret; }
public static ResolveRequest buildRequest(String uri) throws SecoreException { log.trace("Building request for URI: " + uri); uri = StringUtil.urldecode(uri); String fullUri = uri; log.trace("Decoded URI: " + uri); String serviceUri = StringUtil.getServiceUrl(uri); uri = StringUtil.stripDef(uri); log.trace("Parameters: " + uri); // set operation int ind1 = uri.indexOf(REST_SEPARATOR); int ind2 = uri.indexOf(FRAGMENT_SEPARATOR); int ind = -1; if (ind1 != -1 && (ind2 == -1 || ind1 < ind2)) { ind = ind1; } else if (ind2 != -1 && (ind1 == -1 || ind2 < ind1)) { ind = ind2; } else { log.error("Couldn't determine request operation in " + uri); throw new SecoreException(ExceptionCode.InvalidRequest, "Malformed request: " + uri); } String operation = uri.substring(0, ind); uri = uri.substring(ind + 1); ResolveRequest ret = new ResolveRequest(operation, serviceUri, fullUri); // set params String[] pairs = null; if (uri.contains(HTTP_PREFIX)) { // special case for crs-compound/equal while ((ind = uri.indexOf(HTTP_PREFIX, HTTP_PREFIX.length() + 5)) != -1) { String key = uri.substring(0, ind); if (key.matches(".+&\\d+=")) { key = key.substring(0, key.lastIndexOf(PAIR_SEPARATOR)); uri = uri.substring(key.length() + 1); } else { uri = uri.substring(ind); } addParam(ret, key); } addParam(ret, uri); } else { // all other cases pairs = uri.split("[/\\?&]"); for (String pair : pairs) { if (!pair.equals(EMPTY)) { String key = pair; String val = null; if (pair.contains(KEY_VALUE_SEPARATOR)) { String[] tmp = pair.split(KEY_VALUE_SEPARATOR); key = tmp[0]; if (tmp.length > 1) { val = tmp[1]; } } ret.addParam(key, val); } } } log.trace("Built request: " + ret); return ret; }
diff --git a/pmd/src/net/sourceforge/pmd/lang/java/rule/basic/UselessOverridingMethodRule.java b/pmd/src/net/sourceforge/pmd/lang/java/rule/basic/UselessOverridingMethodRule.java index 685e28e81..b5c70be7b 100644 --- a/pmd/src/net/sourceforge/pmd/lang/java/rule/basic/UselessOverridingMethodRule.java +++ b/pmd/src/net/sourceforge/pmd/lang/java/rule/basic/UselessOverridingMethodRule.java @@ -1,235 +1,239 @@ /** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.basic; import java.util.ArrayList; import java.util.List; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.java.ast.ASTArgumentList; import net.sourceforge.pmd.lang.java.ast.ASTArguments; import net.sourceforge.pmd.lang.java.ast.ASTBlock; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameter; import net.sourceforge.pmd.lang.java.ast.ASTFormalParameters; import net.sourceforge.pmd.lang.java.ast.ASTImplementsList; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator; import net.sourceforge.pmd.lang.java.ast.ASTName; import net.sourceforge.pmd.lang.java.ast.ASTNameList; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix; import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix; import net.sourceforge.pmd.lang.java.ast.ASTResultType; import net.sourceforge.pmd.lang.java.ast.ASTStatement; import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import org.jaxen.JaxenException; /** * @author Romain Pelisse, bugfix for [ 1522517 ] False +: UselessOverridingMethod */ public class UselessOverridingMethodRule extends AbstractJavaRule { private List<String> exceptions; private static final String CLONE = "clone"; private static final String OBJECT = "Object"; public UselessOverridingMethodRule() { exceptions = new ArrayList<String>(1); exceptions.add("CloneNotSupportedException"); } @Override public Object visit(ASTImplementsList clz, Object data) { return super.visit(clz, data); } @Override public Object visit(ASTClassOrInterfaceDeclaration clz, Object data) { if (clz.isInterface()) { return data; } return super.visit(clz, data); } //TODO: this method should be externalize into an utility class, shouldn't it ? private boolean isMethodType(ASTMethodDeclaration node, String methodType) { boolean result = false; ASTResultType type = node.getResultType(); if (type != null) { List<Node> results = null; try { results = type.findChildNodesWithXPath("./Type/ReferenceType/ClassOrInterfaceType[@Image = '" + methodType + "']"); } catch (JaxenException e) { e.printStackTrace(); } if (results != null && results.size() > 0) { result = true; } } return result; } //TODO: this method should be externalize into an utility class, shouldn't it ? private boolean isMethodThrowingType(ASTMethodDeclaration node, List<String> exceptedExceptions) { boolean result = false; ASTNameList thrownsExceptions = node.getFirstChildOfType(ASTNameList.class); if (thrownsExceptions != null) { List<ASTName> names = thrownsExceptions.findChildrenOfType(ASTName.class); for (ASTName name : names) { for (String exceptedException : exceptedExceptions) { if (exceptedException.equals(name.getImage())) { result = true; } } } } return result; } private boolean hasArguments(ASTMethodDeclaration node) { boolean result = false; try { List<Node> parameters = node.findChildNodesWithXPath("./MethodDeclarator/FormalParameters/*"); if (parameters != null && parameters.size() < 0) { result = true; } } catch (JaxenException e) { e.printStackTrace(); } return result; } @Override public Object visit(ASTMethodDeclaration node, Object data) { // Can skip abstract methods and methods whose only purpose is to // guarantee that the inherited method is not changed by finalizing // them. if (node.isAbstract() || node.isFinal() || node.isNative() || node.isSynchronized()) { return super.visit(node, data); } // We can also skip the 'clone' method as they are generally // 'useless' but as it is considered a 'good practise' to // implement them anyway ( see bug 1522517) if (CLONE.equals(node.getMethodName()) && node.isPublic() && !this.hasArguments(node) && this.isMethodType(node, OBJECT) && this.isMethodThrowingType(node, exceptions)) { return super.visit(node, data); } ASTBlock block = node.getBlock(); if (block == null) { return super.visit(node, data); } //Only process functions with one BlockStatement if (block.jjtGetNumChildren() != 1 || block.findChildrenOfType(ASTStatement.class).size() != 1) { return super.visit(node, data); } ASTStatement statement = (ASTStatement) block.jjtGetChild(0).jjtGetChild(0); if (statement.jjtGetChild(0).jjtGetNumChildren() == 0) { return data; // skips empty return statements } Node statementGrandChild = statement.jjtGetChild(0).jjtGetChild(0); ASTPrimaryExpression primaryExpression; if (statementGrandChild instanceof ASTPrimaryExpression) { primaryExpression = (ASTPrimaryExpression) statementGrandChild; } else { List<ASTPrimaryExpression> primaryExpressions = findFirstDegreeChildrenOfType(statementGrandChild, ASTPrimaryExpression.class); if (primaryExpressions.size() != 1) { return super.visit(node, data); } primaryExpression = primaryExpressions.get(0); } ASTPrimaryPrefix primaryPrefix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimaryPrefix.class) .get(0); if (!primaryPrefix.usesSuperModifier()) { return super.visit(node, data); } ASTMethodDeclarator methodDeclarator = findFirstDegreeChildrenOfType(node, ASTMethodDeclarator.class).get(0); if (!primaryPrefix.hasImageEqualTo(methodDeclarator.getImage())) { return super.visit(node, data); } + List<ASTPrimarySuffix> primarySuffixList = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimarySuffix.class); + if (primarySuffixList.size() != 1) { + // extra method call on result of super method + return super.visit(node, data); + } //Process arguments - ASTPrimarySuffix primarySuffix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimarySuffix.class) - .get(0); + ASTPrimarySuffix primarySuffix = primarySuffixList.get(0); ASTArguments arguments = (ASTArguments) primarySuffix.jjtGetChild(0); ASTFormalParameters formalParameters = (ASTFormalParameters) methodDeclarator.jjtGetChild(0); if (formalParameters.jjtGetNumChildren() != arguments.jjtGetNumChildren()) { return super.visit(node, data); } if (arguments.jjtGetNumChildren() == 0) { addViolation(data, node, getMessage()); } else { ASTArgumentList argumentList = (ASTArgumentList) arguments.jjtGetChild(0); for (int i = 0; i < argumentList.jjtGetNumChildren(); i++) { Node ExpressionChild = argumentList.jjtGetChild(i).jjtGetChild(0); if (!(ExpressionChild instanceof ASTPrimaryExpression) || ExpressionChild.jjtGetNumChildren() != 1) { return super.visit(node, data); //The arguments are not simply passed through } ASTPrimaryExpression argumentPrimaryExpression = (ASTPrimaryExpression) ExpressionChild; ASTPrimaryPrefix argumentPrimaryPrefix = (ASTPrimaryPrefix) argumentPrimaryExpression.jjtGetChild(0); if (argumentPrimaryPrefix.jjtGetNumChildren() == 0) { return super.visit(node, data); //The arguments are not simply passed through (using "this" for instance) } Node argumentPrimaryPrefixChild = argumentPrimaryPrefix.jjtGetChild(0); if (!(argumentPrimaryPrefixChild instanceof ASTName)) { return super.visit(node, data); //The arguments are not simply passed through } if (formalParameters.jjtGetNumChildren() < i + 1) { return super.visit(node, data); // different number of args } ASTName argumentName = (ASTName) argumentPrimaryPrefixChild; ASTFormalParameter formalParameter = (ASTFormalParameter) formalParameters.jjtGetChild(i); ASTVariableDeclaratorId variableId = findFirstDegreeChildrenOfType(formalParameter, ASTVariableDeclaratorId.class).get(0); if (!argumentName.hasImageEqualTo(variableId.getImage())) { return super.visit(node, data); //The arguments are not simply passed through } } addViolation(data, node, getMessage()); //All arguments are passed through directly } return super.visit(node, data); } public <T> List<T> findFirstDegreeChildrenOfType(Node n, Class<T> targetType) { List<T> l = new ArrayList<T>(); lclFindChildrenOfType(n, targetType, l); return l; } private <T> void lclFindChildrenOfType(Node node, Class<T> targetType, List<T> results) { if (node.getClass().equals(targetType)) { results.add((T) node); } if (node instanceof ASTClassOrInterfaceDeclaration && ((ASTClassOrInterfaceDeclaration) node).isNested()) { return; } if (node instanceof ASTClassOrInterfaceBodyDeclaration && ((ASTClassOrInterfaceBodyDeclaration) node).isAnonymousInnerClass()) { return; } for (int i = 0; i < node.jjtGetNumChildren(); i++) { Node child = node.jjtGetChild(i); if (child.getClass().equals(targetType)) { results.add((T) child); } } } }
false
true
public Object visit(ASTMethodDeclaration node, Object data) { // Can skip abstract methods and methods whose only purpose is to // guarantee that the inherited method is not changed by finalizing // them. if (node.isAbstract() || node.isFinal() || node.isNative() || node.isSynchronized()) { return super.visit(node, data); } // We can also skip the 'clone' method as they are generally // 'useless' but as it is considered a 'good practise' to // implement them anyway ( see bug 1522517) if (CLONE.equals(node.getMethodName()) && node.isPublic() && !this.hasArguments(node) && this.isMethodType(node, OBJECT) && this.isMethodThrowingType(node, exceptions)) { return super.visit(node, data); } ASTBlock block = node.getBlock(); if (block == null) { return super.visit(node, data); } //Only process functions with one BlockStatement if (block.jjtGetNumChildren() != 1 || block.findChildrenOfType(ASTStatement.class).size() != 1) { return super.visit(node, data); } ASTStatement statement = (ASTStatement) block.jjtGetChild(0).jjtGetChild(0); if (statement.jjtGetChild(0).jjtGetNumChildren() == 0) { return data; // skips empty return statements } Node statementGrandChild = statement.jjtGetChild(0).jjtGetChild(0); ASTPrimaryExpression primaryExpression; if (statementGrandChild instanceof ASTPrimaryExpression) { primaryExpression = (ASTPrimaryExpression) statementGrandChild; } else { List<ASTPrimaryExpression> primaryExpressions = findFirstDegreeChildrenOfType(statementGrandChild, ASTPrimaryExpression.class); if (primaryExpressions.size() != 1) { return super.visit(node, data); } primaryExpression = primaryExpressions.get(0); } ASTPrimaryPrefix primaryPrefix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimaryPrefix.class) .get(0); if (!primaryPrefix.usesSuperModifier()) { return super.visit(node, data); } ASTMethodDeclarator methodDeclarator = findFirstDegreeChildrenOfType(node, ASTMethodDeclarator.class).get(0); if (!primaryPrefix.hasImageEqualTo(methodDeclarator.getImage())) { return super.visit(node, data); } //Process arguments ASTPrimarySuffix primarySuffix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimarySuffix.class) .get(0); ASTArguments arguments = (ASTArguments) primarySuffix.jjtGetChild(0); ASTFormalParameters formalParameters = (ASTFormalParameters) methodDeclarator.jjtGetChild(0); if (formalParameters.jjtGetNumChildren() != arguments.jjtGetNumChildren()) { return super.visit(node, data); } if (arguments.jjtGetNumChildren() == 0) { addViolation(data, node, getMessage()); } else { ASTArgumentList argumentList = (ASTArgumentList) arguments.jjtGetChild(0); for (int i = 0; i < argumentList.jjtGetNumChildren(); i++) { Node ExpressionChild = argumentList.jjtGetChild(i).jjtGetChild(0); if (!(ExpressionChild instanceof ASTPrimaryExpression) || ExpressionChild.jjtGetNumChildren() != 1) { return super.visit(node, data); //The arguments are not simply passed through } ASTPrimaryExpression argumentPrimaryExpression = (ASTPrimaryExpression) ExpressionChild; ASTPrimaryPrefix argumentPrimaryPrefix = (ASTPrimaryPrefix) argumentPrimaryExpression.jjtGetChild(0); if (argumentPrimaryPrefix.jjtGetNumChildren() == 0) { return super.visit(node, data); //The arguments are not simply passed through (using "this" for instance) } Node argumentPrimaryPrefixChild = argumentPrimaryPrefix.jjtGetChild(0); if (!(argumentPrimaryPrefixChild instanceof ASTName)) { return super.visit(node, data); //The arguments are not simply passed through } if (formalParameters.jjtGetNumChildren() < i + 1) { return super.visit(node, data); // different number of args } ASTName argumentName = (ASTName) argumentPrimaryPrefixChild; ASTFormalParameter formalParameter = (ASTFormalParameter) formalParameters.jjtGetChild(i); ASTVariableDeclaratorId variableId = findFirstDegreeChildrenOfType(formalParameter, ASTVariableDeclaratorId.class).get(0); if (!argumentName.hasImageEqualTo(variableId.getImage())) { return super.visit(node, data); //The arguments are not simply passed through } } addViolation(data, node, getMessage()); //All arguments are passed through directly } return super.visit(node, data); }
public Object visit(ASTMethodDeclaration node, Object data) { // Can skip abstract methods and methods whose only purpose is to // guarantee that the inherited method is not changed by finalizing // them. if (node.isAbstract() || node.isFinal() || node.isNative() || node.isSynchronized()) { return super.visit(node, data); } // We can also skip the 'clone' method as they are generally // 'useless' but as it is considered a 'good practise' to // implement them anyway ( see bug 1522517) if (CLONE.equals(node.getMethodName()) && node.isPublic() && !this.hasArguments(node) && this.isMethodType(node, OBJECT) && this.isMethodThrowingType(node, exceptions)) { return super.visit(node, data); } ASTBlock block = node.getBlock(); if (block == null) { return super.visit(node, data); } //Only process functions with one BlockStatement if (block.jjtGetNumChildren() != 1 || block.findChildrenOfType(ASTStatement.class).size() != 1) { return super.visit(node, data); } ASTStatement statement = (ASTStatement) block.jjtGetChild(0).jjtGetChild(0); if (statement.jjtGetChild(0).jjtGetNumChildren() == 0) { return data; // skips empty return statements } Node statementGrandChild = statement.jjtGetChild(0).jjtGetChild(0); ASTPrimaryExpression primaryExpression; if (statementGrandChild instanceof ASTPrimaryExpression) { primaryExpression = (ASTPrimaryExpression) statementGrandChild; } else { List<ASTPrimaryExpression> primaryExpressions = findFirstDegreeChildrenOfType(statementGrandChild, ASTPrimaryExpression.class); if (primaryExpressions.size() != 1) { return super.visit(node, data); } primaryExpression = primaryExpressions.get(0); } ASTPrimaryPrefix primaryPrefix = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimaryPrefix.class) .get(0); if (!primaryPrefix.usesSuperModifier()) { return super.visit(node, data); } ASTMethodDeclarator methodDeclarator = findFirstDegreeChildrenOfType(node, ASTMethodDeclarator.class).get(0); if (!primaryPrefix.hasImageEqualTo(methodDeclarator.getImage())) { return super.visit(node, data); } List<ASTPrimarySuffix> primarySuffixList = findFirstDegreeChildrenOfType(primaryExpression, ASTPrimarySuffix.class); if (primarySuffixList.size() != 1) { // extra method call on result of super method return super.visit(node, data); } //Process arguments ASTPrimarySuffix primarySuffix = primarySuffixList.get(0); ASTArguments arguments = (ASTArguments) primarySuffix.jjtGetChild(0); ASTFormalParameters formalParameters = (ASTFormalParameters) methodDeclarator.jjtGetChild(0); if (formalParameters.jjtGetNumChildren() != arguments.jjtGetNumChildren()) { return super.visit(node, data); } if (arguments.jjtGetNumChildren() == 0) { addViolation(data, node, getMessage()); } else { ASTArgumentList argumentList = (ASTArgumentList) arguments.jjtGetChild(0); for (int i = 0; i < argumentList.jjtGetNumChildren(); i++) { Node ExpressionChild = argumentList.jjtGetChild(i).jjtGetChild(0); if (!(ExpressionChild instanceof ASTPrimaryExpression) || ExpressionChild.jjtGetNumChildren() != 1) { return super.visit(node, data); //The arguments are not simply passed through } ASTPrimaryExpression argumentPrimaryExpression = (ASTPrimaryExpression) ExpressionChild; ASTPrimaryPrefix argumentPrimaryPrefix = (ASTPrimaryPrefix) argumentPrimaryExpression.jjtGetChild(0); if (argumentPrimaryPrefix.jjtGetNumChildren() == 0) { return super.visit(node, data); //The arguments are not simply passed through (using "this" for instance) } Node argumentPrimaryPrefixChild = argumentPrimaryPrefix.jjtGetChild(0); if (!(argumentPrimaryPrefixChild instanceof ASTName)) { return super.visit(node, data); //The arguments are not simply passed through } if (formalParameters.jjtGetNumChildren() < i + 1) { return super.visit(node, data); // different number of args } ASTName argumentName = (ASTName) argumentPrimaryPrefixChild; ASTFormalParameter formalParameter = (ASTFormalParameter) formalParameters.jjtGetChild(i); ASTVariableDeclaratorId variableId = findFirstDegreeChildrenOfType(formalParameter, ASTVariableDeclaratorId.class).get(0); if (!argumentName.hasImageEqualTo(variableId.getImage())) { return super.visit(node, data); //The arguments are not simply passed through } } addViolation(data, node, getMessage()); //All arguments are passed through directly } return super.visit(node, data); }
diff --git a/src/main/java/me/chaseoes/tf2/listeners/TF2DeathListener.java b/src/main/java/me/chaseoes/tf2/listeners/TF2DeathListener.java index b20c961..dd8d81d 100644 --- a/src/main/java/me/chaseoes/tf2/listeners/TF2DeathListener.java +++ b/src/main/java/me/chaseoes/tf2/listeners/TF2DeathListener.java @@ -1,76 +1,79 @@ package me.chaseoes.tf2.listeners; import me.chaseoes.tf2.Game; import me.chaseoes.tf2.GamePlayer; import me.chaseoes.tf2.GameUtilities; import me.chaseoes.tf2.Map; import me.chaseoes.tf2.MapUtilities; import me.chaseoes.tf2.TF2; import me.chaseoes.tf2.classes.TF2Class; import me.chaseoes.tf2.events.TF2DeathEvent; import me.chaseoes.tf2.utilities.Localizer; import org.bukkit.ChatColor; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class TF2DeathListener implements Listener { @EventHandler public void onDeath(final TF2DeathEvent event) { TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() { @Override public void run() { final Player player = event.getPlayer(); final GamePlayer playerg = GameUtilities.getUtilities().getGamePlayer(player); final Player killer = event.getKiller(); GamePlayer killerg = GameUtilities.getUtilities().getGamePlayer(killer); Game game = playerg.getGame(); + if (game == null) { + return; + } Map map = game.getMap(); player.teleport(MapUtilities.getUtilities().loadTeamSpawn(map.getName(), playerg.getTeam())); player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KILLED-BY").replace("%teamcolor", killerg.getTeamColor()).replace("%player", killer.getName()).replace("%class", killerg.getCurrentClass().getName())); killer.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KILLED").replace("%teamcolor", playerg.getTeamColor()).replace("%player", player.getName()).replace("%class", playerg.getCurrentClass().getName())); killer.playSound(killer.getLocation(), Sound.valueOf(TF2.getInstance().getConfig().getString("killsound.sound")), TF2.getInstance().getConfig().getInt("killsound.volume"), TF2.getInstance().getConfig().getInt("killsound.pitch")); TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() { @Override public void run() { playerg.setJustSpawned(false); } }, 40L); // Reset the kills of the player who died. playerg.addKillstreak(playerg.getKills()); playerg.setKills(0); playerg.setDeaths(-1); playerg.settotalDeaths(-1); // Add one kill to the kills the killer has made. if (!playerg.getName().equalsIgnoreCase(killerg.getName())) { killerg.setTotalKills(-1); killer.setLevel(killerg.getTotalKills()); killerg.setKills(-1); int kills = killerg.getKills(); if (kills % TF2.getInstance().getConfig().getInt("killstreaks") == 0) { game.broadcast(ChatColor.YELLOW + "[TF2] " + playerg.getTeamColor() + killer.getName() + " " + ChatColor.RESET + ChatColor.YELLOW + "is on a " + ChatColor.DARK_RED + ChatColor.BOLD + "" + kills + " " + ChatColor.RESET + ChatColor.YELLOW + "kill streak!"); } } player.setHealth(20); player.setFireTicks(0); TF2Class c = playerg.getCurrentClass(); c.apply(playerg); playerg.setJustSpawned(true); playerg.setIsDead(false); playerg.setPlayerLastDamagedBy(null); game.getScoreboard().updateBoard(); } }, 1L); } }
true
true
public void onDeath(final TF2DeathEvent event) { TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() { @Override public void run() { final Player player = event.getPlayer(); final GamePlayer playerg = GameUtilities.getUtilities().getGamePlayer(player); final Player killer = event.getKiller(); GamePlayer killerg = GameUtilities.getUtilities().getGamePlayer(killer); Game game = playerg.getGame(); Map map = game.getMap(); player.teleport(MapUtilities.getUtilities().loadTeamSpawn(map.getName(), playerg.getTeam())); player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KILLED-BY").replace("%teamcolor", killerg.getTeamColor()).replace("%player", killer.getName()).replace("%class", killerg.getCurrentClass().getName())); killer.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KILLED").replace("%teamcolor", playerg.getTeamColor()).replace("%player", player.getName()).replace("%class", playerg.getCurrentClass().getName())); killer.playSound(killer.getLocation(), Sound.valueOf(TF2.getInstance().getConfig().getString("killsound.sound")), TF2.getInstance().getConfig().getInt("killsound.volume"), TF2.getInstance().getConfig().getInt("killsound.pitch")); TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() { @Override public void run() { playerg.setJustSpawned(false); } }, 40L); // Reset the kills of the player who died. playerg.addKillstreak(playerg.getKills()); playerg.setKills(0); playerg.setDeaths(-1); playerg.settotalDeaths(-1); // Add one kill to the kills the killer has made. if (!playerg.getName().equalsIgnoreCase(killerg.getName())) { killerg.setTotalKills(-1); killer.setLevel(killerg.getTotalKills()); killerg.setKills(-1); int kills = killerg.getKills(); if (kills % TF2.getInstance().getConfig().getInt("killstreaks") == 0) { game.broadcast(ChatColor.YELLOW + "[TF2] " + playerg.getTeamColor() + killer.getName() + " " + ChatColor.RESET + ChatColor.YELLOW + "is on a " + ChatColor.DARK_RED + ChatColor.BOLD + "" + kills + " " + ChatColor.RESET + ChatColor.YELLOW + "kill streak!"); } } player.setHealth(20); player.setFireTicks(0); TF2Class c = playerg.getCurrentClass(); c.apply(playerg); playerg.setJustSpawned(true); playerg.setIsDead(false); playerg.setPlayerLastDamagedBy(null); game.getScoreboard().updateBoard(); } }, 1L); }
public void onDeath(final TF2DeathEvent event) { TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() { @Override public void run() { final Player player = event.getPlayer(); final GamePlayer playerg = GameUtilities.getUtilities().getGamePlayer(player); final Player killer = event.getKiller(); GamePlayer killerg = GameUtilities.getUtilities().getGamePlayer(killer); Game game = playerg.getGame(); if (game == null) { return; } Map map = game.getMap(); player.teleport(MapUtilities.getUtilities().loadTeamSpawn(map.getName(), playerg.getTeam())); player.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KILLED-BY").replace("%teamcolor", killerg.getTeamColor()).replace("%player", killer.getName()).replace("%class", killerg.getCurrentClass().getName())); killer.sendMessage(Localizer.getLocalizer().loadPrefixedMessage("PLAYER-KILLED").replace("%teamcolor", playerg.getTeamColor()).replace("%player", player.getName()).replace("%class", playerg.getCurrentClass().getName())); killer.playSound(killer.getLocation(), Sound.valueOf(TF2.getInstance().getConfig().getString("killsound.sound")), TF2.getInstance().getConfig().getInt("killsound.volume"), TF2.getInstance().getConfig().getInt("killsound.pitch")); TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() { @Override public void run() { playerg.setJustSpawned(false); } }, 40L); // Reset the kills of the player who died. playerg.addKillstreak(playerg.getKills()); playerg.setKills(0); playerg.setDeaths(-1); playerg.settotalDeaths(-1); // Add one kill to the kills the killer has made. if (!playerg.getName().equalsIgnoreCase(killerg.getName())) { killerg.setTotalKills(-1); killer.setLevel(killerg.getTotalKills()); killerg.setKills(-1); int kills = killerg.getKills(); if (kills % TF2.getInstance().getConfig().getInt("killstreaks") == 0) { game.broadcast(ChatColor.YELLOW + "[TF2] " + playerg.getTeamColor() + killer.getName() + " " + ChatColor.RESET + ChatColor.YELLOW + "is on a " + ChatColor.DARK_RED + ChatColor.BOLD + "" + kills + " " + ChatColor.RESET + ChatColor.YELLOW + "kill streak!"); } } player.setHealth(20); player.setFireTicks(0); TF2Class c = playerg.getCurrentClass(); c.apply(playerg); playerg.setJustSpawned(true); playerg.setIsDead(false); playerg.setPlayerLastDamagedBy(null); game.getScoreboard().updateBoard(); } }, 1L); }
diff --git a/blobstore-largeblob/src/main/java/org/jclouds/examples/blobstore/largeblob/MainApp.java b/blobstore-largeblob/src/main/java/org/jclouds/examples/blobstore/largeblob/MainApp.java index 169afc8..7e6eccd 100755 --- a/blobstore-largeblob/src/main/java/org/jclouds/examples/blobstore/largeblob/MainApp.java +++ b/blobstore-largeblob/src/main/java/org/jclouds/examples/blobstore/largeblob/MainApp.java @@ -1,179 +1,180 @@ /** * * Copyright (C) 2010 Cloud Conscious, LLC. <[email protected]> * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.jclouds.examples.blobstore.largeblob; import static org.jclouds.Constants.PROPERTY_ENDPOINT; import static org.jclouds.blobstore.options.PutOptions.Builder.multipart; import static org.jclouds.location.reference.LocationConstants.ENDPOINT; import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.concurrent.ExecutionException; import javax.ws.rs.core.MediaType; import org.jclouds.aws.domain.Region; import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.BlobStoreContextFactory; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.util.BlobStoreUtils; import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.netty.config.NettyPayloadModule; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Module; /** * Demonstrates the use of {@link BlobStore}. * * Usage is: java MainApp \"provider\" \"identity\" \"credential\" \"localFileName\" * \"containerName\" \"objectName\" plainhttp threadcount * * \"plainhttp\" and \"threadcound\" is optional if all the rest of parameters are omitted * * @author Tibor Kiss * @author Adrian Cole */ public class MainApp { public static int PARAMETERS = 6; public static String INVALID_SYNTAX = "Invalid number of parameters. Syntax is: \"provider\" \"identity\" \"credential\" \"localFileName\" \"containerName\" \"objectName\" plainhttp threadcount"; public final static Properties PLAIN_HTTP_ENDPOINTS = new Properties(); static { PLAIN_HTTP_ENDPOINTS.setProperty(PROPERTY_ENDPOINT, "http://s3.amazonaws.com"); PLAIN_HTTP_ENDPOINTS.setProperty(PROPERTY_REGION + "." + Region.US_STANDARD + "." + ENDPOINT, "http://s3.amazonaws.com"); PLAIN_HTTP_ENDPOINTS.setProperty(PROPERTY_REGION + "." + Region.US_WEST_1 + "." + ENDPOINT, "http://s3-us-west-1.amazonaws.com"); PLAIN_HTTP_ENDPOINTS.setProperty(PROPERTY_REGION + "." + "EU" + "." + ENDPOINT, "http://s3-eu-west-1.amazonaws.com"); PLAIN_HTTP_ENDPOINTS.setProperty(PROPERTY_REGION + "." + Region.AP_SOUTHEAST_1 + "." + ENDPOINT, "http://s3-ap-southeast-1.amazonaws.com"); } final static Iterable<? extends Module> MODULES = ImmutableSet.of(new JavaUrlHttpCommandExecutorServiceModule(), new Log4JLoggingModule(), new NettyPayloadModule()); // we may test different http layer with the following // ImmutableSet.of(new ApacheHCHttpCommandExecutorServiceModule(), new Log4JLoggingModule(), new // NettyPayloadModule()); static String getSpeed(long speed) { if (speed < 1024) { return "" + speed + " bytes/s"; } else if (speed < 1048576) { return "" + (speed / 1024) + " kbytes/s"; } else { return "" + (speed / 1048576) + " Mbytes/s"; } } static void printSpeed(String message, long start, long length) { long sec = (System.currentTimeMillis() - start) / 1000; if (sec == 0) return; long speed = length / sec; System.out.print(message); if (speed < 1024) { System.out.print(" " + length + " bytes"); } else if (speed < 1048576) { System.out.print(" " + (length / 1024) + " kB"); } else if (speed < 1073741824) { System.out.print(" " + (length / 1048576) + " MB"); } else { System.out.print(" " + (length / 1073741824) + " GB"); } System.out.println(" with " + getSpeed(speed) + " (" + length + " bytes)"); } public static void main(String[] args) throws IOException { if (args.length < PARAMETERS) throw new IllegalArgumentException(INVALID_SYNTAX); // Args String provider = args[0]; if (!Iterables.contains(BlobStoreUtils.getSupportedProviders(), provider)) throw new IllegalArgumentException("provider " + provider + " not in supported list: " + BlobStoreUtils.getSupportedProviders()); String identity = args[1]; String credential = args[2]; String fileName = args[3]; String containerName = args[4]; String objectName = args[5]; boolean plainhttp = args.length >= 7 && "plainhttp".equals(args[6]); String threadcount = args.length >= 8 ? args[7] : null; // Init Properties overrides = new Properties(); if (plainhttp) overrides.putAll(PLAIN_HTTP_ENDPOINTS); // default is https if (threadcount != null) overrides.setProperty("jclouds.mpu.parallel.degree", threadcount); // without setting, // default is 4 threads overrides.setProperty(provider + ".identity", identity); overrides.setProperty(provider + ".credential", credential); BlobStoreContext context = new BlobStoreContextFactory().createContext(provider, MODULES, overrides); try { long start = System.currentTimeMillis(); // Create Container AsyncBlobStore blobStore = context.getAsyncBlobStore(); // it can be changed to sync // BlobStore - blobStore.createContainerInLocation(null, containerName); + ListenableFuture<Boolean> future = blobStore.createContainerInLocation(null, containerName); + future.get(); File input = new File(fileName); long length = input.length(); // Add a Blob Blob blob = blobStore.blobBuilder(objectName).payload(input) .contentType(MediaType.APPLICATION_OCTET_STREAM).contentDisposition(objectName).build(); // Upload a file ListenableFuture<String> futureETag = blobStore.putBlob(containerName, blob, multipart()); // asynchronously wait for the upload String eTag = futureETag.get(); printSpeed("Sucessfully uploaded eTag(" + eTag + ")", start, length); } catch (InterruptedException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (ExecutionException e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { // Close connecton context.close(); System.exit(0); } } }
true
true
public static void main(String[] args) throws IOException { if (args.length < PARAMETERS) throw new IllegalArgumentException(INVALID_SYNTAX); // Args String provider = args[0]; if (!Iterables.contains(BlobStoreUtils.getSupportedProviders(), provider)) throw new IllegalArgumentException("provider " + provider + " not in supported list: " + BlobStoreUtils.getSupportedProviders()); String identity = args[1]; String credential = args[2]; String fileName = args[3]; String containerName = args[4]; String objectName = args[5]; boolean plainhttp = args.length >= 7 && "plainhttp".equals(args[6]); String threadcount = args.length >= 8 ? args[7] : null; // Init Properties overrides = new Properties(); if (plainhttp) overrides.putAll(PLAIN_HTTP_ENDPOINTS); // default is https if (threadcount != null) overrides.setProperty("jclouds.mpu.parallel.degree", threadcount); // without setting, // default is 4 threads overrides.setProperty(provider + ".identity", identity); overrides.setProperty(provider + ".credential", credential); BlobStoreContext context = new BlobStoreContextFactory().createContext(provider, MODULES, overrides); try { long start = System.currentTimeMillis(); // Create Container AsyncBlobStore blobStore = context.getAsyncBlobStore(); // it can be changed to sync // BlobStore blobStore.createContainerInLocation(null, containerName); File input = new File(fileName); long length = input.length(); // Add a Blob Blob blob = blobStore.blobBuilder(objectName).payload(input) .contentType(MediaType.APPLICATION_OCTET_STREAM).contentDisposition(objectName).build(); // Upload a file ListenableFuture<String> futureETag = blobStore.putBlob(containerName, blob, multipart()); // asynchronously wait for the upload String eTag = futureETag.get(); printSpeed("Sucessfully uploaded eTag(" + eTag + ")", start, length); } catch (InterruptedException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (ExecutionException e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { // Close connecton context.close(); System.exit(0); } }
public static void main(String[] args) throws IOException { if (args.length < PARAMETERS) throw new IllegalArgumentException(INVALID_SYNTAX); // Args String provider = args[0]; if (!Iterables.contains(BlobStoreUtils.getSupportedProviders(), provider)) throw new IllegalArgumentException("provider " + provider + " not in supported list: " + BlobStoreUtils.getSupportedProviders()); String identity = args[1]; String credential = args[2]; String fileName = args[3]; String containerName = args[4]; String objectName = args[5]; boolean plainhttp = args.length >= 7 && "plainhttp".equals(args[6]); String threadcount = args.length >= 8 ? args[7] : null; // Init Properties overrides = new Properties(); if (plainhttp) overrides.putAll(PLAIN_HTTP_ENDPOINTS); // default is https if (threadcount != null) overrides.setProperty("jclouds.mpu.parallel.degree", threadcount); // without setting, // default is 4 threads overrides.setProperty(provider + ".identity", identity); overrides.setProperty(provider + ".credential", credential); BlobStoreContext context = new BlobStoreContextFactory().createContext(provider, MODULES, overrides); try { long start = System.currentTimeMillis(); // Create Container AsyncBlobStore blobStore = context.getAsyncBlobStore(); // it can be changed to sync // BlobStore ListenableFuture<Boolean> future = blobStore.createContainerInLocation(null, containerName); future.get(); File input = new File(fileName); long length = input.length(); // Add a Blob Blob blob = blobStore.blobBuilder(objectName).payload(input) .contentType(MediaType.APPLICATION_OCTET_STREAM).contentDisposition(objectName).build(); // Upload a file ListenableFuture<String> futureETag = blobStore.putBlob(containerName, blob, multipart()); // asynchronously wait for the upload String eTag = futureETag.get(); printSpeed("Sucessfully uploaded eTag(" + eTag + ")", start, length); } catch (InterruptedException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (ExecutionException e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { // Close connecton context.close(); System.exit(0); } }
diff --git a/webbench/src/com/netease/webbench/blogbench/misc/ParameterGenerator.java b/webbench/src/com/netease/webbench/blogbench/misc/ParameterGenerator.java index 0597d97..791d6df 100644 --- a/webbench/src/com/netease/webbench/blogbench/misc/ParameterGenerator.java +++ b/webbench/src/com/netease/webbench/blogbench/misc/ParameterGenerator.java @@ -1,476 +1,476 @@ /** * Copyright (c) <2011>, <NetEase Corporation> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.netease.webbench.blogbench.misc; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import com.netease.webbench.blogbench.dao.BlogDAO; import com.netease.webbench.blogbench.dao.BlogDAOFactory; import com.netease.webbench.blogbench.misc.ntse.NTSEInitialiser; import com.netease.webbench.blogbench.model.Blog; import com.netease.webbench.blogbench.model.BlogInfoWithPub; import com.netease.webbench.blogbench.statis.ParaDistribution; import com.netease.webbench.common.DbOptions; import com.netease.webbench.common.DynamicArray; import com.netease.webbench.common.Util; import com.netease.webbench.random.GammaGenerator; import com.netease.webbench.random.ZipfGenerator; import com.netease.webbench.resourceReader.BlogResourceReader; import com.netease.webbench.resourceReader.ResourceReader; /** * query parameter generator * @author LI WEIZHAO */ public class ParameterGenerator { public static final int DEFAULT_MIN_RECORDS_LIMIT = 1000; /* array of character for generate blog title */ private final static char[] TITLE = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; /* random Zipf blog index generator */ private ZipfGenerator blgIndexGenerator; /* random Zipf user ID generator */ private ZipfGenerator userIdGenerator; /* random blog content length generator */ private GammaGenerator contentLenGenerator; /* random number generator */ private Random randomGenerator; /* <BlogId,UserId,CurrentTime> pair array */ private DynamicArray<BlogInfoWithPub> blgArr; /* blogbench test options */ private BbTestOptions bbTestOpt; private DbOptions dbOpt; /* range of blog title length */ private int titleLenRange; /* range of blog abstract length */ private int absRange; /* max blog id in test table */ private AtomicLong maxBlogId = new AtomicLong(0); /* buffer array of blog content */ private ArrayList<byte []> cntInitArr; /* blog table run time size */ private long tableRunTimeSize; private ParaDistribution paraDist; private ParaInitialiseHandler initialiseHandler; /** * constructor */ public ParameterGenerator() { titleLenRange = 0; absRange = 0; tableRunTimeSize = 0; cntInitArr = null; paraDist = new ParaDistribution(); } /** * create initialise helper * @param dbSession * @param dbOpt * @throws Exception */ private void initParaInitHandler(DbOptions dbOpt) throws Exception { if (0 == "run".compareToIgnoreCase(bbTestOpt.getOperType()) && dbOpt.getDbType().equalsIgnoreCase("mysql") && bbTestOpt.getTbEngine().equalsIgnoreCase("ntse")) { this.dbOpt = dbOpt; this.initialiseHandler = new NTSEInitialiser(dbOpt, bbTestOpt); } } /** * initialise parameter generator * @param opt * @param dbOpt * @throws Exception */ public void init(BbTestOptions opt, DbOptions dbOpt) throws Exception { System.out.println("Is initializing parameter generator..."); this.bbTestOpt = opt; this.dbOpt = dbOpt; initParaInitHandler(dbOpt); if (null != initialiseHandler) { initialiseHandler.doBeforeInit(); } //do real initialise work doInit(opt, this.dbOpt); if (null != initialiseHandler) { initialiseHandler.doAfterInit(); } System.out.println("Initializing parameter generator done!"); } /** * do real initialise work * @param opt * @param dbOpt * @throws Exception */ private void doInit(BbTestOptions opt, DbOptions dbOpt) throws Exception { this.titleLenRange = bbTestOpt.getMaxTtlSize() - bbTestOpt.getMinTtlSize() + 1; this.absRange = bbTestOpt.getMaxAbsSize() - bbTestOpt.getMinAbsSize() + 1; this.randomGenerator = new Random(); /* read all blog content files */ readBlogResouceFile(); int pst = bbTestOpt.getAvgCntSize() - bbTestOpt.getMinCntSize(); double beta = 0.5 * pst ; BlogDAO blogDao = BlogDAOFactory.getBlogDAO(dbOpt, bbTestOpt.getUseTwoTable()); - if (0 == "load".compareToIgnoreCase(opt.getOperType())) { + if (0 == "run".compareToIgnoreCase(opt.getOperType())) { maxBlogId.set(blogDao.selBlogNums() + 1); blgArr = blogDao.selAllBlogIds(); tableRunTimeSize = blgArr.size(); if (tableRunTimeSize < DEFAULT_MIN_RECORDS_LIMIT) { throw new Exception("The test table contains too less records: " + tableRunTimeSize); } System.out.println("Fetch " + tableRunTimeSize + " records from database."); } else { long tableOldSize = 0; if (!bbTestOpt.isCreateTable()) { tableOldSize = blogDao.selBlogNums(); maxBlogId.set(tableOldSize + 1); } tableRunTimeSize = tableOldSize + opt.getTbSize(); if (tableRunTimeSize < DEFAULT_MIN_RECORDS_LIMIT) { throw new Exception("The table size specified is too less: " + tableRunTimeSize + ", it should larger than " + DEFAULT_MIN_RECORDS_LIMIT); } } blgIndexGenerator = new ZipfGenerator(opt.getBlgZipfPct(), opt .getBlgZipfRes(), opt.getBlgZipfPart(), tableRunTimeSize, true, true); /* range of user ID is 1~tableSize/5 */ userIdGenerator = new ZipfGenerator(opt.getUserZipfPct(), opt .getUserZipfRes(), opt.getUserZipfPart(), tableRunTimeSize / 5, false, false); contentLenGenerator = new GammaGenerator(beta, pst, bbTestOpt.getMaxCntSize() - bbTestOpt.getMinCntSize(), true); } /** * read all blog content text files and cache them * @throws IOException */ private void readBlogResouceFile() throws IOException { ResourceReader blogResourceFileReader = new BlogResourceReader(); cntInitArr = new ArrayList<byte []>(blogResourceFileReader.getResourceFileNum()); for (int i = 0; i < blogResourceFileReader.getResourceFileNum(); i++) { InputStream is = blogResourceFileReader.getNextFileAsIntputStream(); if (null == is) break; int streamLen = is.available(); byte[] buf = new byte[streamLen]; is.read(buf, 0, streamLen); byte[] encodeBytes = new String(buf, "GBK").getBytes( Portable.getCharacterSet()); cntInitArr.add(encodeBytes); is.close(); } } /** * get blog user ID that follows Zipf distribution * @return blog user ID */ public long getZipfUserId() { long id = userIdGenerator.getZipfRandomNum(); paraDist.getUserIDDis().addResult(id); return id; } /** * get blog ID that follows Zipf distribution * @return blog ID */ public long getZipfBlogId() { long blogIndex = blgIndexGenerator.getZipfRandomNum(); long blogId = blgArr.get(blogIndex).getBlogId(); paraDist.getBlogIDDis().addResult(blogId); return blogId; } /** * get blog of which ID follows Zipf distribution * * @return */ public BlogInfoWithPub getZipfRandomBlog() { long blogIndex = blgIndexGenerator.getZipfRandomNum(); BlogInfoWithPub bi = blgArr.get(blogIndex); paraDist.getBlogIDDis().addResult(bi.getBlogId()); return bi; } /** * get current time * @return current time */ public long getCurrentTime() { return Util.currentTimeMillis(); } /** * generate new blog title * @return blog title */ public String getTitle() { char[] titleBuffer; titleBuffer = new char[bbTestOpt.getMaxTtlSize()]; int titleLen = bbTestOpt.getMinTtlSize() + randomGenerator.nextInt(titleLenRange); int i = 0; for (; i < titleLen; i++) { int index = randomGenerator.nextInt(26); titleBuffer[i] = TITLE[index]; } String title = new String(titleBuffer, 0, i); return title; } /** * get random blog content text file index * @return */ private int getRandomCntFileIndex() { return randomGenerator.nextInt(cntInitArr.size()); } /** * generate blog abstract according blog content * @param buf blog content buffer * @return blog abstract */ public String getAbs(byte[] buf) throws UnsupportedEncodingException { int absLen = bbTestOpt.getMinAbsSize() + randomGenerator.nextInt(absRange); int readLen = absLen > buf.length ? buf.length : absLen; byte[] newArr = new byte[readLen]; for (int i = 0; i < readLen; i++) { newArr[i] = buf[i]; } /* avoid UTF8 illegal character exception */ if (newArr[newArr.length - 1] == 0) { newArr[newArr.length - 1] = (byte)32; } return new String(newArr, Portable.getCharacterSet()); } /** * generate new blog content * @return new blog content * @throws UnsupportedEncodingException */ public byte[] getContent() throws Exception { int cntLen = 0; if (bbTestOpt.isExtraLargeBlog()) { double rdn = randomGenerator.nextDouble(); /* generate 1% large contents, large content length is between max/2 ~ max, follows binomial distribution */ if (rdn <= 0.01) { cntLen = (int)(bbTestOpt.getMaxCntSize() * (1 + randomGenerator.nextDouble()) / 2); } else { cntLen = bbTestOpt.getMinCntSize() + contentLenGenerator.getGammaRandomNum(); } } else { cntLen = bbTestOpt.getMinCntSize() + contentLenGenerator.getGammaRandomNum(); } paraDist.getContentLengthDis().addResult(cntLen); ByteBuffer buf = ByteBuffer.allocate(cntLen); int lenBuild = 0; while(lenBuild < cntLen) { int fileIndex = getRandomCntFileIndex(); byte[] byteArr = cntInitArr.get(fileIndex); if (byteArr.length >= (cntLen - lenBuild)) { buf.put(byteArr, 0, cntLen - lenBuild); break; } else { buf.put(byteArr); lenBuild += byteArr.length; } } /* avoid UTF8 illegal character exception */ if (!buf.hasArray()) throw new Exception("Failed to generate blog content test data! "); byte[] checkCnt = buf.array(); if (checkCnt[checkCnt.length - 1] == 0) { checkCnt[checkCnt.length - 1] = (byte)32; } return checkCnt; } /** * generate random allow view * @return allow view */ public int getAllowView() { double randomPro = randomGenerator.nextDouble(); int allowView = -100; if (randomPro < 0.91) { allowView = -100; } else if (randomPro >= 0.92) { allowView = 10000; } else { allowView = 100; } return allowView; } /** * generate new access count * @return access count */ public long getAccessCount() { return 0; } /** * generate new comment count * @return comment count */ public long getCommentCount() { return 0; } /** * update blogs array, used when publish new blog * @param blogId new blog ID * @param userId new blog user ID * @param publishTime new blog publish time */ public synchronized void updateBlgMapArr(long blogId, long userId, long publishTime) { BlogInfoWithPub newBlog = new BlogInfoWithPub(blogId, userId, publishTime); blgArr.append(newBlog); blgIndexGenerator.updateProb(); tableRunTimeSize++; } /** * increase current max blog ID and return it, multi-thread safe * @return new max blog ID */ public long increaseAndGetMaxBlogId() { return maxBlogId.incrementAndGet(); } /** * get frequency of hottest partition of blogs * @return */ public double getBlogHottestPartionFreq() { return blgIndexGenerator.getHottestPartionFreq(); } /** * get frequency of hottest partition of users * @return */ public double getUserHottestPartionFreq() { return userIdGenerator.getHottestPartionFreq(); } /** * get frequency of hottest pct% samples of blogs * @return */ public double getBlogHottestPctFreq() { return blgIndexGenerator.getHottestPctFreq(); } /** * get frequency of hottest pct% samples of users * @return */ public double getUserHottestPctFreq() { return userIdGenerator.getHottestPctFreq(); } /** * get a blog from current blogs according Zipf distribution and update it's properties * Blog ID is selected according Zipf distribution, and publish time, title, content, abstract, allow view are updated. * This function can be used for update-blog transaction. * @return new blog * @throws Exception */ public Blog generateZipfDistrBlog() throws Exception { BlogInfoWithPub blogInfo = getZipfRandomBlog(); long id= blogInfo.getBlogId(); long uId = blogInfo.getUId(); long pTime = getCurrentTime(); String title = getTitle(); byte[] contentBuf = getContent(); String abs = getAbs(contentBuf); String cnt = new String(contentBuf, Portable.getCharacterSet()); int allowView = getAllowView(); return new Blog(id, uId, title, abs, cnt, allowView, pTime, 0, 0); } /** * generate a new blog * Blog ID increases according current Blog table, UserID follows Zipf distribution * @return new Blog * @throws Exception */ public Blog generateNewBlog() throws Exception { long id= increaseAndGetMaxBlogId(); long uId = getZipfUserId(); long pTime = getCurrentTime(); String title = getTitle(); byte[] contentBuf = getContent(); String abs = getAbs(contentBuf); String cnt = new String(contentBuf, Portable.getCharacterSet()); int allowView = getAllowView(); return new Blog(id, uId, title, abs, cnt, allowView, pTime, 0, 0); } public ParaDistribution getParaDistribution() { return paraDist; } }
true
true
private void doInit(BbTestOptions opt, DbOptions dbOpt) throws Exception { this.titleLenRange = bbTestOpt.getMaxTtlSize() - bbTestOpt.getMinTtlSize() + 1; this.absRange = bbTestOpt.getMaxAbsSize() - bbTestOpt.getMinAbsSize() + 1; this.randomGenerator = new Random(); /* read all blog content files */ readBlogResouceFile(); int pst = bbTestOpt.getAvgCntSize() - bbTestOpt.getMinCntSize(); double beta = 0.5 * pst ; BlogDAO blogDao = BlogDAOFactory.getBlogDAO(dbOpt, bbTestOpt.getUseTwoTable()); if (0 == "load".compareToIgnoreCase(opt.getOperType())) { maxBlogId.set(blogDao.selBlogNums() + 1); blgArr = blogDao.selAllBlogIds(); tableRunTimeSize = blgArr.size(); if (tableRunTimeSize < DEFAULT_MIN_RECORDS_LIMIT) { throw new Exception("The test table contains too less records: " + tableRunTimeSize); } System.out.println("Fetch " + tableRunTimeSize + " records from database."); } else { long tableOldSize = 0; if (!bbTestOpt.isCreateTable()) { tableOldSize = blogDao.selBlogNums(); maxBlogId.set(tableOldSize + 1); } tableRunTimeSize = tableOldSize + opt.getTbSize(); if (tableRunTimeSize < DEFAULT_MIN_RECORDS_LIMIT) { throw new Exception("The table size specified is too less: " + tableRunTimeSize + ", it should larger than " + DEFAULT_MIN_RECORDS_LIMIT); } } blgIndexGenerator = new ZipfGenerator(opt.getBlgZipfPct(), opt .getBlgZipfRes(), opt.getBlgZipfPart(), tableRunTimeSize, true, true); /* range of user ID is 1~tableSize/5 */ userIdGenerator = new ZipfGenerator(opt.getUserZipfPct(), opt .getUserZipfRes(), opt.getUserZipfPart(), tableRunTimeSize / 5, false, false); contentLenGenerator = new GammaGenerator(beta, pst, bbTestOpt.getMaxCntSize() - bbTestOpt.getMinCntSize(), true); }
private void doInit(BbTestOptions opt, DbOptions dbOpt) throws Exception { this.titleLenRange = bbTestOpt.getMaxTtlSize() - bbTestOpt.getMinTtlSize() + 1; this.absRange = bbTestOpt.getMaxAbsSize() - bbTestOpt.getMinAbsSize() + 1; this.randomGenerator = new Random(); /* read all blog content files */ readBlogResouceFile(); int pst = bbTestOpt.getAvgCntSize() - bbTestOpt.getMinCntSize(); double beta = 0.5 * pst ; BlogDAO blogDao = BlogDAOFactory.getBlogDAO(dbOpt, bbTestOpt.getUseTwoTable()); if (0 == "run".compareToIgnoreCase(opt.getOperType())) { maxBlogId.set(blogDao.selBlogNums() + 1); blgArr = blogDao.selAllBlogIds(); tableRunTimeSize = blgArr.size(); if (tableRunTimeSize < DEFAULT_MIN_RECORDS_LIMIT) { throw new Exception("The test table contains too less records: " + tableRunTimeSize); } System.out.println("Fetch " + tableRunTimeSize + " records from database."); } else { long tableOldSize = 0; if (!bbTestOpt.isCreateTable()) { tableOldSize = blogDao.selBlogNums(); maxBlogId.set(tableOldSize + 1); } tableRunTimeSize = tableOldSize + opt.getTbSize(); if (tableRunTimeSize < DEFAULT_MIN_RECORDS_LIMIT) { throw new Exception("The table size specified is too less: " + tableRunTimeSize + ", it should larger than " + DEFAULT_MIN_RECORDS_LIMIT); } } blgIndexGenerator = new ZipfGenerator(opt.getBlgZipfPct(), opt .getBlgZipfRes(), opt.getBlgZipfPart(), tableRunTimeSize, true, true); /* range of user ID is 1~tableSize/5 */ userIdGenerator = new ZipfGenerator(opt.getUserZipfPct(), opt .getUserZipfRes(), opt.getUserZipfPart(), tableRunTimeSize / 5, false, false); contentLenGenerator = new GammaGenerator(beta, pst, bbTestOpt.getMaxCntSize() - bbTestOpt.getMinCntSize(), true); }
diff --git a/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java b/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java index 370c2018..19b850e8 100644 --- a/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java +++ b/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java @@ -1,150 +1,149 @@ package DeviceGraphicsDisplay; import java.awt.Graphics2D; import java.util.ArrayList; import javax.swing.JComponent; import DeviceGraphics.BinGraphics; import Networking.Client; import Networking.Request; import Utils.BinData; import Utils.Constants; import Utils.Location; import agent.data.Bin; public class GantryGraphicsDisplay extends DeviceGraphicsDisplay { Location currentLocation; Location destinationLocation; ArrayList<BinGraphicsDisplay> binList; boolean isBinHeld = false; // Determines whether or not the gantry is holding a bin boolean isMoving = false; BinGraphicsDisplay heldBin; BinData tempBin; Client client; double rotationAxisX; double rotationAxisY; int currentDegree; int finalDegree; public GantryGraphicsDisplay (Client c) { currentLocation = new Location (Constants.GANTRY_ROBOT_LOC); destinationLocation = new Location (Constants.GANTRY_ROBOT_LOC); binList = new ArrayList<BinGraphicsDisplay>(); client = c; tempBin = null; rotationAxisX = 0; rotationAxisY = 0; currentDegree = 0; finalDegree = 0; } @Override public void draw(JComponent c, Graphics2D g) { // If robot is at incorrect Y location, first move bot to inital X location if (currentLocation.getY() != destinationLocation.getY() && currentLocation.getX() != Constants.GANTRY_ROBOT_LOC.getX()) { if(currentLocation.getX() < Constants.GANTRY_ROBOT_LOC.getX()) { currentLocation.incrementX(5); } else if(currentLocation.getX() > Constants.GANTRY_ROBOT_LOC.getX()) { currentLocation.incrementX(-5); } } //If robot is in initial X, move to correct Y if(currentLocation.getX() == Constants.GANTRY_ROBOT_LOC.getX() && currentLocation.getY() != destinationLocation.getY()) { if(currentLocation.getY() < destinationLocation.getY()) { currentLocation.incrementY(5); } if(currentLocation.getY() > destinationLocation.getY()) { currentLocation.incrementY(-5); } } /* //If robot is at correct Y, rotate if (currentLocation.getY() == destinationLocation.getY()) { if (finalDegree == 0 || finalDegree == 180) { if (currentLocation.getX() < destinationLocation.getX()){ finalDegree = 90; } else finalDegree = -90; } if (currentDegree != finalDegree){ rotationAxisX = } }*/ //If robot is at correct Y and correct rotation, move to correct X if (currentLocation.getY() == destinationLocation.getY() && currentLocation.getX() != destinationLocation.getX()) { //&& currentDegree == finalDegree) { if(currentLocation.getX() < destinationLocation.getX()) { currentLocation.incrementX(5); } else if(currentLocation.getX() > destinationLocation.getX()) { currentLocation.incrementX(-5); } if(currentLocation.getX() == destinationLocation.getX() && isMoving == true) { client.sendData(new Request(Constants.GANTRY_ROBOT_DONE_MOVE, Constants.GANTRY_ROBOT_TARGET, null)); isMoving = false; } } for (int i = 0; i < binList.size(); i ++) { binList.get(i).drawWithOffset(c, g, client.getOffset()); binList.get(i).draw(c, g); } if (isBinHeld) { heldBin.setLocation(currentLocation); } g.drawImage(Constants.GANTRY_ROBOT_IMAGE, currentLocation.getX() + client.getOffset(), currentLocation.getY(), c); } @Override public void receiveData(Request req) { if (req.getCommand().equals(Constants.GANTRY_ROBOT_GET_BIN_COMMAND)) { tempBin = (BinData) req.getData(); for (int i = 0; i < binList.size(); i ++) if (binList.get(i).getPartType().equals(tempBin.getBinPartType())){ heldBin = binList.get(i); isBinHeld = true; } - //heldBin = new BinGraphicsDisplay(currentLocation, tempBin.getBinPartType()); tempBin = null; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_MOVE_TO_LOC_COMMAND)) { destinationLocation = (Location) req.getData(); isMoving = true; } - else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) { + else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) { heldBin = null; isBinHeld = false; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_ADD_NEW_BIN)) { tempBin = (BinData) req.getData(); binList.add(new BinGraphicsDisplay(tempBin.getBinLocation(), tempBin.getBinPartType())); tempBin = null; } } @Override public void setLocation(Location newLocation) { destinationLocation = newLocation; } }
false
true
public void draw(JComponent c, Graphics2D g) { // If robot is at incorrect Y location, first move bot to inital X location if (currentLocation.getY() != destinationLocation.getY() && currentLocation.getX() != Constants.GANTRY_ROBOT_LOC.getX()) { if(currentLocation.getX() < Constants.GANTRY_ROBOT_LOC.getX()) { currentLocation.incrementX(5); } else if(currentLocation.getX() > Constants.GANTRY_ROBOT_LOC.getX()) { currentLocation.incrementX(-5); } } //If robot is in initial X, move to correct Y if(currentLocation.getX() == Constants.GANTRY_ROBOT_LOC.getX() && currentLocation.getY() != destinationLocation.getY()) { if(currentLocation.getY() < destinationLocation.getY()) { currentLocation.incrementY(5); } if(currentLocation.getY() > destinationLocation.getY()) { currentLocation.incrementY(-5); } } /* //If robot is at correct Y, rotate if (currentLocation.getY() == destinationLocation.getY()) { if (finalDegree == 0 || finalDegree == 180) { if (currentLocation.getX() < destinationLocation.getX()){ finalDegree = 90; } else finalDegree = -90; } if (currentDegree != finalDegree){ rotationAxisX = } }*/ //If robot is at correct Y and correct rotation, move to correct X if (currentLocation.getY() == destinationLocation.getY() && currentLocation.getX() != destinationLocation.getX()) { //&& currentDegree == finalDegree) { if(currentLocation.getX() < destinationLocation.getX()) { currentLocation.incrementX(5); } else if(currentLocation.getX() > destinationLocation.getX()) { currentLocation.incrementX(-5); } if(currentLocation.getX() == destinationLocation.getX() && isMoving == true) { client.sendData(new Request(Constants.GANTRY_ROBOT_DONE_MOVE, Constants.GANTRY_ROBOT_TARGET, null)); isMoving = false; } } for (int i = 0; i < binList.size(); i ++) { binList.get(i).drawWithOffset(c, g, client.getOffset()); binList.get(i).draw(c, g); } if (isBinHeld) { heldBin.setLocation(currentLocation); } g.drawImage(Constants.GANTRY_ROBOT_IMAGE, currentLocation.getX() + client.getOffset(), currentLocation.getY(), c); } @Override public void receiveData(Request req) { if (req.getCommand().equals(Constants.GANTRY_ROBOT_GET_BIN_COMMAND)) { tempBin = (BinData) req.getData(); for (int i = 0; i < binList.size(); i ++) if (binList.get(i).getPartType().equals(tempBin.getBinPartType())){ heldBin = binList.get(i); isBinHeld = true; } //heldBin = new BinGraphicsDisplay(currentLocation, tempBin.getBinPartType()); tempBin = null; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_MOVE_TO_LOC_COMMAND)) { destinationLocation = (Location) req.getData(); isMoving = true; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) { heldBin = null; isBinHeld = false; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_ADD_NEW_BIN)) { tempBin = (BinData) req.getData(); binList.add(new BinGraphicsDisplay(tempBin.getBinLocation(), tempBin.getBinPartType())); tempBin = null; } } @Override public void setLocation(Location newLocation) { destinationLocation = newLocation; } }
public void draw(JComponent c, Graphics2D g) { // If robot is at incorrect Y location, first move bot to inital X location if (currentLocation.getY() != destinationLocation.getY() && currentLocation.getX() != Constants.GANTRY_ROBOT_LOC.getX()) { if(currentLocation.getX() < Constants.GANTRY_ROBOT_LOC.getX()) { currentLocation.incrementX(5); } else if(currentLocation.getX() > Constants.GANTRY_ROBOT_LOC.getX()) { currentLocation.incrementX(-5); } } //If robot is in initial X, move to correct Y if(currentLocation.getX() == Constants.GANTRY_ROBOT_LOC.getX() && currentLocation.getY() != destinationLocation.getY()) { if(currentLocation.getY() < destinationLocation.getY()) { currentLocation.incrementY(5); } if(currentLocation.getY() > destinationLocation.getY()) { currentLocation.incrementY(-5); } } /* //If robot is at correct Y, rotate if (currentLocation.getY() == destinationLocation.getY()) { if (finalDegree == 0 || finalDegree == 180) { if (currentLocation.getX() < destinationLocation.getX()){ finalDegree = 90; } else finalDegree = -90; } if (currentDegree != finalDegree){ rotationAxisX = } }*/ //If robot is at correct Y and correct rotation, move to correct X if (currentLocation.getY() == destinationLocation.getY() && currentLocation.getX() != destinationLocation.getX()) { //&& currentDegree == finalDegree) { if(currentLocation.getX() < destinationLocation.getX()) { currentLocation.incrementX(5); } else if(currentLocation.getX() > destinationLocation.getX()) { currentLocation.incrementX(-5); } if(currentLocation.getX() == destinationLocation.getX() && isMoving == true) { client.sendData(new Request(Constants.GANTRY_ROBOT_DONE_MOVE, Constants.GANTRY_ROBOT_TARGET, null)); isMoving = false; } } for (int i = 0; i < binList.size(); i ++) { binList.get(i).drawWithOffset(c, g, client.getOffset()); binList.get(i).draw(c, g); } if (isBinHeld) { heldBin.setLocation(currentLocation); } g.drawImage(Constants.GANTRY_ROBOT_IMAGE, currentLocation.getX() + client.getOffset(), currentLocation.getY(), c); } @Override public void receiveData(Request req) { if (req.getCommand().equals(Constants.GANTRY_ROBOT_GET_BIN_COMMAND)) { tempBin = (BinData) req.getData(); for (int i = 0; i < binList.size(); i ++) if (binList.get(i).getPartType().equals(tempBin.getBinPartType())){ heldBin = binList.get(i); isBinHeld = true; } tempBin = null; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_MOVE_TO_LOC_COMMAND)) { destinationLocation = (Location) req.getData(); isMoving = true; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) { heldBin = null; isBinHeld = false; } else if (req.getCommand().equals(Constants.GANTRY_ROBOT_ADD_NEW_BIN)) { tempBin = (BinData) req.getData(); binList.add(new BinGraphicsDisplay(tempBin.getBinLocation(), tempBin.getBinPartType())); tempBin = null; } } @Override public void setLocation(Location newLocation) { destinationLocation = newLocation; } }
diff --git a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/ImageTrace.java b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/ImageTrace.java index 1fb03e31f..7a3ec0e97 100644 --- a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/ImageTrace.java +++ b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/ImageTrace.java @@ -1,1144 +1,1142 @@ package org.dawb.workbench.plotting.system.swtxy; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.figures.IAxisListener; import org.csstudio.swt.xygraph.linearscale.Range; import org.dawb.common.services.HistogramBound; import org.dawb.common.services.IImageService; import org.dawb.common.services.IPaletteService; import org.dawb.common.services.ImageServiceBean; import org.dawb.common.services.ImageServiceBean.HistoType; import org.dawb.common.services.ImageServiceBean.ImageOrigin; import org.dawb.common.ui.plot.trace.IImageTrace; import org.dawb.common.ui.plot.trace.IPaletteListener; import org.dawb.common.ui.plot.trace.ITrace; import org.dawb.common.ui.plot.trace.ITraceContainer; import org.dawb.common.ui.plot.trace.PaletteEvent; import org.dawb.common.ui.plot.trace.TraceEvent; import org.dawb.common.ui.plot.trace.TraceUtils; import org.dawb.common.ui.plot.trace.TraceWillPlotEvent; import org.dawb.workbench.plotting.Activator; import org.dawb.workbench.plotting.preference.PlottingConstants; import org.dawb.workbench.plotting.system.PlottingSystemImpl; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.function.Downsample; import uk.ac.diamond.scisoft.analysis.dataset.function.DownsampleMode; import uk.ac.diamond.scisoft.analysis.roi.LinearROI; import uk.ac.diamond.scisoft.analysis.roi.PointROI; import uk.ac.diamond.scisoft.analysis.roi.PolygonalROI; import uk.ac.diamond.scisoft.analysis.roi.PolylineROI; import uk.ac.diamond.scisoft.analysis.roi.ROIBase; import uk.ac.diamond.scisoft.analysis.roi.RectangularROI; /** * A trace which draws an image to the plot. * * @author fcp94556 * */ public class ImageTrace extends Figure implements IImageTrace, IAxisListener, ITraceContainer { private static final Logger logger = LoggerFactory.getLogger(ImageTrace.class); private static final int MINIMUM_ZOOM_SIZE = 4; private String name; private Axis xAxis; private Axis yAxis; private AbstractDataset image; private DownsampleType downsampleType=DownsampleType.MEAN; private int currentDownSampleBin=-1; private List<AbstractDataset> axes; private ImageServiceBean imageServiceBean; private boolean isMaximumZoom; private PlottingSystemImpl plottingSystem; private IImageService service; public ImageTrace(final String name, final Axis xAxis, final Axis yAxis) { this.name = name; this.xAxis = xAxis; this.yAxis = yAxis; this.imageServiceBean = new ImageServiceBean(); try { final IPaletteService pservice = (IPaletteService)PlatformUI.getWorkbench().getService(IPaletteService.class); final String scheme = Activator.getDefault().getPreferenceStore().getString(PlottingConstants.COLOUR_SCHEME); imageServiceBean.setPalette(pservice.getPaletteData(scheme)); } catch (Exception e) { logger.error("Cannot create palette!", e); } imageServiceBean.setOrigin(ImageOrigin.forLabel(Activator.getDefault().getPreferenceStore().getString(PlottingConstants.ORIGIN_PREF))); imageServiceBean.setHistogramType(HistoType.forLabel(Activator.getDefault().getPreferenceStore().getString(PlottingConstants.HISTO_PREF))); imageServiceBean.setMinimumCutBound(HistogramBound.fromString(Activator.getDefault().getPreferenceStore().getString(PlottingConstants.MIN_CUT))); imageServiceBean.setMaximumCutBound(HistogramBound.fromString(Activator.getDefault().getPreferenceStore().getString(PlottingConstants.MAX_CUT))); imageServiceBean.setNanBound(HistogramBound.fromString(Activator.getDefault().getPreferenceStore().getString(PlottingConstants.NAN_CUT))); this.service = (IImageService)PlatformUI.getWorkbench().getService(IImageService.class); xAxis.addListener(this); yAxis.addListener(this); xAxis.setTicksAtEnds(false); yAxis.setTicksAtEnds(false); if (xAxis instanceof AspectAxis && yAxis instanceof AspectAxis) { AspectAxis x = (AspectAxis)xAxis; AspectAxis y = (AspectAxis)yAxis; x.setKeepAspectWith(y); y.setKeepAspectWith(x); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public AspectAxis getXAxis() { return (AspectAxis)xAxis; } public void setXAxis(Axis xAxis) { this.xAxis = xAxis; } public AspectAxis getYAxis() { return (AspectAxis)yAxis; } public void setYAxis(Axis yAxis) { this.yAxis = yAxis; } public AbstractDataset getImage() { return image; } public PaletteData getPaletteData() { if (imageServiceBean==null) return null; return imageServiceBean.getPalette(); } public void setPaletteData(PaletteData paletteData) { if (imageServiceBean==null) return; imageServiceBean.setPalette(paletteData); createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); firePaletteDataListeners(paletteData); } private enum ImageScaleType { // Going up in order of work done NO_REIMAGE, REIMAGE_ALLOWED, FORCE_REIMAGE, REHISTOGRAM; } private Image scaledImage; private ImageData imageData; private boolean imageCreationAllowed = true; /** * When this is called the SWT image is created * and saved in the swtImage field. The image is downsampled. If rescaleAllowed * is set to false, the current bin is not checked and the last scaled image * is always used. * * Do not synchronized this method - it can cause a race condition on linux only. * * @return true if scaledImage created. */ private double xOffset; private double yOffset; private boolean createScaledImage(ImageScaleType rescaleType, final IProgressMonitor monitor) { if (!imageCreationAllowed) return false; boolean requireImageGeneration = imageData==null || rescaleType==ImageScaleType.FORCE_REIMAGE || rescaleType==ImageScaleType.REHISTOGRAM; // We know that it is needed // If we just changed downsample scale, we force the update. // This allows user resizes of the plot area to be picked up // and the larger data size used if it fits. if (!requireImageGeneration && rescaleType==ImageScaleType.REIMAGE_ALLOWED && currentDownSampleBin>0) { if (getDownsampleBin()!=currentDownSampleBin) { requireImageGeneration = true; } } final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle rbounds = graph.getRegionArea().getBounds(); if (rbounds.width<1 || rbounds.height<1) return false; if (!imageCreationAllowed) return false; if (monitor!=null && monitor.isCanceled()) return false; if (requireImageGeneration) { try { imageCreationAllowed = false; if (image==null) return false; AbstractDataset reducedFullImage = getDownsampled(image); imageServiceBean.setImage(reducedFullImage); imageServiceBean.setMonitor(monitor); if (fullMask!=null) { imageServiceBean.setMask(getDownsampled(fullMask)); } else { imageServiceBean.setMask(null); // Ensure we lose the mask! } if (rescaleType==ImageScaleType.REHISTOGRAM) { // Avoids changing colouring to // max and min of new selection. AbstractDataset slice = slice(getXAxis().getRange(), getYAxis().getRange(), getData()); ImageServiceBean histoBean = new ImageServiceBean(slice, getHistoType()); if (fullMask!=null) histoBean.setMask(slice(getXAxis().getRange(), getYAxis().getRange(), fullMask)); float[] fa = service.getFastStatistics(histoBean); // Not sure how to deal with this better, but if the bean is logged, then you need to modify the values if (imageServiceBean.isLogColorScale()) { setMin(Math.log10(fa[0])); setMax(Math.log10(fa[1])); } else { setMin(fa[0]); setMax(fa[1]); } } this.imageData = service.getImageData(imageServiceBean); } catch (Exception e) { logger.error("Cannot create image from data!", e); } finally { imageCreationAllowed = true; } } if (monitor!=null && monitor.isCanceled()) return false; try { isMaximumZoom = false; if (imageData!=null && imageData.width==bounds.width && imageData.height==bounds.height) { // No slice, faster if (monitor!=null && monitor.isCanceled()) return false; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = new Image(Display.getDefault(), imageData); } else { // slice data to get current zoom area /** * x1,y1--------------x2,y2 * | | * | | * | | * x3,y3--------------x4,y4 */ ImageData data = imageData; ImageOrigin origin = getImageOrigin(); Range xRange = xAxis.getRange(); Range yRange = yAxis.getRange(); double minX = xRange.getLower()/currentDownSampleBin; double minY = yRange.getLower()/currentDownSampleBin; double maxX = xRange.getUpper()/currentDownSampleBin; double maxY = yRange.getUpper()/currentDownSampleBin; - int xSize = imageData.width/currentDownSampleBin; - int ySize = imageData.height/currentDownSampleBin; + int xSize = imageData.width; + int ySize = imageData.height; // check as getLower and getUpper don't work as expected if(maxX < minX){ double temp = maxX; maxX = minX; minX = temp; } if(maxY < minY){ double temp = maxY; maxY = minY; minY = temp; } double xSpread = maxX - minX; double ySpread = maxY - minY; double xScale = rbounds.width / xSpread; double yScale = rbounds.height / ySpread; // System.err.println("Area is " + rbounds + " with scale (x,y) " + xScale + ", " + yScale); // Deliberately get the over-sized dimensions so that the edge pixels can be smoothly panned through. int minXI = (int) Math.floor(minX); int minYI = (int) Math.floor(minY); int maxXI = (int) Math.ceil(maxX); int maxYI = (int) Math.ceil(maxY); int fullWidth = (int) (maxXI-minXI); int fullHeight = (int) (maxYI-minYI); // Force a minimum size on the system if (fullWidth <= MINIMUM_ZOOM_SIZE) { if (fullWidth > imageData.width) fullWidth = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } if (fullHeight <= MINIMUM_ZOOM_SIZE) { if (fullHeight > imageData.height) fullHeight = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } int scaleWidth = (int) (fullWidth*xScale); int scaleHeight = (int) (fullHeight*yScale); // System.err.println("Scaling to " + scaleWidth + "x" + scaleHeight); int xPix = (int)minX; int yPix = (int)minY; double xPixD = 0; double yPixD = 0; // These offsets are used when the scaled images is drawn to the screen. xOffset = (minX - Math.floor(minX))*xScale; yOffset = (minY - Math.floor(minY))*yScale; // Deal with the origin orientations correctly. switch (origin) { case TOP_LEFT: break; case TOP_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; break; case BOTTOM_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; case BOTTOM_LEFT: yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; } + // Slice the data. + // Pixel slice on downsampled data = fast! if (imageData.depth <= 8) { - // Slice the data. - // Pixel slice on downsampled data = fast! // NOTE Assumes 8-bit images final int size = fullWidth*fullHeight; final byte[] pixels = new byte[size]; for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, fullWidth*y); } data = new ImageData(fullWidth, fullHeight, data.depth, getPaletteData(), 1, pixels); } else { - // Slice the data. - // Pixel slice on downsampled data = fast! // NOTE Assumes 24 Bit Images final int[] pixels = new int[fullWidth]; data = new ImageData(fullWidth, fullHeight, 24, new PaletteData(0xff0000, 0x00ff00, 0x0000ff)); for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, 0); data.setPixels(0, y, fullWidth, pixels, 0); } } // create the scaled image data = data!=null ? data.scaledTo(scaleWidth, scaleHeight) : null; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } return true; } catch (NullPointerException ne) { throw ne; } catch (Throwable ne) { logger.error("Image scale error!", ne); return false; } } private static final int[] getBounds(Range xr, Range yr) { return new int[] {(int) Math.floor(xr.getLower()), (int) Math.floor(yr.getLower()), (int) Math.ceil(xr.getUpper()), (int) Math.ceil(yr.getUpper())}; } private Map<Integer, Reference<Object>> mipMap; private Map<Integer, Reference<Object>> maskMap; private AbstractDataset getDownsampled(AbstractDataset image) { // Down sample, no point histogramming the whole thing final int bin = getDownsampleBin(); this.currentDownSampleBin = bin; if (bin==1) { logger.trace("No downsample bin (or bin=1)"); return image; // nothing to downsample } if (image.getDtype()!=AbstractDataset.BOOL) { if (mipMap!=null && mipMap.containsKey(bin) && mipMap.get(bin).get()!=null) { logger.trace("Downsample bin used, "+bin); return (AbstractDataset)mipMap.get(bin).get(); } } else { if (maskMap!=null && maskMap.containsKey(bin) && maskMap.get(bin).get()!=null) { logger.trace("Downsample mask bin used, "+bin); return (AbstractDataset)maskMap.get(bin).get(); } } final Downsample downSampler = new Downsample(getDownsampleTypeDiamond(), new int[]{bin,bin}); List<AbstractDataset> sets = downSampler.value(image); final AbstractDataset set = sets.get(0); if (image.getDtype()!=AbstractDataset.BOOL) { if (mipMap==null) mipMap = new HashMap<Integer,Reference<Object>>(3); mipMap.put(bin, new SoftReference<Object>(set)); logger.trace("Downsample bin created, "+bin); } else { if (maskMap==null) maskMap = new HashMap<Integer,Reference<Object>>(3); maskMap.put(bin, new SoftReference<Object>(set)); logger.trace("Downsample mask bin created, "+bin); } return set; } @Override public AbstractDataset getDownsampled() { return getDownsampled(getImage()); } public AbstractDataset getDownsampledMask() { if (getMask()==null) return null; return getDownsampled(getMask()); } /** * Returns the bin for downsampling, either 1,2,4 or 8 currently. * This gives a pixel count of 1,4,16 or 64 for the bin. If 1 no * binning at all is done and no downsampling is being done, getDownsampled() * will return the AbstractDataset ok even if bin is one (no downsampling). * * @param slice * @param bounds * @return */ public int getDownsampleBin() { final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle realBounds = graph.getRegionArea().getBounds(); double rwidth = getSpan(getXAxis()); double rheight = getSpan(getYAxis()); int iwidth = realBounds.width; int iheight = realBounds.height; if (iwidth>(rwidth/2d) || iheight>(rheight/2d)) { return 1; } if (iwidth>(rwidth/4d) || iheight>(rheight/4d)) { return 2; } if (iwidth>(rwidth/8d) || iheight>(rheight/8d)) { return 4; } return 8; } private double getSpan(Axis axis) { final Range range = axis.getRange(); return Math.max(range.getUpper(),range.getLower()) - Math.min(range.getUpper(), range.getLower()); } private boolean lastAspectRatio = true; @Override protected void paintFigure(Graphics graphics) { super.paintFigure(graphics); /** * This is not actually needed except that when there * are a number of opens of an image, e.g. when moving * around an h5 gallery with arrow keys, it looks smooth * with this in. */ if (scaledImage==null || !isKeepAspectRatio() || lastAspectRatio!=isKeepAspectRatio()) { boolean imageReady = createScaledImage(ImageScaleType.NO_REIMAGE, null); if (!imageReady) return; lastAspectRatio = isKeepAspectRatio(); } graphics.pushState(); final XYRegionGraph graph = (XYRegionGraph)xAxis.getParent(); final Point loc = graph.getRegionArea().getLocation(); // Offsets and scaled image are calculated in the createScaledImage method. graphics.drawImage(scaledImage, loc.x-((int)xOffset), loc.y-((int)yOffset)); graphics.popState(); } private boolean isKeepAspectRatio() { return getXAxis().isKeepAspect() && getYAxis().isKeepAspect(); } public void remove() { if (mipMap!=null) mipMap.clear(); if (maskMap!=null) maskMap.clear(); if (scaledImage!=null) scaledImage.dispose(); if (paletteListeners!=null) paletteListeners.clear(); paletteListeners = null; clearAspect(xAxis); clearAspect(yAxis); if (getParent()!=null) getParent().remove(this); xAxis.removeListener(this); yAxis.removeListener(this); xAxis.setTicksAtEnds(true); yAxis.setTicksAtEnds(true); axisRedrawActive = false; imageServiceBean.dispose(); if (this.scaledImage!=null && !scaledImage.isDisposed()) scaledImage.dispose(); imageServiceBean = null; service = null; } private void clearAspect(Axis axis) { if (axis instanceof AspectAxis ) { AspectAxis aaxis = (AspectAxis)axis; aaxis.setKeepAspectWith(null); aaxis.setMaximumRange(null); } } @Override public AbstractDataset getData() { return image; } /** * Create a slice of data from given ranges * @param xr * @param yr * @return */ private final AbstractDataset slice(Range xr, Range yr, final AbstractDataset data) { // Check that a slice needed, this speeds up the initial show of the image. final int[] shape = data.getShape(); final int[] imageRanges = getImageBounds(shape, getImageOrigin()); final int[] bounds = getBounds(xr, yr); if (imageRanges!=null && Arrays.equals(imageRanges, bounds)) { return data; } int[] xRange = getRange(bounds, shape[0], 0, false); int[] yRange = getRange(bounds, shape[1], 1, false); try { return data.getSlice(new int[]{xRange[0],yRange[0]}, new int[]{xRange[1],yRange[1]}, null); } catch (IllegalArgumentException iae) { logger.error("Cannot slice image", iae); return data; } } private static final int[] getRange(int[] bounds, int side, int index, boolean inverted) { int start = bounds[index]; if (inverted) start = side-start; int stop = bounds[2+index]; if (inverted) stop = side-stop; if (start>stop) { start = bounds[2+index]; if (inverted) start = side-start; stop = bounds[index]; if (inverted) stop = side-stop; } return new int[]{start, stop}; } private boolean axisRedrawActive = true; @Override public void axisRangeChanged(Axis axis, Range old_range, Range new_range) { //createScaledImage(true, null); } /** * We do a bit here to ensure that * not too many calls to createScaledImage(...) are made. */ @Override public void axisRevalidated(Axis axis) { if (axis.isYAxis()) updateAxisRange(axis); } private void updateAxisRange(Axis axis) { if (!axisRedrawActive) return; createScaledImage(ImageScaleType.REIMAGE_ALLOWED, null); } private void setAxisRedrawActive(boolean b) { this.axisRedrawActive = b; } public void performAutoscale() { final int[] shape = image.getShape(); switch(getImageOrigin()) { case TOP_LEFT: xAxis.setRange(0, shape[1]); yAxis.setRange(shape[0], 0); break; case BOTTOM_LEFT: xAxis.setRange(0, shape[0]); yAxis.setRange(0, shape[1]); break; case BOTTOM_RIGHT: xAxis.setRange(shape[1], 0); yAxis.setRange(0, shape[0]); break; case TOP_RIGHT: xAxis.setRange(shape[0], 0); yAxis.setRange(shape[1], 0); break; } } private static final int[] getImageBounds(int[] shape, ImageOrigin origin) { if (origin==null) origin = ImageOrigin.TOP_LEFT; switch (origin) { case TOP_LEFT: return new int[] {0, shape[0], shape[1], 0}; case BOTTOM_LEFT: return new int[] {0, 0, shape[0], shape[1]}; case BOTTOM_RIGHT: return new int[] {shape[1], 0, 0, shape[0]}; case TOP_RIGHT: return new int[] {shape[0], shape[1], 0, 0}; } return null; } public void setImageOrigin(ImageOrigin imageOrigin) { if (this.mipMap!=null) mipMap.clear(); imageServiceBean.setOrigin(imageOrigin); createAxisBounds(); performAutoscale(); createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); fireImageOriginListeners(); } /** * Creates new axis bounds, updates the label data set */ private void createAxisBounds() { final int[] shape = image.getShape(); if (getImageOrigin()==ImageOrigin.TOP_LEFT || getImageOrigin()==ImageOrigin.BOTTOM_RIGHT) { setupAxis(getXAxis(), new Range(0,shape[1]), axes!=null&&axes.size()>0 ? axes.get(0) : null); setupAxis(getYAxis(), new Range(0,shape[0]), axes!=null&&axes.size()>1 ? axes.get(1) : null); } else { setupAxis(getXAxis(), new Range(0,shape[0]), axes!=null&&axes.size()>1 ? axes.get(1) : null); setupAxis(getYAxis(), new Range(0,shape[1]), axes!=null&&axes.size()>0 ? axes.get(0) : null); } } private void setupAxis(Axis axis, Range bounds, AbstractDataset labels) { ((AspectAxis)axis).setMaximumRange(bounds); ((AspectAxis)axis).setLabelDataAndTitle(labels); } @Override public ImageOrigin getImageOrigin() { if (imageServiceBean==null) return ImageOrigin.TOP_LEFT; return imageServiceBean.getOrigin(); } private boolean rescaleHistogram = true; public boolean isRescaleHistogram() { return rescaleHistogram; } public void setRescaleHistogram(boolean rescaleHistogram) { this.rescaleHistogram = rescaleHistogram; } @Override public boolean setData(AbstractDataset image, List<AbstractDataset> axes, boolean performAuto) { if (plottingSystem!=null) try { if (plottingSystem.getTraces().contains(this)) { final TraceWillPlotEvent evt = new TraceWillPlotEvent(this, false); evt.setImageData(image, axes); evt.setNewImageDataSet(false); plottingSystem.fireWillPlot(evt); if (!evt.doit) return false; if (evt.isNewImageDataSet()) { image = evt.getImage(); axes = evt.getAxes(); } } } catch (Throwable ignored) { // We allow things to proceed without a warning. } // The image is drawn low y to the top left but the axes are low y to the bottom right // We do not currently reflect it as it takes too long. Instead in the slice // method, we allow for the fact that the dataset is in a different orientation to // what is plotted. this.image = image; if (this.mipMap!=null) mipMap.clear(); if (imageServiceBean==null) imageServiceBean = new ImageServiceBean(); imageServiceBean.setImage(image); if (service==null) service = (IImageService)PlatformUI.getWorkbench().getService(IImageService.class); if (rescaleHistogram) { final float[] fa = service.getFastStatistics(imageServiceBean); setMin(fa[0]); setMax(fa[1]); } setAxes(axes, performAuto); if (plottingSystem!=null) try { if (plottingSystem.getTraces().contains(this)) { plottingSystem.fireTraceUpdated(new TraceEvent(this)); } } catch (Throwable ignored) { // We allow things to proceed without a warning. } return true; } @Override public void setAxes(List<AbstractDataset> axes, boolean performAuto) { this.axes = axes; createAxisBounds(); if (performAuto) { try { setAxisRedrawActive(false); performAutoscale(); } finally { setAxisRedrawActive(true); } } else { createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); } } public Number getMin() { return imageServiceBean.getMin(); } public void setMin(Number min) { if (imageServiceBean==null) return; imageServiceBean.setMin(min); fireMinDataListeners(); } public Number getMax() { return imageServiceBean.getMax(); } public void setMax(Number max) { if (imageServiceBean==null) return; imageServiceBean.setMax(max); fireMaxDataListeners(); } @Override public ImageServiceBean getImageServiceBean() { return imageServiceBean; } private Collection<IPaletteListener> paletteListeners; @Override public void addPaletteListener(IPaletteListener pl) { if (paletteListeners==null) paletteListeners = new HashSet<IPaletteListener>(11); paletteListeners.add(pl); } @Override public void removePaletteListener(IPaletteListener pl) { if (paletteListeners==null) return; paletteListeners.remove(pl); } private void firePaletteDataListeners(PaletteData paletteData) { if (paletteListeners==null) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); // Important do not let Mark get at it :) for (IPaletteListener pl : paletteListeners) pl.paletteChanged(evt); } private void fireMinDataListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.minChanged(evt); } private void fireMaxDataListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.maxChanged(evt); } private void fireMaxCutListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.maxCutChanged(evt); } private void fireMinCutListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.minCutChanged(evt); } private void fireNanBoundsListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.nanBoundsChanged(evt); } private void fireMaskListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.maskChanged(evt); } private void fireImageOriginListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.imageOriginChanged(evt); } @Override public DownsampleType getDownsampleType() { return downsampleType; } @Override public void setDownsampleType(DownsampleType type) { if (this.mipMap!=null) mipMap.clear(); this.downsampleType = type; createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); } private DownsampleMode getDownsampleTypeDiamond() { switch(getDownsampleType()) { case MEAN: return DownsampleMode.MEAN; case MAXIMUM: return DownsampleMode.MAXIMUM; case MINIMUM: return DownsampleMode.MINIMUM; case POINT: return DownsampleMode.POINT; } return DownsampleMode.MEAN; } @Override public void rehistogram() { if (imageServiceBean==null) return; imageServiceBean.setMax(null); imageServiceBean.setMin(null); createScaledImage(ImageScaleType.REHISTOGRAM, null); // Max and min changed in all likely-hood fireMaxDataListeners(); fireMinDataListeners(); repaint(); } @Override public List<AbstractDataset> getAxes() { return axes; } /** * return the HistoType being used * @return */ @Override public HistoType getHistoType() { if (imageServiceBean==null) return null; return imageServiceBean.getHistogramType(); } /** * Sets the histo type. */ @Override public void setHistoType(HistoType type) { if (imageServiceBean==null) return; imageServiceBean.setHistogramType(type); Activator.getDefault().getPreferenceStore().setValue(PlottingConstants.HISTO_PREF, type.getLabel()); createScaledImage(ImageScaleType.REHISTOGRAM, null); repaint(); } @Override public ITrace getTrace() { return this; } @Override public void setTrace(ITrace trace) { // Does nothing, you cannot change the trace, this is the trace. } public void setImageUpdateActive(boolean active) { this.imageCreationAllowed = active; if (active) { createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); } firePaletteDataListeners(getPaletteData()); } @Override public HistogramBound getMinCut() { return imageServiceBean.getMinimumCutBound(); } @Override public void setMinCut(HistogramBound bound) { storeBound(bound, PlottingConstants.MIN_CUT); if (imageServiceBean==null) return; imageServiceBean.setMinimumCutBound(bound); fireMinCutListeners(); } private void storeBound(HistogramBound bound, String prop) { if (bound!=null) { Activator.getDefault().getPreferenceStore().setValue(prop, bound.toString()); } else { Activator.getDefault().getPreferenceStore().setValue(prop, ""); } } @Override public HistogramBound getMaxCut() { return imageServiceBean.getMaximumCutBound(); } @Override public void setMaxCut(HistogramBound bound) { storeBound(bound, PlottingConstants.MAX_CUT); if (imageServiceBean==null) return; imageServiceBean.setMaximumCutBound(bound); fireMaxCutListeners(); } @Override public HistogramBound getNanBound() { return imageServiceBean.getNanBound(); } @Override public void setNanBound(HistogramBound bound) { storeBound(bound, PlottingConstants.NAN_CUT); if (imageServiceBean==null) return; imageServiceBean.setNanBound(bound); fireNanBoundsListeners(); } private AbstractDataset fullMask; /** * The masking dataset of there is one, normally null. * @return */ public AbstractDataset getMask() { return fullMask; } /** * * @param bd */ public void setMask(AbstractDataset bd) { if (maskMap!=null) maskMap.clear(); fullMask = bd; rehistogram(); fireMaskListeners(); } private boolean userTrace = true; @Override public boolean isUserTrace() { return userTrace; } @Override public void setUserTrace(boolean isUserTrace) { this.userTrace = isUserTrace; } public boolean isMaximumZoom() { return isMaximumZoom; } private Object userObject; public Object getUserObject() { return userObject; } public void setUserObject(Object userObject) { this.userObject = userObject; } /** * If the axis data set has been set, this method will return * a selection region in the coordinates of the axes labels rather * than the indices. * * Ellipse and Sector rois are not currently supported. * * @return ROI in label coordinates. This roi is not that useful after it * is created. The data processing needs rois with indices. */ @Override public ROIBase getRegionInAxisCoordinates(final ROIBase roi) throws Exception { if (!TraceUtils.isCustomAxes(this)) return roi; final AbstractDataset xl = axes.get(0); // May be null final AbstractDataset yl = axes.get(1); // May be null if (roi instanceof LinearROI) { double[] sp = ((LinearROI)roi).getPoint(); double[] ep = ((LinearROI)roi).getEndPoint(); transform(xl,0,sp,ep); transform(yl,1,sp,ep); return new LinearROI(sp, ep); } else if (roi instanceof PolylineROI) { PolylineROI proi = (PolylineROI)roi; final PolylineROI ret = (proi instanceof PolygonalROI) ? new PolygonalROI() : new PolylineROI(); for (PointROI pointROI : proi) { double[] dp = pointROI.getPoint(); transform(xl,0,dp); transform(yl,1,dp); ret.insertPoint(dp); } } else if (roi instanceof PointROI) { double[] dp = ((PointROI)roi).getPoint(); transform(xl,0,dp); transform(yl,1,dp); return new PointROI(dp); } else if (roi instanceof RectangularROI) { RectangularROI rroi = (RectangularROI)roi; double[] sp=roi.getPoint(); double[] ep=rroi.getEndPoint(); transform(xl,0,sp,ep); transform(yl,1,sp,ep); return new RectangularROI(sp[0], sp[1], ep[0]-sp[0], sp[1]-ep[1], rroi.getAngle()); } else { throw new Exception("Unsupported roi "+roi.getClass()); } return roi; } @Override public double[] getPointInAxisCoordinates(final double[] point) throws Exception { if (!TraceUtils.isCustomAxes(this)) return point; final AbstractDataset xl = axes.get(0); // May be null final AbstractDataset yl = axes.get(1); // May be null transform(xl,0,point); transform(yl,1,point); return point; } private void transform(AbstractDataset label, int index, double[]... points) { if (label!=null) { for (double[] ds : points) { int dataIndex = (int)ds[index]; ds[index] = label.getDouble(dataIndex); } } } public PlottingSystemImpl getPlottingSystem() { return plottingSystem; } public void setPlottingSystem(PlottingSystemImpl plottingSystem) { this.plottingSystem = plottingSystem; } }
false
true
private boolean createScaledImage(ImageScaleType rescaleType, final IProgressMonitor monitor) { if (!imageCreationAllowed) return false; boolean requireImageGeneration = imageData==null || rescaleType==ImageScaleType.FORCE_REIMAGE || rescaleType==ImageScaleType.REHISTOGRAM; // We know that it is needed // If we just changed downsample scale, we force the update. // This allows user resizes of the plot area to be picked up // and the larger data size used if it fits. if (!requireImageGeneration && rescaleType==ImageScaleType.REIMAGE_ALLOWED && currentDownSampleBin>0) { if (getDownsampleBin()!=currentDownSampleBin) { requireImageGeneration = true; } } final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle rbounds = graph.getRegionArea().getBounds(); if (rbounds.width<1 || rbounds.height<1) return false; if (!imageCreationAllowed) return false; if (monitor!=null && monitor.isCanceled()) return false; if (requireImageGeneration) { try { imageCreationAllowed = false; if (image==null) return false; AbstractDataset reducedFullImage = getDownsampled(image); imageServiceBean.setImage(reducedFullImage); imageServiceBean.setMonitor(monitor); if (fullMask!=null) { imageServiceBean.setMask(getDownsampled(fullMask)); } else { imageServiceBean.setMask(null); // Ensure we lose the mask! } if (rescaleType==ImageScaleType.REHISTOGRAM) { // Avoids changing colouring to // max and min of new selection. AbstractDataset slice = slice(getXAxis().getRange(), getYAxis().getRange(), getData()); ImageServiceBean histoBean = new ImageServiceBean(slice, getHistoType()); if (fullMask!=null) histoBean.setMask(slice(getXAxis().getRange(), getYAxis().getRange(), fullMask)); float[] fa = service.getFastStatistics(histoBean); // Not sure how to deal with this better, but if the bean is logged, then you need to modify the values if (imageServiceBean.isLogColorScale()) { setMin(Math.log10(fa[0])); setMax(Math.log10(fa[1])); } else { setMin(fa[0]); setMax(fa[1]); } } this.imageData = service.getImageData(imageServiceBean); } catch (Exception e) { logger.error("Cannot create image from data!", e); } finally { imageCreationAllowed = true; } } if (monitor!=null && monitor.isCanceled()) return false; try { isMaximumZoom = false; if (imageData!=null && imageData.width==bounds.width && imageData.height==bounds.height) { // No slice, faster if (monitor!=null && monitor.isCanceled()) return false; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = new Image(Display.getDefault(), imageData); } else { // slice data to get current zoom area /** * x1,y1--------------x2,y2 * | | * | | * | | * x3,y3--------------x4,y4 */ ImageData data = imageData; ImageOrigin origin = getImageOrigin(); Range xRange = xAxis.getRange(); Range yRange = yAxis.getRange(); double minX = xRange.getLower()/currentDownSampleBin; double minY = yRange.getLower()/currentDownSampleBin; double maxX = xRange.getUpper()/currentDownSampleBin; double maxY = yRange.getUpper()/currentDownSampleBin; int xSize = imageData.width/currentDownSampleBin; int ySize = imageData.height/currentDownSampleBin; // check as getLower and getUpper don't work as expected if(maxX < minX){ double temp = maxX; maxX = minX; minX = temp; } if(maxY < minY){ double temp = maxY; maxY = minY; minY = temp; } double xSpread = maxX - minX; double ySpread = maxY - minY; double xScale = rbounds.width / xSpread; double yScale = rbounds.height / ySpread; // System.err.println("Area is " + rbounds + " with scale (x,y) " + xScale + ", " + yScale); // Deliberately get the over-sized dimensions so that the edge pixels can be smoothly panned through. int minXI = (int) Math.floor(minX); int minYI = (int) Math.floor(minY); int maxXI = (int) Math.ceil(maxX); int maxYI = (int) Math.ceil(maxY); int fullWidth = (int) (maxXI-minXI); int fullHeight = (int) (maxYI-minYI); // Force a minimum size on the system if (fullWidth <= MINIMUM_ZOOM_SIZE) { if (fullWidth > imageData.width) fullWidth = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } if (fullHeight <= MINIMUM_ZOOM_SIZE) { if (fullHeight > imageData.height) fullHeight = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } int scaleWidth = (int) (fullWidth*xScale); int scaleHeight = (int) (fullHeight*yScale); // System.err.println("Scaling to " + scaleWidth + "x" + scaleHeight); int xPix = (int)minX; int yPix = (int)minY; double xPixD = 0; double yPixD = 0; // These offsets are used when the scaled images is drawn to the screen. xOffset = (minX - Math.floor(minX))*xScale; yOffset = (minY - Math.floor(minY))*yScale; // Deal with the origin orientations correctly. switch (origin) { case TOP_LEFT: break; case TOP_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; break; case BOTTOM_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; case BOTTOM_LEFT: yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; } if (imageData.depth <= 8) { // Slice the data. // Pixel slice on downsampled data = fast! // NOTE Assumes 8-bit images final int size = fullWidth*fullHeight; final byte[] pixels = new byte[size]; for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, fullWidth*y); } data = new ImageData(fullWidth, fullHeight, data.depth, getPaletteData(), 1, pixels); } else { // Slice the data. // Pixel slice on downsampled data = fast! // NOTE Assumes 24 Bit Images final int[] pixels = new int[fullWidth]; data = new ImageData(fullWidth, fullHeight, 24, new PaletteData(0xff0000, 0x00ff00, 0x0000ff)); for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, 0); data.setPixels(0, y, fullWidth, pixels, 0); } } // create the scaled image data = data!=null ? data.scaledTo(scaleWidth, scaleHeight) : null; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } return true; } catch (NullPointerException ne) { throw ne; } catch (Throwable ne) { logger.error("Image scale error!", ne); return false; } }
private boolean createScaledImage(ImageScaleType rescaleType, final IProgressMonitor monitor) { if (!imageCreationAllowed) return false; boolean requireImageGeneration = imageData==null || rescaleType==ImageScaleType.FORCE_REIMAGE || rescaleType==ImageScaleType.REHISTOGRAM; // We know that it is needed // If we just changed downsample scale, we force the update. // This allows user resizes of the plot area to be picked up // and the larger data size used if it fits. if (!requireImageGeneration && rescaleType==ImageScaleType.REIMAGE_ALLOWED && currentDownSampleBin>0) { if (getDownsampleBin()!=currentDownSampleBin) { requireImageGeneration = true; } } final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle rbounds = graph.getRegionArea().getBounds(); if (rbounds.width<1 || rbounds.height<1) return false; if (!imageCreationAllowed) return false; if (monitor!=null && monitor.isCanceled()) return false; if (requireImageGeneration) { try { imageCreationAllowed = false; if (image==null) return false; AbstractDataset reducedFullImage = getDownsampled(image); imageServiceBean.setImage(reducedFullImage); imageServiceBean.setMonitor(monitor); if (fullMask!=null) { imageServiceBean.setMask(getDownsampled(fullMask)); } else { imageServiceBean.setMask(null); // Ensure we lose the mask! } if (rescaleType==ImageScaleType.REHISTOGRAM) { // Avoids changing colouring to // max and min of new selection. AbstractDataset slice = slice(getXAxis().getRange(), getYAxis().getRange(), getData()); ImageServiceBean histoBean = new ImageServiceBean(slice, getHistoType()); if (fullMask!=null) histoBean.setMask(slice(getXAxis().getRange(), getYAxis().getRange(), fullMask)); float[] fa = service.getFastStatistics(histoBean); // Not sure how to deal with this better, but if the bean is logged, then you need to modify the values if (imageServiceBean.isLogColorScale()) { setMin(Math.log10(fa[0])); setMax(Math.log10(fa[1])); } else { setMin(fa[0]); setMax(fa[1]); } } this.imageData = service.getImageData(imageServiceBean); } catch (Exception e) { logger.error("Cannot create image from data!", e); } finally { imageCreationAllowed = true; } } if (monitor!=null && monitor.isCanceled()) return false; try { isMaximumZoom = false; if (imageData!=null && imageData.width==bounds.width && imageData.height==bounds.height) { // No slice, faster if (monitor!=null && monitor.isCanceled()) return false; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = new Image(Display.getDefault(), imageData); } else { // slice data to get current zoom area /** * x1,y1--------------x2,y2 * | | * | | * | | * x3,y3--------------x4,y4 */ ImageData data = imageData; ImageOrigin origin = getImageOrigin(); Range xRange = xAxis.getRange(); Range yRange = yAxis.getRange(); double minX = xRange.getLower()/currentDownSampleBin; double minY = yRange.getLower()/currentDownSampleBin; double maxX = xRange.getUpper()/currentDownSampleBin; double maxY = yRange.getUpper()/currentDownSampleBin; int xSize = imageData.width; int ySize = imageData.height; // check as getLower and getUpper don't work as expected if(maxX < minX){ double temp = maxX; maxX = minX; minX = temp; } if(maxY < minY){ double temp = maxY; maxY = minY; minY = temp; } double xSpread = maxX - minX; double ySpread = maxY - minY; double xScale = rbounds.width / xSpread; double yScale = rbounds.height / ySpread; // System.err.println("Area is " + rbounds + " with scale (x,y) " + xScale + ", " + yScale); // Deliberately get the over-sized dimensions so that the edge pixels can be smoothly panned through. int minXI = (int) Math.floor(minX); int minYI = (int) Math.floor(minY); int maxXI = (int) Math.ceil(maxX); int maxYI = (int) Math.ceil(maxY); int fullWidth = (int) (maxXI-minXI); int fullHeight = (int) (maxYI-minYI); // Force a minimum size on the system if (fullWidth <= MINIMUM_ZOOM_SIZE) { if (fullWidth > imageData.width) fullWidth = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } if (fullHeight <= MINIMUM_ZOOM_SIZE) { if (fullHeight > imageData.height) fullHeight = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } int scaleWidth = (int) (fullWidth*xScale); int scaleHeight = (int) (fullHeight*yScale); // System.err.println("Scaling to " + scaleWidth + "x" + scaleHeight); int xPix = (int)minX; int yPix = (int)minY; double xPixD = 0; double yPixD = 0; // These offsets are used when the scaled images is drawn to the screen. xOffset = (minX - Math.floor(minX))*xScale; yOffset = (minY - Math.floor(minY))*yScale; // Deal with the origin orientations correctly. switch (origin) { case TOP_LEFT: break; case TOP_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; break; case BOTTOM_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; case BOTTOM_LEFT: yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; } // Slice the data. // Pixel slice on downsampled data = fast! if (imageData.depth <= 8) { // NOTE Assumes 8-bit images final int size = fullWidth*fullHeight; final byte[] pixels = new byte[size]; for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, fullWidth*y); } data = new ImageData(fullWidth, fullHeight, data.depth, getPaletteData(), 1, pixels); } else { // NOTE Assumes 24 Bit Images final int[] pixels = new int[fullWidth]; data = new ImageData(fullWidth, fullHeight, 24, new PaletteData(0xff0000, 0x00ff00, 0x0000ff)); for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, 0); data.setPixels(0, y, fullWidth, pixels, 0); } } // create the scaled image data = data!=null ? data.scaledTo(scaleWidth, scaleHeight) : null; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } return true; } catch (NullPointerException ne) { throw ne; } catch (Throwable ne) { logger.error("Image scale error!", ne); return false; } }
diff --git a/common/cpw/mods/fml/relauncher/RelaunchLibraryManager.java b/common/cpw/mods/fml/relauncher/RelaunchLibraryManager.java index 9346c563..3ed09f91 100644 --- a/common/cpw/mods/fml/relauncher/RelaunchLibraryManager.java +++ b/common/cpw/mods/fml/relauncher/RelaunchLibraryManager.java @@ -1,274 +1,274 @@ package cpw.mods.fml.relauncher; import java.awt.HeadlessException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.MappedByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.FileChannel.MapMode; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.ProgressMonitorInputStream; import cpw.mods.fml.common.discovery.ModCandidate; public class RelaunchLibraryManager { private static String[] plugins = { "cpw.mods.fml.relauncher.FMLCorePlugin" , "net.minecraftforge.classloading.FMLForgePlugin" }; private static final String HEXES = "0123456789abcdef"; private static List<String> loadedLibraries = new ArrayList<String>(); public static void handleLaunch(File mcDir, RelaunchClassLoader actualClassLoader) { List<IFMLLoadingPlugin> loadPlugins = new ArrayList<IFMLLoadingPlugin>(); List<ILibrarySet> libraries = new ArrayList<ILibrarySet>(); for (String s : plugins) { try { IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) Class.forName(s, true, actualClassLoader).newInstance(); loadPlugins.add(plugin); for (String libName : plugin.getLibraryRequestClass()) { libraries.add((ILibrarySet) Class.forName(libName, true, actualClassLoader).newInstance()); } } catch (Exception e) { // HMMM } } if (loadPlugins.isEmpty()) { throw new RuntimeException("A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation."); } List<Throwable> caughtErrors = new ArrayList<Throwable>(); try { File libDir; try { libDir = setupLibDir(mcDir); } catch (Exception e) { caughtErrors.add(e); return; } for (ILibrarySet lib : libraries) { for (int i=0; i<lib.getLibraries().length; i++) { boolean download = false; String libName = lib.getLibraries()[i]; String checksum = lib.getHashes()[i]; File libFile = new File(libDir, libName); if (!libFile.exists()) { try { downloadFile(libFile, lib.getRootURL()); download = true; } catch (Throwable e) { caughtErrors.add(e); continue; } } if (libFile.exists() && !libFile.isFile()) { caughtErrors.add(new RuntimeException(String.format("Found a file %s that is not a normal file - you should clear this out of the way", libName))); continue; } String fileChecksum = generateChecksum(libFile); // bad checksum and I did not download this file if (!checksum.equals(fileChecksum) && !download) { caughtErrors.add(new RuntimeException(String.format("The file %s was found in your lib directory and has an invalid checksum %s (expecting %s) - it is unlikely to be the correct download, please move it out of the way and try again.", libName, fileChecksum, checksum))); continue; } // bad checksum but file was downloaded this session else if (!checksum.equals(fileChecksum)) { caughtErrors.add(new RuntimeException(String.format("The downloaded file %s has an invalid checksum %s (expecting %s). The download did not succeed correctly and the file has been deleted. Please try launching again.", libName, fileChecksum, checksum))); libFile.delete(); continue; } if (!download) { - System.out.printf("Found library file %s present and correct in lib dir", libName); + System.out.printf("Found library file %s present and correct in lib dir\n", libName); } else { - System.out.printf("Library file %s was downloaded and verified successfully", libName); + System.out.printf("Library file %s was downloaded and verified successfully\n", libName); } try { actualClassLoader.addURL(libFile.toURI().toURL()); loadedLibraries.add(libName); } catch (MalformedURLException e) { caughtErrors.add(new RuntimeException(String.format("Should never happen - %s is broken - probably a somehow corrupted download. Delete it and try again.", libFile.getName()), e)); } } } } finally { if (!caughtErrors.isEmpty()) { FMLLog.severe("There were errors during initial FML setup. " + "Some files failed to download or were otherwise corrupted. " + "You will need to manually obtain the following files from " + "these download links and ensure your lib directory is clean. "); for (ILibrarySet set : libraries) { for (String file : set.getLibraries()) { FMLLog.severe("*** Download "+set.getRootURL(), file); } } FMLLog.severe("<===========>"); FMLLog.severe("The following is the errors that caused the setup to fail. " + "They may help you diagnose and resolve the issue"); for (Throwable t : caughtErrors) { FMLLog.severe(t.getMessage()); } FMLLog.severe("<<< ==== >>>"); FMLLog.severe("The following is diagnostic information for developers to review."); for (Throwable t : caughtErrors) { FMLLog.log(Level.SEVERE, t, "Error details"); } throw new RuntimeException("A fatal error occured and FML cannot continue"); } } for (IFMLLoadingPlugin plug : loadPlugins) { for (String xformClass : plug.getASMTransformerClass()) { actualClassLoader.registerTransformer(xformClass); } } try { Class<?> loaderClazz = Class.forName("cpw.mods.fml.common.Loader", true, actualClassLoader); } catch (Exception e) { // Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here throw new RuntimeException(e); } } /** * @param mcDir * @return */ private static File setupLibDir(File mcDir) { File libDir = new File(mcDir,"lib"); try { libDir = libDir.getCanonicalFile(); } catch (IOException e) { throw new RuntimeException(String.format("Unable to canonicalize the lib dir at %s", mcDir.getName()),e); } if (!libDir.exists()) { libDir.mkdir(); } else if (libDir.exists() && !libDir.isDirectory()) { throw new RuntimeException(String.format("Found a lib file in %s that's not a directory", mcDir.getName())); } return libDir; } private static String generateChecksum(File file) { try { FileInputStream fis = new FileInputStream(file); FileChannel chan = fis.getChannel(); MessageDigest digest = MessageDigest.getInstance("SHA-1"); MappedByteBuffer mappedFile = chan.map(MapMode.READ_ONLY, 0, file.length()); digest.update(mappedFile); chan.close(); fis.close(); byte[] chksum = digest.digest(); final StringBuilder hex = new StringBuilder( 2 * chksum.length ); for ( final byte b : chksum ) { hex.append(HEXES.charAt((b & 0xF0) >> 4)) .append(HEXES.charAt((b & 0x0F))); } return hex.toString(); } catch (Exception e) { return null; } } private static void downloadFile(File libFile, String rootUrl) { try { URL libDownload = new URL(String.format(rootUrl,libFile.getName())); String infoString = String.format("Downloading file %s", libDownload.toString()); FMLLog.info(infoString); InputStream urlStream = libDownload.openStream(); urlStream = FMLEmbeddingRelauncher.instance().wrapStream(urlStream, infoString); ReadableByteChannel urlChannel = Channels.newChannel(urlStream); FileOutputStream libFileStream = new FileOutputStream(libFile); FileChannel libFileChannel = libFileStream.getChannel(); libFileChannel.transferFrom(urlChannel, 0, 1<<24); libFileChannel.close(); libFileStream.close(); urlChannel.close(); urlStream.close(); FMLLog.info("Download complete"); } catch (Exception e) { FMLLog.severe("There was a problem downloading the file %s automatically. Perhaps you" + "have an environment without internet access. You will need to download " + "the file manually\n", libFile.getName()); libFile.delete(); throw new RuntimeException("A download error occured", e); } } public static List<String> getLibraries() { return loadedLibraries; } }
false
true
public static void handleLaunch(File mcDir, RelaunchClassLoader actualClassLoader) { List<IFMLLoadingPlugin> loadPlugins = new ArrayList<IFMLLoadingPlugin>(); List<ILibrarySet> libraries = new ArrayList<ILibrarySet>(); for (String s : plugins) { try { IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) Class.forName(s, true, actualClassLoader).newInstance(); loadPlugins.add(plugin); for (String libName : plugin.getLibraryRequestClass()) { libraries.add((ILibrarySet) Class.forName(libName, true, actualClassLoader).newInstance()); } } catch (Exception e) { // HMMM } } if (loadPlugins.isEmpty()) { throw new RuntimeException("A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation."); } List<Throwable> caughtErrors = new ArrayList<Throwable>(); try { File libDir; try { libDir = setupLibDir(mcDir); } catch (Exception e) { caughtErrors.add(e); return; } for (ILibrarySet lib : libraries) { for (int i=0; i<lib.getLibraries().length; i++) { boolean download = false; String libName = lib.getLibraries()[i]; String checksum = lib.getHashes()[i]; File libFile = new File(libDir, libName); if (!libFile.exists()) { try { downloadFile(libFile, lib.getRootURL()); download = true; } catch (Throwable e) { caughtErrors.add(e); continue; } } if (libFile.exists() && !libFile.isFile()) { caughtErrors.add(new RuntimeException(String.format("Found a file %s that is not a normal file - you should clear this out of the way", libName))); continue; } String fileChecksum = generateChecksum(libFile); // bad checksum and I did not download this file if (!checksum.equals(fileChecksum) && !download) { caughtErrors.add(new RuntimeException(String.format("The file %s was found in your lib directory and has an invalid checksum %s (expecting %s) - it is unlikely to be the correct download, please move it out of the way and try again.", libName, fileChecksum, checksum))); continue; } // bad checksum but file was downloaded this session else if (!checksum.equals(fileChecksum)) { caughtErrors.add(new RuntimeException(String.format("The downloaded file %s has an invalid checksum %s (expecting %s). The download did not succeed correctly and the file has been deleted. Please try launching again.", libName, fileChecksum, checksum))); libFile.delete(); continue; } if (!download) { System.out.printf("Found library file %s present and correct in lib dir", libName); } else { System.out.printf("Library file %s was downloaded and verified successfully", libName); } try { actualClassLoader.addURL(libFile.toURI().toURL()); loadedLibraries.add(libName); } catch (MalformedURLException e) { caughtErrors.add(new RuntimeException(String.format("Should never happen - %s is broken - probably a somehow corrupted download. Delete it and try again.", libFile.getName()), e)); } } } } finally { if (!caughtErrors.isEmpty()) { FMLLog.severe("There were errors during initial FML setup. " + "Some files failed to download or were otherwise corrupted. " + "You will need to manually obtain the following files from " + "these download links and ensure your lib directory is clean. "); for (ILibrarySet set : libraries) { for (String file : set.getLibraries()) { FMLLog.severe("*** Download "+set.getRootURL(), file); } } FMLLog.severe("<===========>"); FMLLog.severe("The following is the errors that caused the setup to fail. " + "They may help you diagnose and resolve the issue"); for (Throwable t : caughtErrors) { FMLLog.severe(t.getMessage()); } FMLLog.severe("<<< ==== >>>"); FMLLog.severe("The following is diagnostic information for developers to review."); for (Throwable t : caughtErrors) { FMLLog.log(Level.SEVERE, t, "Error details"); } throw new RuntimeException("A fatal error occured and FML cannot continue"); } } for (IFMLLoadingPlugin plug : loadPlugins) { for (String xformClass : plug.getASMTransformerClass()) { actualClassLoader.registerTransformer(xformClass); } } try { Class<?> loaderClazz = Class.forName("cpw.mods.fml.common.Loader", true, actualClassLoader); } catch (Exception e) { // Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here throw new RuntimeException(e); } }
public static void handleLaunch(File mcDir, RelaunchClassLoader actualClassLoader) { List<IFMLLoadingPlugin> loadPlugins = new ArrayList<IFMLLoadingPlugin>(); List<ILibrarySet> libraries = new ArrayList<ILibrarySet>(); for (String s : plugins) { try { IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) Class.forName(s, true, actualClassLoader).newInstance(); loadPlugins.add(plugin); for (String libName : plugin.getLibraryRequestClass()) { libraries.add((ILibrarySet) Class.forName(libName, true, actualClassLoader).newInstance()); } } catch (Exception e) { // HMMM } } if (loadPlugins.isEmpty()) { throw new RuntimeException("A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation."); } List<Throwable> caughtErrors = new ArrayList<Throwable>(); try { File libDir; try { libDir = setupLibDir(mcDir); } catch (Exception e) { caughtErrors.add(e); return; } for (ILibrarySet lib : libraries) { for (int i=0; i<lib.getLibraries().length; i++) { boolean download = false; String libName = lib.getLibraries()[i]; String checksum = lib.getHashes()[i]; File libFile = new File(libDir, libName); if (!libFile.exists()) { try { downloadFile(libFile, lib.getRootURL()); download = true; } catch (Throwable e) { caughtErrors.add(e); continue; } } if (libFile.exists() && !libFile.isFile()) { caughtErrors.add(new RuntimeException(String.format("Found a file %s that is not a normal file - you should clear this out of the way", libName))); continue; } String fileChecksum = generateChecksum(libFile); // bad checksum and I did not download this file if (!checksum.equals(fileChecksum) && !download) { caughtErrors.add(new RuntimeException(String.format("The file %s was found in your lib directory and has an invalid checksum %s (expecting %s) - it is unlikely to be the correct download, please move it out of the way and try again.", libName, fileChecksum, checksum))); continue; } // bad checksum but file was downloaded this session else if (!checksum.equals(fileChecksum)) { caughtErrors.add(new RuntimeException(String.format("The downloaded file %s has an invalid checksum %s (expecting %s). The download did not succeed correctly and the file has been deleted. Please try launching again.", libName, fileChecksum, checksum))); libFile.delete(); continue; } if (!download) { System.out.printf("Found library file %s present and correct in lib dir\n", libName); } else { System.out.printf("Library file %s was downloaded and verified successfully\n", libName); } try { actualClassLoader.addURL(libFile.toURI().toURL()); loadedLibraries.add(libName); } catch (MalformedURLException e) { caughtErrors.add(new RuntimeException(String.format("Should never happen - %s is broken - probably a somehow corrupted download. Delete it and try again.", libFile.getName()), e)); } } } } finally { if (!caughtErrors.isEmpty()) { FMLLog.severe("There were errors during initial FML setup. " + "Some files failed to download or were otherwise corrupted. " + "You will need to manually obtain the following files from " + "these download links and ensure your lib directory is clean. "); for (ILibrarySet set : libraries) { for (String file : set.getLibraries()) { FMLLog.severe("*** Download "+set.getRootURL(), file); } } FMLLog.severe("<===========>"); FMLLog.severe("The following is the errors that caused the setup to fail. " + "They may help you diagnose and resolve the issue"); for (Throwable t : caughtErrors) { FMLLog.severe(t.getMessage()); } FMLLog.severe("<<< ==== >>>"); FMLLog.severe("The following is diagnostic information for developers to review."); for (Throwable t : caughtErrors) { FMLLog.log(Level.SEVERE, t, "Error details"); } throw new RuntimeException("A fatal error occured and FML cannot continue"); } } for (IFMLLoadingPlugin plug : loadPlugins) { for (String xformClass : plug.getASMTransformerClass()) { actualClassLoader.registerTransformer(xformClass); } } try { Class<?> loaderClazz = Class.forName("cpw.mods.fml.common.Loader", true, actualClassLoader); } catch (Exception e) { // Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here throw new RuntimeException(e); } }
diff --git a/src/com/android/mms/transaction/MmsSystemEventReceiver.java b/src/com/android/mms/transaction/MmsSystemEventReceiver.java index e152b3a7..92511338 100644 --- a/src/com/android/mms/transaction/MmsSystemEventReceiver.java +++ b/src/com/android/mms/transaction/MmsSystemEventReceiver.java @@ -1,102 +1,105 @@ /* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.transaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.provider.Telephony.Mms; import android.util.Log; import com.android.mms.LogTag; import com.android.mms.MmsApp; /** * MmsSystemEventReceiver receives the * {@link android.content.intent.ACTION_BOOT_COMPLETED}, * {@link com.android.internal.telephony.TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED} * and performs a series of operations which may include: * <ul> * <li>Show/hide the icon in notification area which is used to indicate * whether there is new incoming message.</li> * <li>Resend the MM's in the outbox.</li> * </ul> */ public class MmsSystemEventReceiver extends BroadcastReceiver { private static final String TAG = "MmsSystemEventReceiver"; private static ConnectivityManager mConnMgr = null; public static void wakeUpService(Context context) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "wakeUpService: start transaction service ..."); } context.startService(new Intent(context, TransactionService.class)); } @Override public void onReceive(Context context, Intent intent) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "Intent received: " + intent); } String action = intent.getAction(); if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) { Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS); MmsApp.getApplication().getPduLoaderManager().removePdu(changed); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (mConnMgr == null) { mConnMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); } if (!mConnMgr.getMobileDataEnabled()) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "mobile data turned off, bailing"); } return; } NetworkInfo mmsNetworkInfo = mConnMgr .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS); - boolean available = mmsNetworkInfo.isAvailable(); - boolean isConnected = mmsNetworkInfo.isConnected(); + if (mmsNetworkInfo!=null) + { + boolean available = mmsNetworkInfo.isAvailable(); + boolean isConnected = mmsNetworkInfo.isConnected(); - if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { - Log.v(TAG, "TYPE_MOBILE_MMS available = " + available + + if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { + Log.v(TAG, "TYPE_MOBILE_MMS available = " + available + ", isConnected = " + isConnected); - } + } - // Wake up transact service when MMS data is available and isn't connected. - if (available && !isConnected) { - wakeUpService(context); + // Wake up transact service when MMS data is available and isn't connected. + if (available && !isConnected) { + wakeUpService(context); + } } } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // We should check whether there are unread incoming // messages in the Inbox and then update the notification icon. // Called on the UI thread so don't block. MessagingNotification.nonBlockingUpdateNewMessageIndicator( context, MessagingNotification.THREAD_NONE, false); // Scan and send pending Mms once after boot completed since // ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle wakeUpService(context); } } }
false
true
public void onReceive(Context context, Intent intent) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "Intent received: " + intent); } String action = intent.getAction(); if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) { Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS); MmsApp.getApplication().getPduLoaderManager().removePdu(changed); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (mConnMgr == null) { mConnMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); } if (!mConnMgr.getMobileDataEnabled()) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "mobile data turned off, bailing"); } return; } NetworkInfo mmsNetworkInfo = mConnMgr .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS); boolean available = mmsNetworkInfo.isAvailable(); boolean isConnected = mmsNetworkInfo.isConnected(); if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "TYPE_MOBILE_MMS available = " + available + ", isConnected = " + isConnected); } // Wake up transact service when MMS data is available and isn't connected. if (available && !isConnected) { wakeUpService(context); } } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // We should check whether there are unread incoming // messages in the Inbox and then update the notification icon. // Called on the UI thread so don't block. MessagingNotification.nonBlockingUpdateNewMessageIndicator( context, MessagingNotification.THREAD_NONE, false); // Scan and send pending Mms once after boot completed since // ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle wakeUpService(context); } }
public void onReceive(Context context, Intent intent) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "Intent received: " + intent); } String action = intent.getAction(); if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) { Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS); MmsApp.getApplication().getPduLoaderManager().removePdu(changed); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (mConnMgr == null) { mConnMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); } if (!mConnMgr.getMobileDataEnabled()) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "mobile data turned off, bailing"); } return; } NetworkInfo mmsNetworkInfo = mConnMgr .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS); if (mmsNetworkInfo!=null) { boolean available = mmsNetworkInfo.isAvailable(); boolean isConnected = mmsNetworkInfo.isConnected(); if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "TYPE_MOBILE_MMS available = " + available + ", isConnected = " + isConnected); } // Wake up transact service when MMS data is available and isn't connected. if (available && !isConnected) { wakeUpService(context); } } } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // We should check whether there are unread incoming // messages in the Inbox and then update the notification icon. // Called on the UI thread so don't block. MessagingNotification.nonBlockingUpdateNewMessageIndicator( context, MessagingNotification.THREAD_NONE, false); // Scan and send pending Mms once after boot completed since // ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle wakeUpService(context); } }
diff --git a/plugins/net.bioclipse.brunn.ui/src/net/bioclipse/brunn/ui/dialogs/CreatePatientCell.java b/plugins/net.bioclipse.brunn.ui/src/net/bioclipse/brunn/ui/dialogs/CreatePatientCell.java index a99b532..846870f 100644 --- a/plugins/net.bioclipse.brunn.ui/src/net/bioclipse/brunn/ui/dialogs/CreatePatientCell.java +++ b/plugins/net.bioclipse.brunn.ui/src/net/bioclipse/brunn/ui/dialogs/CreatePatientCell.java @@ -1,123 +1,123 @@ package net.bioclipse.brunn.ui.dialogs; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class CreatePatientCell extends TitleAreaDialog { private Text lidText; private Text nameText; private String name; private String lid; /** * Create the dialog * @param parentShell */ public CreatePatientCell(Shell parentShell) { super(parentShell); } /** * Create contents of the dialog * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayout(new FormLayout()); container.setLayoutData(new GridData(GridData.FILL_BOTH)); final Label label = new Label(container, SWT.NONE); final FormData fd_label = new FormData(); fd_label.right = new FormAttachment(0, 109); label.setLayoutData(fd_label); label.setText("Name:"); nameText = new Text(container, SWT.BORDER); fd_label.bottom = new FormAttachment(nameText, -2, SWT.BOTTOM); final FormData fd_nameText = new FormData(); fd_nameText.right = new FormAttachment(100, -119); fd_nameText.top = new FormAttachment(0, 36); fd_nameText.left = new FormAttachment(0, 115); nameText.setLayoutData(fd_nameText); lidText = new Text(container, SWT.BORDER); final FormData fd_lid = new FormData(); fd_lid.right = new FormAttachment(nameText, 0, SWT.RIGHT); fd_lid.top = new FormAttachment(0, 76); fd_lid.left = new FormAttachment(0, 115); lidText.setLayoutData(fd_lid); final Label lidLabel = new Label(container, SWT.NONE); final FormData fd_lidLabel = new FormData(); fd_lidLabel.bottom = new FormAttachment(lidText, -2, SWT.BOTTOM); fd_lidLabel.right = new FormAttachment(0, 109); lidLabel.setLayoutData(fd_lidLabel); lidLabel.setText("lid:"); final Label eg08045Label = new Label(container, SWT.NONE); final FormData fd_eg08045Label = new FormData(); fd_eg08045Label.bottom = new FormAttachment(nameText, 0, SWT.BOTTOM); fd_eg08045Label.left = new FormAttachment(nameText, 5, SWT.RIGHT); eg08045Label.setLayoutData(fd_eg08045Label); - eg08045Label.setText("(e.g. 08/045-A)"); + eg08045Label.setText("(e.g. 08/045-B)"); final Label eg08045Label_1 = new Label(container, SWT.NONE); final FormData fd_eg08045Label_1 = new FormData(); fd_eg08045Label_1.bottom = new FormAttachment(lidText, 0, SWT.BOTTOM); fd_eg08045Label_1.left = new FormAttachment(lidText, 5, SWT.RIGHT); eg08045Label_1.setLayoutData(fd_eg08045Label_1); eg08045Label_1.setText("(e.g. 08/045)"); setTitle("Create Patient Cell"); // return area; } /** * Create contents of the button bar * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog */ @Override protected Point getInitialSize() { return new Point(452, 349); } protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.OK_ID) { name = nameText.getText(); lid = lidText.getText(); } super.buttonPressed(buttonId); } public String getName() { return name; } public String getLid() { return lid; } }
true
true
protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayout(new FormLayout()); container.setLayoutData(new GridData(GridData.FILL_BOTH)); final Label label = new Label(container, SWT.NONE); final FormData fd_label = new FormData(); fd_label.right = new FormAttachment(0, 109); label.setLayoutData(fd_label); label.setText("Name:"); nameText = new Text(container, SWT.BORDER); fd_label.bottom = new FormAttachment(nameText, -2, SWT.BOTTOM); final FormData fd_nameText = new FormData(); fd_nameText.right = new FormAttachment(100, -119); fd_nameText.top = new FormAttachment(0, 36); fd_nameText.left = new FormAttachment(0, 115); nameText.setLayoutData(fd_nameText); lidText = new Text(container, SWT.BORDER); final FormData fd_lid = new FormData(); fd_lid.right = new FormAttachment(nameText, 0, SWT.RIGHT); fd_lid.top = new FormAttachment(0, 76); fd_lid.left = new FormAttachment(0, 115); lidText.setLayoutData(fd_lid); final Label lidLabel = new Label(container, SWT.NONE); final FormData fd_lidLabel = new FormData(); fd_lidLabel.bottom = new FormAttachment(lidText, -2, SWT.BOTTOM); fd_lidLabel.right = new FormAttachment(0, 109); lidLabel.setLayoutData(fd_lidLabel); lidLabel.setText("lid:"); final Label eg08045Label = new Label(container, SWT.NONE); final FormData fd_eg08045Label = new FormData(); fd_eg08045Label.bottom = new FormAttachment(nameText, 0, SWT.BOTTOM); fd_eg08045Label.left = new FormAttachment(nameText, 5, SWT.RIGHT); eg08045Label.setLayoutData(fd_eg08045Label); eg08045Label.setText("(e.g. 08/045-A)"); final Label eg08045Label_1 = new Label(container, SWT.NONE); final FormData fd_eg08045Label_1 = new FormData(); fd_eg08045Label_1.bottom = new FormAttachment(lidText, 0, SWT.BOTTOM); fd_eg08045Label_1.left = new FormAttachment(lidText, 5, SWT.RIGHT); eg08045Label_1.setLayoutData(fd_eg08045Label_1); eg08045Label_1.setText("(e.g. 08/045)"); setTitle("Create Patient Cell"); // return area; }
protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayout(new FormLayout()); container.setLayoutData(new GridData(GridData.FILL_BOTH)); final Label label = new Label(container, SWT.NONE); final FormData fd_label = new FormData(); fd_label.right = new FormAttachment(0, 109); label.setLayoutData(fd_label); label.setText("Name:"); nameText = new Text(container, SWT.BORDER); fd_label.bottom = new FormAttachment(nameText, -2, SWT.BOTTOM); final FormData fd_nameText = new FormData(); fd_nameText.right = new FormAttachment(100, -119); fd_nameText.top = new FormAttachment(0, 36); fd_nameText.left = new FormAttachment(0, 115); nameText.setLayoutData(fd_nameText); lidText = new Text(container, SWT.BORDER); final FormData fd_lid = new FormData(); fd_lid.right = new FormAttachment(nameText, 0, SWT.RIGHT); fd_lid.top = new FormAttachment(0, 76); fd_lid.left = new FormAttachment(0, 115); lidText.setLayoutData(fd_lid); final Label lidLabel = new Label(container, SWT.NONE); final FormData fd_lidLabel = new FormData(); fd_lidLabel.bottom = new FormAttachment(lidText, -2, SWT.BOTTOM); fd_lidLabel.right = new FormAttachment(0, 109); lidLabel.setLayoutData(fd_lidLabel); lidLabel.setText("lid:"); final Label eg08045Label = new Label(container, SWT.NONE); final FormData fd_eg08045Label = new FormData(); fd_eg08045Label.bottom = new FormAttachment(nameText, 0, SWT.BOTTOM); fd_eg08045Label.left = new FormAttachment(nameText, 5, SWT.RIGHT); eg08045Label.setLayoutData(fd_eg08045Label); eg08045Label.setText("(e.g. 08/045-B)"); final Label eg08045Label_1 = new Label(container, SWT.NONE); final FormData fd_eg08045Label_1 = new FormData(); fd_eg08045Label_1.bottom = new FormAttachment(lidText, 0, SWT.BOTTOM); fd_eg08045Label_1.left = new FormAttachment(lidText, 5, SWT.RIGHT); eg08045Label_1.setLayoutData(fd_eg08045Label_1); eg08045Label_1.setText("(e.g. 08/045)"); setTitle("Create Patient Cell"); // return area; }
diff --git a/Client/src/com/mamehub/client/login/LoginDialog.java b/Client/src/com/mamehub/client/login/LoginDialog.java index 2baa1813..73b7bccf 100644 --- a/Client/src/com/mamehub/client/login/LoginDialog.java +++ b/Client/src/com/mamehub/client/login/LoginDialog.java @@ -1,409 +1,405 @@ package com.mamehub.client.login; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mamehub.client.Main; import com.mamehub.client.MainFrame; import com.mamehub.client.Utils; import com.mamehub.client.login.FacebookLogin.FacebookLoginCallback; import com.mamehub.client.login.GoogleLogin.GoogleLoginCallback; import com.mamehub.client.net.RpcEngine; import com.mamehub.client.server.ClientHttpServer; import com.mamehub.client.server.UDPReflectionServer; import com.mamehub.client.utility.OSValidator; import com.mamehub.thrift.ApplicationSettings; import com.mamehub.thrift.Player; public class LoginDialog extends JFrame implements FacebookLoginCallback, GoogleLoginCallback { private static final long serialVersionUID = 1L; final Logger logger = LoggerFactory.getLogger(LoginDialog.class); private final JPanel contentPanel = new JPanel(); private JLabel lblWelcomeToMamehub; private JButton facebookLoginButton; public boolean loggingIn=false; protected FacebookLogin facebookLogin; protected GoogleLogin googleLogin; protected RpcEngine rpcEngine; private JLabel lblWaitingForAuthorization; private JButton btnCancelLogin; private JLabel errorLabel; private JPanel panel; private JPanel internalAccountPanel; private JLabel lblUserName; private JTextField usernameTextField; private JLabel lblPassword; private JTextField passwordTextField; private JButton manualLoginButton; private JButton newAccountButton; private JLabel lblNewLabel; private JButton googleLoginButton; private UDPReflectionServer udpReflectionServer; private ClientHttpServer clientHttpServer; private JPanel panel_1; private JLabel lblNewLabel_1; private JButton forgotPasswordButton; private JLabel lblOrCreateA; /** * Create the dialog. * @throws IOException */ @SuppressWarnings("restriction") public LoginDialog(ClientHttpServer clientHttpServer) throws IOException { super(); URL u = Utils.getResource(LoginDialog.class, "/MAMEHub.png"); BufferedImage bi = ImageIO.read(u); this.setIconImage(bi); - if(OSValidator.isMac()) { - com.apple.eawt.Application macApp = com.apple.eawt.Application.getApplication(); - macApp.setDockIconImage(bi); - } udpReflectionServer = new UDPReflectionServer(); rpcEngine = new RpcEngine(); logger.info("Adding intro dialog"); Utils.windows.add(this); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent arg0) { logger.info("Got windowClosed for intro dialog"); if(facebookLogin != null) { facebookLogin.giveUp = true; try { facebookLogin.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } logger.info("Removing intro dialog"); Utils.removeWindow(LoginDialog.this); } }); setBounds(100, 100, 400, 400); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); { lblWelcomeToMamehub = new JLabel("Welcome to MAMEHub 2.0!"); lblWelcomeToMamehub.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblWelcomeToMamehub); } { lblNewLabel = new JLabel("Login through Facebook or Google"); lblNewLabel.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblNewLabel); } { panel = new JPanel(); contentPanel.add(panel); { facebookLoginButton = new JButton("Login"); panel.add(facebookLoginButton); facebookLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } if(loggingIn) return; loggingIn = true; try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLoginButton.setVisible(false); googleLoginButton.setVisible(false); internalAccountPanel.setVisible(false); btnCancelLogin.setVisible(true); lblWaitingForAuthorization.setVisible(true); facebookLogin = new FacebookLogin(rpcEngine, LoginDialog.this); facebookLogin.start(); loggingIn = false; } }); facebookLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT); facebookLoginButton.setIcon(new ImageIcon(Utils.getResource(LoginDialog.class, "/images/f_logo_icon.png"))); } { googleLoginButton = new JButton("Login"); googleLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } if(loggingIn) return; loggingIn = true; try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLoginButton.setVisible(false); googleLoginButton.setVisible(false); internalAccountPanel.setVisible(false); btnCancelLogin.setVisible(true); lblWaitingForAuthorization.setVisible(true); googleLogin = new GoogleLogin(rpcEngine, LoginDialog.this); googleLogin.start(); loggingIn = false; } }); googleLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT); googleLoginButton.setIcon(new ImageIcon(Utils.getResource(LoginDialog.class, "/images/g_logo_icon.png"))); panel.add(googleLoginButton); } { lblWaitingForAuthorization = new JLabel("Waiting for authorization..."); panel.add(lblWaitingForAuthorization); lblWaitingForAuthorization.setVisible(false); lblWaitingForAuthorization.setAlignmentX(Component.CENTER_ALIGNMENT); } { btnCancelLogin = new JButton("Cancel Login"); panel.add(btnCancelLogin); btnCancelLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancelLogin(); } }); btnCancelLogin.setVisible(false); btnCancelLogin.setAlignmentX(Component.CENTER_ALIGNMENT); } { errorLabel = new JLabel(""); panel.add(errorLabel); errorLabel.setForeground(Color.RED); } } { newAccountButton = new JButton("Create a New Account"); newAccountButton.setAlignmentX(Component.CENTER_ALIGNMENT); newAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "New Account failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "New Account failed: Your client is out of date, please restart MAMEHub."); return; } try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new NewAccountDialog(LoginDialog.this, rpcEngine).setVisible(true); } }); { lblOrCreateA = new JLabel("Or create a new MAMEHub account"); lblOrCreateA.setAlignmentX(0.5f); contentPanel.add(lblOrCreateA); } contentPanel.add(newAccountButton); } { lblNewLabel_1 = new JLabel("Or Login with an existing MAMEHub account"); lblNewLabel_1.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblNewLabel_1); } { internalAccountPanel = new JPanel(); contentPanel.add(internalAccountPanel); internalAccountPanel.setLayout(new GridLayout(3, 2, 0, 0)); { lblUserName = new JLabel("Username"); internalAccountPanel.add(lblUserName); } { usernameTextField = new JTextField(); internalAccountPanel.add(usernameTextField); usernameTextField.setColumns(10); } { lblPassword = new JLabel("Password"); internalAccountPanel.add(lblPassword); } { passwordTextField = new JPasswordField(); internalAccountPanel.add(passwordTextField); passwordTextField.setColumns(10); } { manualLoginButton = new JButton("Login"); manualLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String errorMessage = rpcEngine.login(usernameTextField.getText(), passwordTextField.getText()); if(errorMessage.length()==0) { ApplicationSettings as = Utils.getApplicationSettings(); as.lastInternalLoginId = usernameTextField.getText(); Utils.putApplicationSettings(as); loginComplete(); } else { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: " + errorMessage); } } }); { panel_1 = new JPanel(); internalAccountPanel.add(panel_1); } internalAccountPanel.add(manualLoginButton); } { forgotPasswordButton = new JButton("Email Password Reminder"); forgotPasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Email Password: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Email Password: Your client is out of date, please restart MAMEHub."); return; } if(manualLoginButton.getText().length()<3) { JOptionPane.showMessageDialog(LoginDialog.this, "Enter a valid email address in the login field."); return; } if(!rpcEngine.emailPassword(manualLoginButton.getText())) { JOptionPane.showMessageDialog(LoginDialog.this, "Email address not found on server (did you make an account yet?)."); return; } else { JOptionPane.showMessageDialog(LoginDialog.this, "Password sent to " + manualLoginButton.getText()); return; } } }); forgotPasswordButton.setAlignmentX(0.5f); contentPanel.add(forgotPasswordButton); } } ApplicationSettings as = Utils.getApplicationSettings(); usernameTextField.setText(as.lastInternalLoginId); } protected void cancelLogin() { internalAccountPanel.setVisible(true); facebookLoginButton.setVisible(true); googleLoginButton.setVisible(true); btnCancelLogin.setVisible(false); lblWaitingForAuthorization.setVisible(false); if(facebookLogin != null) { facebookLogin.giveUp = true; try { facebookLogin.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLogin = null; } loggingIn = false; } void loginComplete() { try { udpReflectionServer.shutdown(); MainFrame mainFrame = new MainFrame(rpcEngine, clientHttpServer); mainFrame.setVisible(true); this.dispose(); Player myself = rpcEngine.getMyself(); if(!myself.portsOpen) { JOptionPane.showMessageDialog(mainFrame, "MAMEHub has detected that you don't have port 6805 open (both TCP & UDP are required).\nAs a result, you cannot play networked games or transfer data with other players.\nSee http://portforward.com/ for details."); } return; } catch (Exception e) { e.printStackTrace(); errorLabel.setText(e.getMessage()); } // If we get here, an exception was thrown cancelLogin(); } @Override public void facebookLoginComplete() { loginComplete(); } @Override public void googleLoginComplete() { loginComplete(); } }
true
true
public LoginDialog(ClientHttpServer clientHttpServer) throws IOException { super(); URL u = Utils.getResource(LoginDialog.class, "/MAMEHub.png"); BufferedImage bi = ImageIO.read(u); this.setIconImage(bi); if(OSValidator.isMac()) { com.apple.eawt.Application macApp = com.apple.eawt.Application.getApplication(); macApp.setDockIconImage(bi); } udpReflectionServer = new UDPReflectionServer(); rpcEngine = new RpcEngine(); logger.info("Adding intro dialog"); Utils.windows.add(this); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent arg0) { logger.info("Got windowClosed for intro dialog"); if(facebookLogin != null) { facebookLogin.giveUp = true; try { facebookLogin.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } logger.info("Removing intro dialog"); Utils.removeWindow(LoginDialog.this); } }); setBounds(100, 100, 400, 400); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); { lblWelcomeToMamehub = new JLabel("Welcome to MAMEHub 2.0!"); lblWelcomeToMamehub.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblWelcomeToMamehub); } { lblNewLabel = new JLabel("Login through Facebook or Google"); lblNewLabel.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblNewLabel); } { panel = new JPanel(); contentPanel.add(panel); { facebookLoginButton = new JButton("Login"); panel.add(facebookLoginButton); facebookLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } if(loggingIn) return; loggingIn = true; try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLoginButton.setVisible(false); googleLoginButton.setVisible(false); internalAccountPanel.setVisible(false); btnCancelLogin.setVisible(true); lblWaitingForAuthorization.setVisible(true); facebookLogin = new FacebookLogin(rpcEngine, LoginDialog.this); facebookLogin.start(); loggingIn = false; } }); facebookLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT); facebookLoginButton.setIcon(new ImageIcon(Utils.getResource(LoginDialog.class, "/images/f_logo_icon.png"))); } { googleLoginButton = new JButton("Login"); googleLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } if(loggingIn) return; loggingIn = true; try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLoginButton.setVisible(false); googleLoginButton.setVisible(false); internalAccountPanel.setVisible(false); btnCancelLogin.setVisible(true); lblWaitingForAuthorization.setVisible(true); googleLogin = new GoogleLogin(rpcEngine, LoginDialog.this); googleLogin.start(); loggingIn = false; } }); googleLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT); googleLoginButton.setIcon(new ImageIcon(Utils.getResource(LoginDialog.class, "/images/g_logo_icon.png"))); panel.add(googleLoginButton); } { lblWaitingForAuthorization = new JLabel("Waiting for authorization..."); panel.add(lblWaitingForAuthorization); lblWaitingForAuthorization.setVisible(false); lblWaitingForAuthorization.setAlignmentX(Component.CENTER_ALIGNMENT); } { btnCancelLogin = new JButton("Cancel Login"); panel.add(btnCancelLogin); btnCancelLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancelLogin(); } }); btnCancelLogin.setVisible(false); btnCancelLogin.setAlignmentX(Component.CENTER_ALIGNMENT); } { errorLabel = new JLabel(""); panel.add(errorLabel); errorLabel.setForeground(Color.RED); } } { newAccountButton = new JButton("Create a New Account"); newAccountButton.setAlignmentX(Component.CENTER_ALIGNMENT); newAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "New Account failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "New Account failed: Your client is out of date, please restart MAMEHub."); return; } try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new NewAccountDialog(LoginDialog.this, rpcEngine).setVisible(true); } }); { lblOrCreateA = new JLabel("Or create a new MAMEHub account"); lblOrCreateA.setAlignmentX(0.5f); contentPanel.add(lblOrCreateA); } contentPanel.add(newAccountButton); } { lblNewLabel_1 = new JLabel("Or Login with an existing MAMEHub account"); lblNewLabel_1.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblNewLabel_1); } { internalAccountPanel = new JPanel(); contentPanel.add(internalAccountPanel); internalAccountPanel.setLayout(new GridLayout(3, 2, 0, 0)); { lblUserName = new JLabel("Username"); internalAccountPanel.add(lblUserName); } { usernameTextField = new JTextField(); internalAccountPanel.add(usernameTextField); usernameTextField.setColumns(10); } { lblPassword = new JLabel("Password"); internalAccountPanel.add(lblPassword); } { passwordTextField = new JPasswordField(); internalAccountPanel.add(passwordTextField); passwordTextField.setColumns(10); } { manualLoginButton = new JButton("Login"); manualLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String errorMessage = rpcEngine.login(usernameTextField.getText(), passwordTextField.getText()); if(errorMessage.length()==0) { ApplicationSettings as = Utils.getApplicationSettings(); as.lastInternalLoginId = usernameTextField.getText(); Utils.putApplicationSettings(as); loginComplete(); } else { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: " + errorMessage); } } }); { panel_1 = new JPanel(); internalAccountPanel.add(panel_1); } internalAccountPanel.add(manualLoginButton); } { forgotPasswordButton = new JButton("Email Password Reminder"); forgotPasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Email Password: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Email Password: Your client is out of date, please restart MAMEHub."); return; } if(manualLoginButton.getText().length()<3) { JOptionPane.showMessageDialog(LoginDialog.this, "Enter a valid email address in the login field."); return; } if(!rpcEngine.emailPassword(manualLoginButton.getText())) { JOptionPane.showMessageDialog(LoginDialog.this, "Email address not found on server (did you make an account yet?)."); return; } else { JOptionPane.showMessageDialog(LoginDialog.this, "Password sent to " + manualLoginButton.getText()); return; } } }); forgotPasswordButton.setAlignmentX(0.5f); contentPanel.add(forgotPasswordButton); } } ApplicationSettings as = Utils.getApplicationSettings(); usernameTextField.setText(as.lastInternalLoginId); }
public LoginDialog(ClientHttpServer clientHttpServer) throws IOException { super(); URL u = Utils.getResource(LoginDialog.class, "/MAMEHub.png"); BufferedImage bi = ImageIO.read(u); this.setIconImage(bi); udpReflectionServer = new UDPReflectionServer(); rpcEngine = new RpcEngine(); logger.info("Adding intro dialog"); Utils.windows.add(this); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent arg0) { logger.info("Got windowClosed for intro dialog"); if(facebookLogin != null) { facebookLogin.giveUp = true; try { facebookLogin.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } logger.info("Removing intro dialog"); Utils.removeWindow(LoginDialog.this); } }); setBounds(100, 100, 400, 400); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); { lblWelcomeToMamehub = new JLabel("Welcome to MAMEHub 2.0!"); lblWelcomeToMamehub.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblWelcomeToMamehub); } { lblNewLabel = new JLabel("Login through Facebook or Google"); lblNewLabel.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblNewLabel); } { panel = new JPanel(); contentPanel.add(panel); { facebookLoginButton = new JButton("Login"); panel.add(facebookLoginButton); facebookLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } if(loggingIn) return; loggingIn = true; try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLoginButton.setVisible(false); googleLoginButton.setVisible(false); internalAccountPanel.setVisible(false); btnCancelLogin.setVisible(true); lblWaitingForAuthorization.setVisible(true); facebookLogin = new FacebookLogin(rpcEngine, LoginDialog.this); facebookLogin.start(); loggingIn = false; } }); facebookLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT); facebookLoginButton.setIcon(new ImageIcon(Utils.getResource(LoginDialog.class, "/images/f_logo_icon.png"))); } { googleLoginButton = new JButton("Login"); googleLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } if(loggingIn) return; loggingIn = true; try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } facebookLoginButton.setVisible(false); googleLoginButton.setVisible(false); internalAccountPanel.setVisible(false); btnCancelLogin.setVisible(true); lblWaitingForAuthorization.setVisible(true); googleLogin = new GoogleLogin(rpcEngine, LoginDialog.this); googleLogin.start(); loggingIn = false; } }); googleLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT); googleLoginButton.setIcon(new ImageIcon(Utils.getResource(LoginDialog.class, "/images/g_logo_icon.png"))); panel.add(googleLoginButton); } { lblWaitingForAuthorization = new JLabel("Waiting for authorization..."); panel.add(lblWaitingForAuthorization); lblWaitingForAuthorization.setVisible(false); lblWaitingForAuthorization.setAlignmentX(Component.CENTER_ALIGNMENT); } { btnCancelLogin = new JButton("Cancel Login"); panel.add(btnCancelLogin); btnCancelLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancelLogin(); } }); btnCancelLogin.setVisible(false); btnCancelLogin.setAlignmentX(Component.CENTER_ALIGNMENT); } { errorLabel = new JLabel(""); panel.add(errorLabel); errorLabel.setForeground(Color.RED); } } { newAccountButton = new JButton("Create a New Account"); newAccountButton.setAlignmentX(Component.CENTER_ALIGNMENT); newAccountButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "New Account failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "New Account failed: Your client is out of date, please restart MAMEHub."); return; } try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new NewAccountDialog(LoginDialog.this, rpcEngine).setVisible(true); } }); { lblOrCreateA = new JLabel("Or create a new MAMEHub account"); lblOrCreateA.setAlignmentX(0.5f); contentPanel.add(lblOrCreateA); } contentPanel.add(newAccountButton); } { lblNewLabel_1 = new JLabel("Or Login with an existing MAMEHub account"); lblNewLabel_1.setAlignmentX(Component.CENTER_ALIGNMENT); contentPanel.add(lblNewLabel_1); } { internalAccountPanel = new JPanel(); contentPanel.add(internalAccountPanel); internalAccountPanel.setLayout(new GridLayout(3, 2, 0, 0)); { lblUserName = new JLabel("Username"); internalAccountPanel.add(lblUserName); } { usernameTextField = new JTextField(); internalAccountPanel.add(usernameTextField); usernameTextField.setColumns(10); } { lblPassword = new JLabel("Password"); internalAccountPanel.add(lblPassword); } { passwordTextField = new JPasswordField(); internalAccountPanel.add(passwordTextField); passwordTextField.setColumns(10); } { manualLoginButton = new JButton("Login"); manualLoginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: Your client is out of date, please restart MAMEHub."); return; } try { Main.portOpenerThread.join(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String errorMessage = rpcEngine.login(usernameTextField.getText(), passwordTextField.getText()); if(errorMessage.length()==0) { ApplicationSettings as = Utils.getApplicationSettings(); as.lastInternalLoginId = usernameTextField.getText(); Utils.putApplicationSettings(as); loginComplete(); } else { JOptionPane.showMessageDialog(LoginDialog.this, "Login failed: " + errorMessage); } } }); { panel_1 = new JPanel(); internalAccountPanel.add(panel_1); } internalAccountPanel.add(manualLoginButton); } { forgotPasswordButton = new JButton("Email Password Reminder"); forgotPasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { RpcEngine.PingResponse pr = rpcEngine.ping(); if(pr == RpcEngine.PingResponse.SERVER_DOWN) { JOptionPane.showMessageDialog(LoginDialog.this, "Email Password: MAMEHub server is down."); return; } if(pr == RpcEngine.PingResponse.CLIENT_TOO_OLD) { JOptionPane.showMessageDialog(LoginDialog.this, "Email Password: Your client is out of date, please restart MAMEHub."); return; } if(manualLoginButton.getText().length()<3) { JOptionPane.showMessageDialog(LoginDialog.this, "Enter a valid email address in the login field."); return; } if(!rpcEngine.emailPassword(manualLoginButton.getText())) { JOptionPane.showMessageDialog(LoginDialog.this, "Email address not found on server (did you make an account yet?)."); return; } else { JOptionPane.showMessageDialog(LoginDialog.this, "Password sent to " + manualLoginButton.getText()); return; } } }); forgotPasswordButton.setAlignmentX(0.5f); contentPanel.add(forgotPasswordButton); } } ApplicationSettings as = Utils.getApplicationSettings(); usernameTextField.setText(as.lastInternalLoginId); }
diff --git a/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java b/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java index 252652725..e342afdee 100644 --- a/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java +++ b/atlas-web/src/main/java/uk/ac/ebi/gxa/tasks/RepairExperimentTask.java @@ -1,91 +1,94 @@ /* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.tasks; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author pashky */ public class RepairExperimentTask extends AbstractWorkingTask { private static Logger log = LoggerFactory.getLogger(RepairExperimentTask.class); public static final String TYPE = "repairexperiment"; public void start() { final String accession = getTaskSpec().getAccession(); log.info("Repair experiment - task started, checking NetCDF"); final TaskSpec netcdfSpec = LoaderTask.SPEC_UPDATEEXPERIMENT(accession); final TaskStatus netcdfState = taskMan.getTaskStatus(netcdfSpec); if(TaskStatus.DONE != netcdfState) { taskMan.scheduleTask(this, netcdfSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); + taskMan.notifyTaskFinished(this); return; } log.info("Repair experiment - NetCDF is complete, checking analytics"); final TaskSpec analyticsSpec = AnalyticsTask.SPEC_ANALYTICS(accession); final TaskStatus analyticsState = taskMan.getTaskStatus(analyticsSpec); if(TaskStatus.DONE != analyticsState) { taskMan.scheduleTask(this, analyticsSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); + taskMan.notifyTaskFinished(this); return; } log.info("Repair experiment - analytics is complete, checking index"); final TaskSpec indexSpec = IndexTask.SPEC_INDEXEXPERIMENT(accession); final TaskStatus indexState = taskMan.getTaskStatus(indexSpec); if(TaskStatus.DONE != indexState) { taskMan.scheduleTask(this, indexSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); + taskMan.notifyTaskFinished(this); return; } log.info("Repair experiment - index is complete, nothing to do"); taskMan.notifyTaskFinished(this); } public void stop() { } public RepairExperimentTask(TaskManager taskMan, long taskId, TaskSpec taskSpec, TaskRunMode runMode, TaskUser user, boolean runningAutoDependencies) { super(taskMan, taskId, taskSpec, runMode, user, runningAutoDependencies); } public boolean isBlockedBy(Task otherTask) { return false; } public static final TaskFactory FACTORY = new TaskFactory() { public QueuedTask createTask(TaskManager taskMan, long taskId, TaskSpec taskSpec, TaskRunMode runMode, TaskUser user, boolean runningAutoDependencies) { return new RepairExperimentTask(taskMan, taskId, taskSpec, runMode, user, runningAutoDependencies); } public boolean isFor(TaskSpec taskSpec) { return TYPE.equals(taskSpec.getType()); } }; }
false
true
public void start() { final String accession = getTaskSpec().getAccession(); log.info("Repair experiment - task started, checking NetCDF"); final TaskSpec netcdfSpec = LoaderTask.SPEC_UPDATEEXPERIMENT(accession); final TaskStatus netcdfState = taskMan.getTaskStatus(netcdfSpec); if(TaskStatus.DONE != netcdfState) { taskMan.scheduleTask(this, netcdfSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); return; } log.info("Repair experiment - NetCDF is complete, checking analytics"); final TaskSpec analyticsSpec = AnalyticsTask.SPEC_ANALYTICS(accession); final TaskStatus analyticsState = taskMan.getTaskStatus(analyticsSpec); if(TaskStatus.DONE != analyticsState) { taskMan.scheduleTask(this, analyticsSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); return; } log.info("Repair experiment - analytics is complete, checking index"); final TaskSpec indexSpec = IndexTask.SPEC_INDEXEXPERIMENT(accession); final TaskStatus indexState = taskMan.getTaskStatus(indexSpec); if(TaskStatus.DONE != indexState) { taskMan.scheduleTask(this, indexSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); return; } log.info("Repair experiment - index is complete, nothing to do"); taskMan.notifyTaskFinished(this); }
public void start() { final String accession = getTaskSpec().getAccession(); log.info("Repair experiment - task started, checking NetCDF"); final TaskSpec netcdfSpec = LoaderTask.SPEC_UPDATEEXPERIMENT(accession); final TaskStatus netcdfState = taskMan.getTaskStatus(netcdfSpec); if(TaskStatus.DONE != netcdfState) { taskMan.scheduleTask(this, netcdfSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); taskMan.notifyTaskFinished(this); return; } log.info("Repair experiment - NetCDF is complete, checking analytics"); final TaskSpec analyticsSpec = AnalyticsTask.SPEC_ANALYTICS(accession); final TaskStatus analyticsState = taskMan.getTaskStatus(analyticsSpec); if(TaskStatus.DONE != analyticsState) { taskMan.scheduleTask(this, analyticsSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); taskMan.notifyTaskFinished(this); return; } log.info("Repair experiment - analytics is complete, checking index"); final TaskSpec indexSpec = IndexTask.SPEC_INDEXEXPERIMENT(accession); final TaskStatus indexState = taskMan.getTaskStatus(indexSpec); if(TaskStatus.DONE != indexState) { taskMan.scheduleTask(this, indexSpec, TaskRunMode.CONTINUE, getUser(), true, "Automatically added by experiment " + accession + " repair task"); taskMan.notifyTaskFinished(this); return; } log.info("Repair experiment - index is complete, nothing to do"); taskMan.notifyTaskFinished(this); }
diff --git a/src/de/cdauth/osm/basic/ChangesetContent.java b/src/de/cdauth/osm/basic/ChangesetContent.java index 473d382..c5a1445 100644 --- a/src/de/cdauth/osm/basic/ChangesetContent.java +++ b/src/de/cdauth/osm/basic/ChangesetContent.java @@ -1,411 +1,417 @@ /* This file is part of OSM Route Manager. OSM Route Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OSM Route Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with OSM Route Manager. If not, see <http://www.gnu.org/licenses/>. */ package de.cdauth.osm.basic; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.text.ParseException; import java.text.SimpleDateFormat; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Represents the content (the modified elements) of a changeset. */ public class ChangesetContent extends XMLObject { static private Hashtable<String,ChangesetContent> sm_cache = new Hashtable<String,ChangesetContent>(); private String m_id; public enum ChangeType { create, modify, delete }; /** * @param a_id The ID of the changeset, as it is not provided with the XML response. * @param a_dom */ protected ChangesetContent(String a_id, Element a_dom) { super(a_dom); m_id = a_id; } public static ChangesetContent fetch(String a_id) throws IOException, APIError, SAXException, ParserConfigurationException { if(isCached(a_id)) return sm_cache.get(a_id); ChangesetContent root = new ChangesetContent(a_id, API.fetch("/changeset/"+a_id+"/download")); sm_cache.put(a_id, root); return root; } protected static boolean isCached(String a_id) { return sm_cache.containsKey(a_id); } /** * Returns an array of all objects that are part of one ChangeType of this changeset. * @param a_type * @return For created and modified objects, their new version. For deleted objects, their old version. */ public Object[] getMemberObjects(ChangeType a_type) { ArrayList<Object> ret = new ArrayList<Object>(); NodeList nodes = getDOM().getElementsByTagName(a_type.toString()); for(int i=0; i<nodes.getLength(); i++) ret.addAll(API.makeObjects((Element) nodes.item(i))); Object[] retArr = ret.toArray(new Object[0]); for(Object object : retArr) { String type = object.getDOM().getTagName(); if(type.equals("node")) Node.getCache().cacheVersion((Node)object); else if(type.equals("way")) Way.getCache().cacheVersion((Way)object); else if(type.equals("relation")) Relation.getCache().cacheVersion((Relation)object); } return retArr; } /** * Returns all objects that are part of this changeset. * @return For created and modified objects, their new version. For deleted objects, their old version. */ public Object[] getMemberObjects() { ArrayList<Object> ret = new ArrayList<Object>(); ret.addAll(Arrays.asList(getMemberObjects(ChangeType.create))); ret.addAll(Arrays.asList(getMemberObjects(ChangeType.modify))); ret.addAll(Arrays.asList(getMemberObjects(ChangeType.delete))); return ret.toArray(new Object[0]); } /** * Fetches the previous version of all objects that were modified in this changeset. * @return A hashtable with the new version of an object in the key and the old version in the value * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws APIError */ public Hashtable<Object,Object> getPreviousVersions() throws IOException, SAXException, ParserConfigurationException, APIError { return getPreviousVersions(false); } /** * Fetches the previous version of all objects that were modified in this changeset. * @param onlyWithTagChanges If true, only objects will be returned whose tags have changed * @return A hashtable with the new version of an object in the key and the old version in the value * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws APIError */ public Hashtable<Object,Object> getPreviousVersions(boolean onlyWithTagChanges) throws IOException, SAXException, ParserConfigurationException, APIError { Object[] newVersions = getMemberObjects(ChangeType.modify); Hashtable<Object,Object> ret = new Hashtable<Object,Object>(); for(int i=0; i<newVersions.length; i++) { Object last = null; String tagName = newVersions[i].getDOM().getTagName(); try { if(tagName.equals("node")) last = Node.fetch(newVersions[i].getDOM().getAttribute("id"), ""+(Long.parseLong(newVersions[i].getDOM().getAttribute("version"))-1)); else if(tagName.equals("way")) last = Way.fetch(newVersions[i].getDOM().getAttribute("id"), ""+(Long.parseLong(newVersions[i].getDOM().getAttribute("version"))-1)); else if(tagName.equals("relation")) last = Relation.fetch(newVersions[i].getDOM().getAttribute("id"), ""+(Long.parseLong(newVersions[i].getDOM().getAttribute("version"))-1)); } catch(APIError e) { } if(!onlyWithTagChanges || !last.getTags().equals(newVersions[i].getTags())) ret.put(newVersions[i], last); } return ret; } /** * Resolves all ways and nodes that were changed in this changeset to segments * (connections of two nodes). Then returns three lists of segments: * 1. Those that have been removed (which is the case even if one of their nodes has been moved) * 2. Those that have been created * 3. Those that haven’t been changed but have somehow been affected by the changeset, * be it by changing their tags or by changing another part of the way they belong to. * Nodes that have been changed will be represented by a Segment consisting of two * equal Nodes. * @return An array of three Segment arrays. The first one is the removed segments, * the second one the created and the third one the unchanged ones. * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws APIError * @throws ParseException */ public Segment[][] getNodeChanges() throws IOException, SAXException, ParserConfigurationException, APIError, ParseException { Hashtable<Object,Object> old = getPreviousVersions(); Hashtable<String,Node> nodesRemoved = new Hashtable<String,Node>(); // All removed nodes and the old versions of all moved nodes Hashtable<String,Node> nodesAdded = new Hashtable<String,Node>(); // All created nodes and the new versions of all moved nodes Hashtable<String,Node> nodesChanged = new Hashtable<String,Node>(); // Only the new versions of all moved nodes for(Object obj : getMemberObjects(ChangeType.delete)) { if(obj.getDOM().getTagName().equals("node")) nodesRemoved.put(obj.getDOM().getAttribute("id"), (Node) obj); } for(Object obj : getMemberObjects(ChangeType.create)) { if(obj.getDOM().getTagName().equals("node")) nodesAdded.put(obj.getDOM().getAttribute("id"), (Node) obj); } for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("node")) continue; Node newVersion = (Node)obj; Node oldVersion = (Node)old.get(obj); if(oldVersion == null) continue; nodesRemoved.put(oldVersion.getDOM().getAttribute("id"), oldVersion); nodesAdded.put(newVersion.getDOM().getAttribute("id"), newVersion); if(!oldVersion.getLonLat().equals(newVersion.getLonLat())) nodesChanged.put(newVersion.getDOM().getAttribute("id"), newVersion); } Hashtable<Way,List<String>> containedWays = new Hashtable<Way,List<String>>(); Hashtable<String,Way> previousWays = new Hashtable<String,Way>(); for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("way")) continue; Way way = (Way) obj; containedWays.put(way, Arrays.asList(way.getMembers())); previousWays.put(way.getDOM().getAttribute("id"), (Way)old.get(way)); } // If only one node is moved in a changeset, that node might be a member of one or more // ways and thus change these. As there is no real way to find out the parent ways // of a node at the time of the changeset, we have to guess them. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date changesetDate = dateFormat.parse(Changeset.fetch(m_id).getDOM().getAttribute("created_at")); Hashtable<String,Way> waysChanged = new Hashtable<String,Way>(); for(Node node : nodesChanged.values()) { String nodeID = node.getDOM().getAttribute("id"); // First guess: Ways that have been changed in the changeset /*for(Map.Entry<Way,List<String>> entry : containedWays.entrySet()) { if(entry.getValue().contains(nodeID)) { String id = entry.getKey().getDOM().getAttribute("id"); waysChanged.put(id, previousWays.get(id)); } }*/ // Second guess: Current parent nodes of the node for(Object obj : API.get("/node/"+node.getDOM().getAttribute("id")+"/ways")) { if(!obj.getDOM().getTagName().equals("way")) continue; if(waysChanged.containsKey(obj.getDOM().getAttribute("id"))) continue; if(containedWays.containsKey(obj)) continue; TreeMap<Long,Way> history = Way.getHistory(obj.getDOM().getAttribute("id")); for(Way historyEntry : history.descendingMap().values()) { Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp")); if(historyDate.compareTo(changesetDate) < 0) { if(Arrays.asList(historyEntry.getMembers()).contains(nodeID)) waysChanged.put(historyEntry.getDOM().getAttribute("id"), historyEntry); break; } } } } // Now make an array of node arrays to represent the old and the new form of the changed ways Hashtable<String,Node> nodesCache = new Hashtable<String,Node>(); HashSet<Segment> segmentsOld = new HashSet<Segment>(); HashSet<Segment> segmentsNew = new HashSet<Segment>(); for(Object obj : getMemberObjects(ChangeType.create)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesAdded.containsKey(id)) thisNode = nodesAdded.get(id); else { if(!nodesCache.containsKey(id)) - nodesCache.put(id, Node.fetch(id, changesetDate)); - thisNode = nodesCache.get(id); + { + thisNode = Node.fetch(id, changesetDate); + if(thisNode == null) + continue; + nodesCache.put(id, thisNode); + } + else + thisNode = nodesCache.get(id); } if(lastNode != null) segmentsNew.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Object obj : getMemberObjects(ChangeType.delete)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesRemoved.containsKey(id)) thisNode = nodesRemoved.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsOld.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)old.get(obj)).getMembers()) { Node thisNode = null; if(nodesRemoved.containsKey(id)) thisNode = nodesRemoved.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsOld.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesAdded.containsKey(id)) thisNode = nodesAdded.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsNew.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Way way : waysChanged.values()) { Node lastNodeOld = null; Node lastNodeNew = null; for(String id : way.getMembers()) { Node thisNodeOld = null; Node thisNodeNew = null; if(nodesAdded.containsKey(id)) thisNodeNew = nodesAdded.get(id); if(nodesRemoved.containsKey(id)) thisNodeOld = nodesRemoved.get(id); if(thisNodeOld == null || thisNodeNew == null) { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); if(thisNodeOld == null) thisNodeOld = nodesCache.get(id); if(thisNodeNew == null) thisNodeNew = nodesCache.get(id); } if(lastNodeOld != null) segmentsOld.add(new Segment(lastNodeOld, thisNodeOld)); if(lastNodeNew != null) segmentsNew.add(new Segment(lastNodeNew, thisNodeNew)); lastNodeOld = thisNodeOld; lastNodeNew = thisNodeNew; } } // Create one-node entries for node changes for(Node node : nodesRemoved.values()) segmentsOld.add(new Segment(node, node)); for(Node node : nodesAdded.values()) segmentsNew.add(new Segment(node, node)); HashSet<Segment> segmentsUnchanged = new HashSet<Segment>(); segmentsUnchanged.addAll(segmentsOld); segmentsUnchanged.retainAll(segmentsNew); segmentsOld.removeAll(segmentsUnchanged); segmentsNew.removeAll(segmentsUnchanged); Segment[][] ret = { segmentsOld.toArray(new Segment[0]), segmentsNew.toArray(new Segment[0]), segmentsUnchanged.toArray(new Segment[0]) }; return ret; } }
true
true
public Segment[][] getNodeChanges() throws IOException, SAXException, ParserConfigurationException, APIError, ParseException { Hashtable<Object,Object> old = getPreviousVersions(); Hashtable<String,Node> nodesRemoved = new Hashtable<String,Node>(); // All removed nodes and the old versions of all moved nodes Hashtable<String,Node> nodesAdded = new Hashtable<String,Node>(); // All created nodes and the new versions of all moved nodes Hashtable<String,Node> nodesChanged = new Hashtable<String,Node>(); // Only the new versions of all moved nodes for(Object obj : getMemberObjects(ChangeType.delete)) { if(obj.getDOM().getTagName().equals("node")) nodesRemoved.put(obj.getDOM().getAttribute("id"), (Node) obj); } for(Object obj : getMemberObjects(ChangeType.create)) { if(obj.getDOM().getTagName().equals("node")) nodesAdded.put(obj.getDOM().getAttribute("id"), (Node) obj); } for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("node")) continue; Node newVersion = (Node)obj; Node oldVersion = (Node)old.get(obj); if(oldVersion == null) continue; nodesRemoved.put(oldVersion.getDOM().getAttribute("id"), oldVersion); nodesAdded.put(newVersion.getDOM().getAttribute("id"), newVersion); if(!oldVersion.getLonLat().equals(newVersion.getLonLat())) nodesChanged.put(newVersion.getDOM().getAttribute("id"), newVersion); } Hashtable<Way,List<String>> containedWays = new Hashtable<Way,List<String>>(); Hashtable<String,Way> previousWays = new Hashtable<String,Way>(); for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("way")) continue; Way way = (Way) obj; containedWays.put(way, Arrays.asList(way.getMembers())); previousWays.put(way.getDOM().getAttribute("id"), (Way)old.get(way)); } // If only one node is moved in a changeset, that node might be a member of one or more // ways and thus change these. As there is no real way to find out the parent ways // of a node at the time of the changeset, we have to guess them. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date changesetDate = dateFormat.parse(Changeset.fetch(m_id).getDOM().getAttribute("created_at")); Hashtable<String,Way> waysChanged = new Hashtable<String,Way>(); for(Node node : nodesChanged.values()) { String nodeID = node.getDOM().getAttribute("id"); // First guess: Ways that have been changed in the changeset /*for(Map.Entry<Way,List<String>> entry : containedWays.entrySet()) { if(entry.getValue().contains(nodeID)) { String id = entry.getKey().getDOM().getAttribute("id"); waysChanged.put(id, previousWays.get(id)); } }*/ // Second guess: Current parent nodes of the node for(Object obj : API.get("/node/"+node.getDOM().getAttribute("id")+"/ways")) { if(!obj.getDOM().getTagName().equals("way")) continue; if(waysChanged.containsKey(obj.getDOM().getAttribute("id"))) continue; if(containedWays.containsKey(obj)) continue; TreeMap<Long,Way> history = Way.getHistory(obj.getDOM().getAttribute("id")); for(Way historyEntry : history.descendingMap().values()) { Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp")); if(historyDate.compareTo(changesetDate) < 0) { if(Arrays.asList(historyEntry.getMembers()).contains(nodeID)) waysChanged.put(historyEntry.getDOM().getAttribute("id"), historyEntry); break; } } } } // Now make an array of node arrays to represent the old and the new form of the changed ways Hashtable<String,Node> nodesCache = new Hashtable<String,Node>(); HashSet<Segment> segmentsOld = new HashSet<Segment>(); HashSet<Segment> segmentsNew = new HashSet<Segment>(); for(Object obj : getMemberObjects(ChangeType.create)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesAdded.containsKey(id)) thisNode = nodesAdded.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsNew.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Object obj : getMemberObjects(ChangeType.delete)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesRemoved.containsKey(id)) thisNode = nodesRemoved.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsOld.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)old.get(obj)).getMembers()) { Node thisNode = null; if(nodesRemoved.containsKey(id)) thisNode = nodesRemoved.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsOld.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesAdded.containsKey(id)) thisNode = nodesAdded.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsNew.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Way way : waysChanged.values()) { Node lastNodeOld = null; Node lastNodeNew = null; for(String id : way.getMembers()) { Node thisNodeOld = null; Node thisNodeNew = null; if(nodesAdded.containsKey(id)) thisNodeNew = nodesAdded.get(id); if(nodesRemoved.containsKey(id)) thisNodeOld = nodesRemoved.get(id); if(thisNodeOld == null || thisNodeNew == null) { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); if(thisNodeOld == null) thisNodeOld = nodesCache.get(id); if(thisNodeNew == null) thisNodeNew = nodesCache.get(id); } if(lastNodeOld != null) segmentsOld.add(new Segment(lastNodeOld, thisNodeOld)); if(lastNodeNew != null) segmentsNew.add(new Segment(lastNodeNew, thisNodeNew)); lastNodeOld = thisNodeOld; lastNodeNew = thisNodeNew; } } // Create one-node entries for node changes for(Node node : nodesRemoved.values()) segmentsOld.add(new Segment(node, node)); for(Node node : nodesAdded.values()) segmentsNew.add(new Segment(node, node)); HashSet<Segment> segmentsUnchanged = new HashSet<Segment>(); segmentsUnchanged.addAll(segmentsOld); segmentsUnchanged.retainAll(segmentsNew); segmentsOld.removeAll(segmentsUnchanged); segmentsNew.removeAll(segmentsUnchanged); Segment[][] ret = { segmentsOld.toArray(new Segment[0]), segmentsNew.toArray(new Segment[0]), segmentsUnchanged.toArray(new Segment[0]) }; return ret; }
public Segment[][] getNodeChanges() throws IOException, SAXException, ParserConfigurationException, APIError, ParseException { Hashtable<Object,Object> old = getPreviousVersions(); Hashtable<String,Node> nodesRemoved = new Hashtable<String,Node>(); // All removed nodes and the old versions of all moved nodes Hashtable<String,Node> nodesAdded = new Hashtable<String,Node>(); // All created nodes and the new versions of all moved nodes Hashtable<String,Node> nodesChanged = new Hashtable<String,Node>(); // Only the new versions of all moved nodes for(Object obj : getMemberObjects(ChangeType.delete)) { if(obj.getDOM().getTagName().equals("node")) nodesRemoved.put(obj.getDOM().getAttribute("id"), (Node) obj); } for(Object obj : getMemberObjects(ChangeType.create)) { if(obj.getDOM().getTagName().equals("node")) nodesAdded.put(obj.getDOM().getAttribute("id"), (Node) obj); } for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("node")) continue; Node newVersion = (Node)obj; Node oldVersion = (Node)old.get(obj); if(oldVersion == null) continue; nodesRemoved.put(oldVersion.getDOM().getAttribute("id"), oldVersion); nodesAdded.put(newVersion.getDOM().getAttribute("id"), newVersion); if(!oldVersion.getLonLat().equals(newVersion.getLonLat())) nodesChanged.put(newVersion.getDOM().getAttribute("id"), newVersion); } Hashtable<Way,List<String>> containedWays = new Hashtable<Way,List<String>>(); Hashtable<String,Way> previousWays = new Hashtable<String,Way>(); for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("way")) continue; Way way = (Way) obj; containedWays.put(way, Arrays.asList(way.getMembers())); previousWays.put(way.getDOM().getAttribute("id"), (Way)old.get(way)); } // If only one node is moved in a changeset, that node might be a member of one or more // ways and thus change these. As there is no real way to find out the parent ways // of a node at the time of the changeset, we have to guess them. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date changesetDate = dateFormat.parse(Changeset.fetch(m_id).getDOM().getAttribute("created_at")); Hashtable<String,Way> waysChanged = new Hashtable<String,Way>(); for(Node node : nodesChanged.values()) { String nodeID = node.getDOM().getAttribute("id"); // First guess: Ways that have been changed in the changeset /*for(Map.Entry<Way,List<String>> entry : containedWays.entrySet()) { if(entry.getValue().contains(nodeID)) { String id = entry.getKey().getDOM().getAttribute("id"); waysChanged.put(id, previousWays.get(id)); } }*/ // Second guess: Current parent nodes of the node for(Object obj : API.get("/node/"+node.getDOM().getAttribute("id")+"/ways")) { if(!obj.getDOM().getTagName().equals("way")) continue; if(waysChanged.containsKey(obj.getDOM().getAttribute("id"))) continue; if(containedWays.containsKey(obj)) continue; TreeMap<Long,Way> history = Way.getHistory(obj.getDOM().getAttribute("id")); for(Way historyEntry : history.descendingMap().values()) { Date historyDate = dateFormat.parse(historyEntry.getDOM().getAttribute("timestamp")); if(historyDate.compareTo(changesetDate) < 0) { if(Arrays.asList(historyEntry.getMembers()).contains(nodeID)) waysChanged.put(historyEntry.getDOM().getAttribute("id"), historyEntry); break; } } } } // Now make an array of node arrays to represent the old and the new form of the changed ways Hashtable<String,Node> nodesCache = new Hashtable<String,Node>(); HashSet<Segment> segmentsOld = new HashSet<Segment>(); HashSet<Segment> segmentsNew = new HashSet<Segment>(); for(Object obj : getMemberObjects(ChangeType.create)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesAdded.containsKey(id)) thisNode = nodesAdded.get(id); else { if(!nodesCache.containsKey(id)) { thisNode = Node.fetch(id, changesetDate); if(thisNode == null) continue; nodesCache.put(id, thisNode); } else thisNode = nodesCache.get(id); } if(lastNode != null) segmentsNew.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Object obj : getMemberObjects(ChangeType.delete)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesRemoved.containsKey(id)) thisNode = nodesRemoved.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsOld.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Object obj : getMemberObjects(ChangeType.modify)) { if(!obj.getDOM().getTagName().equals("way")) continue; Node lastNode = null; for(String id : ((Way)old.get(obj)).getMembers()) { Node thisNode = null; if(nodesRemoved.containsKey(id)) thisNode = nodesRemoved.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsOld.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } lastNode = null; for(String id : ((Way)obj).getMembers()) { Node thisNode = null; if(nodesAdded.containsKey(id)) thisNode = nodesAdded.get(id); else { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); thisNode = nodesCache.get(id); } if(lastNode != null) segmentsNew.add(new Segment(lastNode, thisNode)); lastNode = thisNode; } } for(Way way : waysChanged.values()) { Node lastNodeOld = null; Node lastNodeNew = null; for(String id : way.getMembers()) { Node thisNodeOld = null; Node thisNodeNew = null; if(nodesAdded.containsKey(id)) thisNodeNew = nodesAdded.get(id); if(nodesRemoved.containsKey(id)) thisNodeOld = nodesRemoved.get(id); if(thisNodeOld == null || thisNodeNew == null) { if(!nodesCache.containsKey(id)) nodesCache.put(id, Node.fetch(id, changesetDate)); if(thisNodeOld == null) thisNodeOld = nodesCache.get(id); if(thisNodeNew == null) thisNodeNew = nodesCache.get(id); } if(lastNodeOld != null) segmentsOld.add(new Segment(lastNodeOld, thisNodeOld)); if(lastNodeNew != null) segmentsNew.add(new Segment(lastNodeNew, thisNodeNew)); lastNodeOld = thisNodeOld; lastNodeNew = thisNodeNew; } } // Create one-node entries for node changes for(Node node : nodesRemoved.values()) segmentsOld.add(new Segment(node, node)); for(Node node : nodesAdded.values()) segmentsNew.add(new Segment(node, node)); HashSet<Segment> segmentsUnchanged = new HashSet<Segment>(); segmentsUnchanged.addAll(segmentsOld); segmentsUnchanged.retainAll(segmentsNew); segmentsOld.removeAll(segmentsUnchanged); segmentsNew.removeAll(segmentsUnchanged); Segment[][] ret = { segmentsOld.toArray(new Segment[0]), segmentsNew.toArray(new Segment[0]), segmentsUnchanged.toArray(new Segment[0]) }; return ret; }
diff --git a/src/com/markupartist/iglaset/provider/DrinksParser.java b/src/com/markupartist/iglaset/provider/DrinksParser.java index 73589de..4a62a46 100644 --- a/src/com/markupartist/iglaset/provider/DrinksParser.java +++ b/src/com/markupartist/iglaset/provider/DrinksParser.java @@ -1,138 +1,138 @@ package com.markupartist.iglaset.provider; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import android.text.TextUtils; import android.util.Log; import com.markupartist.iglaset.provider.Drink.Volume; class DrinksParser extends DefaultHandler { private static final String TAG = "DrinksParser"; private ArrayList<Drink> mDrinks = null; private Drink mCurrentDrink; private Volume mCurrentVolume = null; private String mCurrentTagType; private StringBuilder mTextBuffer = null; @Override public void startDocument() throws SAXException { super.startDocument(); mTextBuffer = new StringBuilder(); } public ArrayList<Drink> parseDrinks(InputStream in, ArrayList<Drink> drinks) { try { mDrinks = drinks; InputSource inputSource = new InputSource(in); inputSource.setEncoding("UTF-8"); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); xr.parse(inputSource); } catch (IOException e) { Log.e(TAG, e.toString()); } catch (SAXException e) { Log.e(TAG, e.toString()); } catch (ParserConfigurationException e) { Log.e(TAG, e.toString()); } return mDrinks; } public void startElement(String uri, String name, String qName, Attributes atts) { if (name.equals("article")) { mCurrentDrink = new Drink(Integer.parseInt(atts.getValue("id").trim())); } else if (name.equals("supplier") && !TextUtils.isEmpty(atts.getValue("url").trim())) { mCurrentDrink.setSupplierUrl(atts.getValue("url").trim()); } else if (name.equals("volume")) { mCurrentVolume = new Volume(); mCurrentVolume.setArticleId(Integer.parseInt(atts.getValue("sb_article_id").trim())); mCurrentVolume.setPriceSek(atts.getValue("price").trim()); mCurrentVolume.setRetired(Integer.parseInt(atts.getValue("retired").trim())); } else if (name.equals("tag")) { mCurrentTagType = atts.getValue("type").trim(); } } public void characters(char ch[], int start, int length) { mTextBuffer.append(ch, start, length); } public void endElement(String uri, String name, String qName) throws SAXException { final String result = mTextBuffer.toString().replace("\n", "").trim(); if (mCurrentDrink != null) { if (name.trim().equals("name")) { mCurrentDrink.setName(result); } else if (name.equals("producer")) { mCurrentDrink.setProducer(result); } else if (name.equals("supplier")) { mCurrentDrink.setSupplier(result); } else if (name.equals("origin")) { mCurrentDrink.setOrigin(result); } else if (name.equals("origin_country")) { mCurrentDrink.setOriginCountry(result); } else if (name.equals("alc_percent")) { mCurrentDrink.setAlcoholPercent(result); } else if (name.equals("year")) { mCurrentDrink.setYear(Integer.parseInt(result)); } else if (name.equals("volume")) { mCurrentVolume.setVolume(Integer.parseInt(result)); mCurrentDrink.addVolume(mCurrentVolume); } else if (name.equals("tag")) { mCurrentDrink.addTag(mCurrentTagType, result); } else if (name.equals("commercial_desc")) { // Use newline as <br>. That's why the distilled "result" variable // cannot be used. - mCurrentDrink.setDescription(mTextBuffer.toString().replaceAll("\n", "<br/>")); + mCurrentDrink.setDescription(mTextBuffer.toString().trim().replaceAll("\n", "<br/>")); } else if (name.equals("avg_rating")) { mCurrentDrink.setRating(result); } else if (name.equals("comments")) { mCurrentDrink.setCommentCount(Integer.parseInt(result)); } else if (name.equals("small")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.SMALL, result); } } else if (name.equals("medium")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.MEDIUM, result); } } else if (name.equals("large")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.LARGE, result); } } else if (name.equals("user_rating") && result.length() > 0) { mCurrentDrink.setUserRating(Float.parseFloat(result)); } else if (name.equals("comments")) { mCurrentDrink.setCommentCount(Integer.parseInt(result)); } else if (name.equals("ratings")) { mCurrentDrink.setRatingCount(Integer.parseInt(result)); } } if (name.trim().equals("article")) { mDrinks.add(mCurrentDrink); mCurrentDrink = null; } mTextBuffer.setLength(0); } }
true
true
public void endElement(String uri, String name, String qName) throws SAXException { final String result = mTextBuffer.toString().replace("\n", "").trim(); if (mCurrentDrink != null) { if (name.trim().equals("name")) { mCurrentDrink.setName(result); } else if (name.equals("producer")) { mCurrentDrink.setProducer(result); } else if (name.equals("supplier")) { mCurrentDrink.setSupplier(result); } else if (name.equals("origin")) { mCurrentDrink.setOrigin(result); } else if (name.equals("origin_country")) { mCurrentDrink.setOriginCountry(result); } else if (name.equals("alc_percent")) { mCurrentDrink.setAlcoholPercent(result); } else if (name.equals("year")) { mCurrentDrink.setYear(Integer.parseInt(result)); } else if (name.equals("volume")) { mCurrentVolume.setVolume(Integer.parseInt(result)); mCurrentDrink.addVolume(mCurrentVolume); } else if (name.equals("tag")) { mCurrentDrink.addTag(mCurrentTagType, result); } else if (name.equals("commercial_desc")) { // Use newline as <br>. That's why the distilled "result" variable // cannot be used. mCurrentDrink.setDescription(mTextBuffer.toString().replaceAll("\n", "<br/>")); } else if (name.equals("avg_rating")) { mCurrentDrink.setRating(result); } else if (name.equals("comments")) { mCurrentDrink.setCommentCount(Integer.parseInt(result)); } else if (name.equals("small")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.SMALL, result); } } else if (name.equals("medium")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.MEDIUM, result); } } else if (name.equals("large")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.LARGE, result); } } else if (name.equals("user_rating") && result.length() > 0) { mCurrentDrink.setUserRating(Float.parseFloat(result)); } else if (name.equals("comments")) { mCurrentDrink.setCommentCount(Integer.parseInt(result)); } else if (name.equals("ratings")) { mCurrentDrink.setRatingCount(Integer.parseInt(result)); } } if (name.trim().equals("article")) { mDrinks.add(mCurrentDrink); mCurrentDrink = null; } mTextBuffer.setLength(0); }
public void endElement(String uri, String name, String qName) throws SAXException { final String result = mTextBuffer.toString().replace("\n", "").trim(); if (mCurrentDrink != null) { if (name.trim().equals("name")) { mCurrentDrink.setName(result); } else if (name.equals("producer")) { mCurrentDrink.setProducer(result); } else if (name.equals("supplier")) { mCurrentDrink.setSupplier(result); } else if (name.equals("origin")) { mCurrentDrink.setOrigin(result); } else if (name.equals("origin_country")) { mCurrentDrink.setOriginCountry(result); } else if (name.equals("alc_percent")) { mCurrentDrink.setAlcoholPercent(result); } else if (name.equals("year")) { mCurrentDrink.setYear(Integer.parseInt(result)); } else if (name.equals("volume")) { mCurrentVolume.setVolume(Integer.parseInt(result)); mCurrentDrink.addVolume(mCurrentVolume); } else if (name.equals("tag")) { mCurrentDrink.addTag(mCurrentTagType, result); } else if (name.equals("commercial_desc")) { // Use newline as <br>. That's why the distilled "result" variable // cannot be used. mCurrentDrink.setDescription(mTextBuffer.toString().trim().replaceAll("\n", "<br/>")); } else if (name.equals("avg_rating")) { mCurrentDrink.setRating(result); } else if (name.equals("comments")) { mCurrentDrink.setCommentCount(Integer.parseInt(result)); } else if (name.equals("small")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.SMALL, result); } } else if (name.equals("medium")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.MEDIUM, result); } } else if (name.equals("large")) { if (!TextUtils.isEmpty(mTextBuffer)) { mCurrentDrink.setImageUrl(Drink.ImageSize.LARGE, result); } } else if (name.equals("user_rating") && result.length() > 0) { mCurrentDrink.setUserRating(Float.parseFloat(result)); } else if (name.equals("comments")) { mCurrentDrink.setCommentCount(Integer.parseInt(result)); } else if (name.equals("ratings")) { mCurrentDrink.setRatingCount(Integer.parseInt(result)); } } if (name.trim().equals("article")) { mDrinks.add(mCurrentDrink); mCurrentDrink = null; } mTextBuffer.setLength(0); }
diff --git a/src/taberystwyth/controller/JudgeInsertionFrameListener.java b/src/taberystwyth/controller/JudgeInsertionFrameListener.java index a7a5112..f8a608f 100644 --- a/src/taberystwyth/controller/JudgeInsertionFrameListener.java +++ b/src/taberystwyth/controller/JudgeInsertionFrameListener.java @@ -1,80 +1,84 @@ /* * This file is part of TAberystwyth, a debating competition organiser * Copyright (C) 2010, Roberto Sarrionandia and Cal Paterson * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package taberystwyth.controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import taberystwyth.db.TabServer; import taberystwyth.view.JudgeInsertionFrame; /** * This class is the listener for the judge insertion frame * * @author Roberto Sarrionandia * @author Cal Paterson * */ public class JudgeInsertionFrameListener implements ActionListener { private static final Logger LOG = Logger .getLogger(JudgeInsertionFrameListener.class); private JudgeInsertionFrame frame; @Override public void actionPerformed(ActionEvent e) { frame = JudgeInsertionFrame.getInstance(); if (e.getActionCommand().equals("Save")) { try { Connection sql = TabServer.getConnectionPool().getConnection(); synchronized (sql) { - String s = "insert into judges (name, institution, rating) values (?,?,?);"; + String s = "insert into judges " + + "(\"name\", " + + "\"institution\", " + + "\"rating\") " + + "values (?,?,?);"; PreparedStatement p = sql.prepareStatement(s); p.setString(1, frame.getJudgeName().getText()); p.setString(2, frame.getInstitution().getText()); p.setString(3, frame.getRating().getText()); p.execute(); p.close(); sql.commit(); } } catch (SQLException e1) { LOG.error("Unable to insert a judge", e1); JOptionPane.showMessageDialog(frame, "Unable to insert that judge into the database", "Database Error", JOptionPane.ERROR_MESSAGE); } frame.getJudgeName().setText(""); frame.getInstitution().setText(""); frame.getRating().setText(""); } else if (e.getActionCommand().equals("Clear")) { frame.getJudgeName().setText(""); frame.getInstitution().setText(""); frame.getRating().setText(""); } } }
true
true
public void actionPerformed(ActionEvent e) { frame = JudgeInsertionFrame.getInstance(); if (e.getActionCommand().equals("Save")) { try { Connection sql = TabServer.getConnectionPool().getConnection(); synchronized (sql) { String s = "insert into judges (name, institution, rating) values (?,?,?);"; PreparedStatement p = sql.prepareStatement(s); p.setString(1, frame.getJudgeName().getText()); p.setString(2, frame.getInstitution().getText()); p.setString(3, frame.getRating().getText()); p.execute(); p.close(); sql.commit(); } } catch (SQLException e1) { LOG.error("Unable to insert a judge", e1); JOptionPane.showMessageDialog(frame, "Unable to insert that judge into the database", "Database Error", JOptionPane.ERROR_MESSAGE); } frame.getJudgeName().setText(""); frame.getInstitution().setText(""); frame.getRating().setText(""); } else if (e.getActionCommand().equals("Clear")) { frame.getJudgeName().setText(""); frame.getInstitution().setText(""); frame.getRating().setText(""); } }
public void actionPerformed(ActionEvent e) { frame = JudgeInsertionFrame.getInstance(); if (e.getActionCommand().equals("Save")) { try { Connection sql = TabServer.getConnectionPool().getConnection(); synchronized (sql) { String s = "insert into judges " + "(\"name\", " + "\"institution\", " + "\"rating\") " + "values (?,?,?);"; PreparedStatement p = sql.prepareStatement(s); p.setString(1, frame.getJudgeName().getText()); p.setString(2, frame.getInstitution().getText()); p.setString(3, frame.getRating().getText()); p.execute(); p.close(); sql.commit(); } } catch (SQLException e1) { LOG.error("Unable to insert a judge", e1); JOptionPane.showMessageDialog(frame, "Unable to insert that judge into the database", "Database Error", JOptionPane.ERROR_MESSAGE); } frame.getJudgeName().setText(""); frame.getInstitution().setText(""); frame.getRating().setText(""); } else if (e.getActionCommand().equals("Clear")) { frame.getJudgeName().setText(""); frame.getInstitution().setText(""); frame.getRating().setText(""); } }
diff --git a/src/java/net/sf/samtools/SAMRecord.java b/src/java/net/sf/samtools/SAMRecord.java index d5f873f..801cd01 100644 --- a/src/java/net/sf/samtools/SAMRecord.java +++ b/src/java/net/sf/samtools/SAMRecord.java @@ -1,1757 +1,1757 @@ /* * The MIT License * * Copyright (c) 2009 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a 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, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 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 net.sf.samtools; import net.sf.samtools.util.CoordMath; import net.sf.samtools.util.StringUtil; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Java binding for a SAM file record. c.f. http://samtools.sourceforge.net/SAM1.pdf * * The presence of reference name/reference index and alignment start * do not necessarily mean that a read is aligned. Those values may merely be set to force a SAMRecord * to appear in a certain place in the sort order. The readUnmappedFlag must be checked to determine whether * or not a read is mapped. Only if the readUnmappedFlag is false can the reference name/index and alignment start * be interpreted as indicating an actual alignment position. * * Likewise, presence of mate reference name/index and mate alignment start do not necessarily mean that the * mate is aligned. These may be set for an unaligned mate if the mate has been forced into a particular place * in the sort order per the above paragraph. Only if the mateUnmappedFlag is false can the mate reference name/index * and mate alignment start be interpreted as indicating the actual alignment position of the mate. * * Note also that there are a number of getters & setters that are linked, i.e. they present different representations * of the same underlying data. In these cases there is typically a representation that is preferred because it * ought to be faster than some other representation. The following are the preferred representations: * * getReadNameLength() is preferred to getReadName().length() * get/setReadBases() is preferred to get/setReadString() * get/setBaseQualities() is preferred to get/setBaseQualityString() * get/setReferenceIndex() is preferred to get/setReferenceName() * get/setMateReferenceIndex() is preferred to get/setMateReferenceName() * getCigarLength() is preferred to getCigar().getNumElements() * get/setCigar() is preferred to get/setCigarString() * * Note that setIndexingBin() need not be called when writing SAMRecords. It will be computed as necessary. It is only * present as an optimization in the event that the value is already known and need not be computed. * * setHeader() need not be called when writing SAMRecords. It may be convenient to call it, however, because * get/setReferenceIndex() and get/setMateReferenceIndex() must have access to the SAM header, either as an argument * or previously passed to setHeader(). * * setHeader() is called by the SAM reading code, so the get/setReferenceIndex() and get/setMateReferenceIndex() * methods will have access to the sequence dictionary. * * Some of the get() methods return values that are mutable, due to the limitations of Java. A caller should * never change the value returned by a get() method. If you want to change the value of some attribute of a * SAMRecord, create a new value object and call the appropriate set() method. * * By default, extensive validation of SAMRecords is done when they are read. Very limited validation is done when * values are set onto SAMRecords. */ public class SAMRecord implements Cloneable { /** * Alignment score for a good alignment, but where computing a Phred-score is not feasible. */ public static final int UNKNOWN_MAPPING_QUALITY = 255; /** * Alignment score for an unaligned read. */ public static final int NO_MAPPING_QUALITY = 0; /** * If a read has this reference name, it is unaligned, but not all unaligned reads have * this reference name (see above). */ public static final String NO_ALIGNMENT_REFERENCE_NAME = "*"; /** * If a read has this reference index, it is unaligned, but not all unaligned reads have * this reference index (see above). */ public static final int NO_ALIGNMENT_REFERENCE_INDEX = -1; /** * Cigar string for an unaligned read. */ public static final String NO_ALIGNMENT_CIGAR = "*"; /** * If a read has reference name "*", it will have this value for position. */ public static final int NO_ALIGNMENT_START = 0; /** * This should rarely be used, since a read with no sequence doesn't make much sense. */ public static final byte[] NULL_SEQUENCE = new byte[0]; public static final String NULL_SEQUENCE_STRING = "*"; /** * This should rarely be used, since all reads should have quality scores. */ public static final byte[] NULL_QUALS = new byte[0]; public static final String NULL_QUALS_STRING = "*"; /** * abs(insertSize) must be <= this */ public static final int MAX_INSERT_SIZE = 1<<29; /** * It is not necessary in general to use the flag constants, because there are getters * & setters that handles these symbolically. */ private static final int READ_PAIRED_FLAG = 0x1; private static final int PROPER_PAIR_FLAG = 0x2; private static final int READ_UNMAPPED_FLAG = 0x4; private static final int MATE_UNMAPPED_FLAG = 0x8; private static final int READ_STRAND_FLAG = 0x10; private static final int MATE_STRAND_FLAG = 0x20; private static final int FIRST_OF_PAIR_FLAG = 0x40; private static final int SECOND_OF_PAIR_FLAG = 0x80; private static final int NOT_PRIMARY_ALIGNMENT_FLAG = 0x100; private static final int READ_FAILS_VENDOR_QUALITY_CHECK_FLAG = 0x200; private static final int DUPLICATE_READ_FLAG = 0x400; private String mReadName = null; private byte[] mReadBases = NULL_SEQUENCE; private byte[] mBaseQualities = NULL_QUALS; private String mReferenceName = NO_ALIGNMENT_REFERENCE_NAME; private int mAlignmentStart = NO_ALIGNMENT_START; private transient int mAlignmentEnd = NO_ALIGNMENT_START; private int mMappingQuality = NO_MAPPING_QUALITY; private String mCigarString = NO_ALIGNMENT_CIGAR; private Cigar mCigar = null; private List<AlignmentBlock> mAlignmentBlocks = null; private int mFlags = 0; private String mMateReferenceName = NO_ALIGNMENT_REFERENCE_NAME; private int mMateAlignmentStart = 0; private int mInferredInsertSize = 0; private SAMBinaryTagAndValue mAttributes = null; protected Integer mReferenceIndex = null; protected Integer mMateReferenceIndex = null; private Integer mIndexingBin = null; /** * Some attributes (e.g. CIGAR) are not decoded immediately. Use this to decide how to validate when decoded. */ private SAMFileReader.ValidationStringency mValidationStringency = SAMFileReader.ValidationStringency.SILENT; private SAMFileSource mFileSource; private SAMFileHeader mHeader = null; public SAMRecord(final SAMFileHeader header) { mHeader = header; } public String getReadName() { return mReadName; } /** * This method is preferred over getReadName().length(), because for BAMRecord * it may be faster. * @return length not including a null terminator. */ public int getReadNameLength() { return mReadName.length(); } public void setReadName(final String value) { mReadName = value; } /** * @return read sequence as a string of ACGTN=. */ public String getReadString() { final byte[] readBases = getReadBases(); if (readBases.length == 0) { return NULL_SEQUENCE_STRING; } return StringUtil.bytesToString(readBases); } public void setReadString(final String value) { if (NULL_SEQUENCE_STRING.equals(value)) { mReadBases = NULL_SEQUENCE; } else { final byte[] bases = StringUtil.stringToBytes(value); SAMUtils.normalizeBases(bases); setReadBases(bases); } } /** * Do not modify the value returned by this method. If you want to change the bases, create a new * byte[] and call setReadBases() or call setReadString(). * @return read sequence as ASCII bytes ACGTN=. */ public byte[] getReadBases() { return mReadBases; } public void setReadBases(final byte[] value) { mReadBases = value; } /** * This method is preferred over getReadBases().length, because for BAMRecord it may be faster. * @return number of bases in the read. */ public int getReadLength() { return getReadBases().length; } /** * @return Base qualities, encoded as a FASTQ string. */ public String getBaseQualityString() { if (Arrays.equals(NULL_QUALS, getBaseQualities())) { return NULL_QUALS_STRING; } return SAMUtils.phredToFastq(getBaseQualities()); } public void setBaseQualityString(final String value) { if (NULL_QUALS_STRING.equals(value)) { setBaseQualities(NULL_QUALS); } else { setBaseQualities(SAMUtils.fastqToPhred(value)); } } /** * Do not modify the value returned by this method. If you want to change the qualities, create a new * byte[] and call setBaseQualities() or call setBaseQualityString(). * @return Base qualities, as binary phred scores (not ASCII). */ public byte[] getBaseQualities() { return mBaseQualities; } public void setBaseQualities(final byte[] value) { mBaseQualities = value; } /** * If the original base quality scores have been store in the "OQ" tag will return the numeric * score as a byte[] */ public byte[] getOriginalBaseQualities() { final String oqString = (String) getAttribute("OQ"); if (oqString != null && oqString.length() > 0) { return SAMUtils.fastqToPhred(oqString); } else { return null; } } /** * Sets the original base quality scores into the "OQ" tag as a String. Supplied value should be * as phred-scaled numeric qualities. */ public void setOriginalBaseQualities(final byte[] oq) { setAttribute("OQ", SAMUtils.phredToFastq(oq)); } private static boolean hasReferenceName(final Integer referenceIndex, final String referenceName) { return (referenceIndex != null && referenceIndex != NO_ALIGNMENT_REFERENCE_INDEX) || !NO_ALIGNMENT_REFERENCE_NAME.equals(referenceName); } /** * @return true if this SAMRecord has a reference, either as a String or index (or both). */ private boolean hasReferenceName() { return hasReferenceName(mReferenceIndex, mReferenceName); } /** * @return true if this SAMRecord has a mate reference, either as a String or index (or both). */ private boolean hasMateReferenceName() { return hasReferenceName(mMateReferenceIndex, mMateReferenceName); } /** * @return Reference name, or null if record has no reference. */ public String getReferenceName() { return mReferenceName; } public void setReferenceName(final String value) { /* String.intern() is surprisingly expensive, so avoid it by looking up in sequence dictionary if possible */ if (NO_ALIGNMENT_REFERENCE_NAME.equals(value)) { mReferenceName = NO_ALIGNMENT_REFERENCE_NAME; mReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; return; } else if (mHeader != null) { int referenceIndex = mHeader.getSequenceIndex(value); if (referenceIndex != -1) { setReferenceIndex(referenceIndex); return; } } // Drop through from above if nothing done. mReferenceName = value.intern(); mReferenceIndex = null; } /** * @return index of the reference sequence for this read in the sequence dictionary, or -1 * if read has no reference sequence set, or if a String reference name is not found in the sequence index.. */ public Integer getReferenceIndex() { if (mReferenceIndex == null) { if (mReferenceName == null) { mReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else if (NO_ALIGNMENT_REFERENCE_NAME.equals(mReferenceName)) { mReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else { mReferenceIndex = mHeader.getSequenceIndex(mReferenceName); } } return mReferenceIndex; } /** * @param referenceIndex Must either equal -1 (indicating no reference), or exist in the sequence dictionary * in the header associated with this record. */ public void setReferenceIndex(final int referenceIndex) { mReferenceIndex = referenceIndex; if (mReferenceIndex == NO_ALIGNMENT_REFERENCE_INDEX) { mReferenceName = NO_ALIGNMENT_REFERENCE_NAME; } else { try { mReferenceName = mHeader.getSequence(referenceIndex).getSequenceName(); } catch (NullPointerException e) { throw new IllegalArgumentException("Reference index " + referenceIndex + " not found in sequence dictionary.", e); } } } /** * @return Mate reference name, or null if one is not assigned. */ public String getMateReferenceName() { return mMateReferenceName; } public void setMateReferenceName(final String mateReferenceName) { /* String.intern() is surprisingly expensive, so avoid it by looking up in sequence dictionary if possible */ if (NO_ALIGNMENT_REFERENCE_NAME.equals(mateReferenceName)) { mMateReferenceName = NO_ALIGNMENT_REFERENCE_NAME; mMateReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; return; } else if (mHeader != null) { int referenceIndex = mHeader.getSequenceIndex(mateReferenceName); if (referenceIndex != -1) { setMateReferenceIndex(referenceIndex); return; } } // Drop through from above if nothing done. this.mMateReferenceName = mateReferenceName.intern(); mMateReferenceIndex = null; } /** * @return index of the reference sequence for this read's mate in the sequence dictionary, or -1 * if mate has no reference sequence set. */ public Integer getMateReferenceIndex() { if (mMateReferenceIndex == null) { if (mMateReferenceName == null) { mMateReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else if (NO_ALIGNMENT_REFERENCE_NAME.equals(mMateReferenceName)){ mMateReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else { mMateReferenceIndex = mHeader.getSequenceIndex(mMateReferenceName); } } return mMateReferenceIndex; } /** * @param referenceIndex Must either equal -1 (indicating no reference), or exist in the sequence dictionary * in the header associated with this record. */ public void setMateReferenceIndex(final int referenceIndex) { mMateReferenceIndex = referenceIndex; if (mMateReferenceIndex == NO_ALIGNMENT_REFERENCE_INDEX) { mMateReferenceName = NO_ALIGNMENT_REFERENCE_NAME; } else { try { mMateReferenceName = mHeader.getSequence(referenceIndex).getSequenceName(); } catch (NullPointerException e) { throw new IllegalArgumentException("Reference index " + referenceIndex + " not found in sequence dictionary.", e); } } } /** * @return 1-based inclusive leftmost position of the clippped sequence, or 0 if there is no position. */ public int getAlignmentStart() { return mAlignmentStart; } /** * @param value 1-based inclusive leftmost position of the clippped sequence, or 0 if there is no position. */ public void setAlignmentStart(final int value) { mAlignmentStart = value; // Clear cached alignment end mAlignmentEnd = NO_ALIGNMENT_START; // Change to alignmentStart could change indexing bin setIndexingBin(null); } /** * @return 1-based inclusive rightmost position of the clippped sequence, or 0 read if unmapped. */ public int getAlignmentEnd() { if (getReadUnmappedFlag()) { return NO_ALIGNMENT_START; } else if (this.mAlignmentEnd == NO_ALIGNMENT_START) { this.mAlignmentEnd = mAlignmentStart + getCigar().getReferenceLength() - 1; } return this.mAlignmentEnd; } /** * @return the alignment start (1-based, inclusive) adjusted for clipped bases. For example if the read * has an alignment start of 100 but the first 4 bases were clipped (hard or soft clipped) * then this method will return 96. * * Invalid to call on an unmapped read. */ public int getUnclippedStart() { int pos = getAlignmentStart(); for (final CigarElement cig : getCigar().getCigarElements()) { final CigarOperator op = cig.getOperator(); if (op == CigarOperator.SOFT_CLIP || op == CigarOperator.HARD_CLIP) { pos -= cig.getLength(); } else { break; } } return pos; } /** * @return the alignment end (1-based, inclusive) adjusted for clipped bases. For example if the read * has an alignment end of 100 but the last 7 bases were clipped (hard or soft clipped) * then this method will return 107. * * Invalid to call on an unmapped read. */ public int getUnclippedEnd() { int pos = getAlignmentEnd(); final List<CigarElement> cigs = getCigar().getCigarElements(); for (int i=cigs.size() - 1; i>=0; --i) { final CigarElement cig = cigs.get(i); final CigarOperator op = cig.getOperator(); if (op == CigarOperator.SOFT_CLIP || op == CigarOperator.HARD_CLIP) { pos += cig.getLength(); } else { break; } } return pos; } /** * @return 1-based inclusive reference position of the unclippped sequence at a given offset, * or 0 if there is no position. * For example, given the sequence NNNAAACCCGGG, cigar 3S9M, and an alignment start of 1, * and a (1-based)offset 10 (start of GGG) it returns 7 (1-based offset starting after the soft clip. * For example: given the sequence AAACCCGGGTTT, cigar 4M1D6M, an alignment start of 1, * an offset of 4 returns reference position 4, an offset of 5 returns reference position 6. * Another example: given the sequence AAACCCGGGTTT, cigar 4M1I6M, an alignment start of 1, * an offset of 4 returns reference position 4, an offset of 5 returns 0. * @offset 1-based location within the unclipped sequence */ public int getReferencePositionAtReadPosition(final int offset) { if (offset == 0) return 0; for (final AlignmentBlock alignmentBlock : getAlignmentBlocks()) { if (CoordMath.getEnd(alignmentBlock.getReadStart(), alignmentBlock.getLength()) < offset) { continue; } else if (offset < alignmentBlock.getReadStart()) { return 0; } else { return alignmentBlock.getReferenceStart() + offset - alignmentBlock.getReadStart(); } } return 0; // offset not located in an alignment block } /** * Unsupported. This property is derived from alignment start and CIGAR. */ public void setAlignmentEnd(final int value) { throw new UnsupportedOperationException("Not supported: setAlignmentEnd"); } /** * @return 1-based inclusive leftmost position of the clippped mate sequence, or 0 if there is no position. */ public int getMateAlignmentStart() { return mMateAlignmentStart; } public void setMateAlignmentStart(final int mateAlignmentStart) { this.mMateAlignmentStart = mateAlignmentStart; } /** * @return insert size (difference btw 5' end of read & 5' end of mate), if possible, else 0. * Negative if mate maps to lower position than read. */ public int getInferredInsertSize() { return mInferredInsertSize; } public void setInferredInsertSize(final int inferredInsertSize) { this.mInferredInsertSize = inferredInsertSize; } /** * @return phred scaled mapping quality. 255 implies valid mapping but quality is hard to compute. */ public int getMappingQuality() { return mMappingQuality; } public void setMappingQuality(final int value) { mMappingQuality = value; } public String getCigarString() { if (mCigarString == null && getCigar() != null) { mCigarString = TextCigarCodec.getSingleton().encode(getCigar()); } return mCigarString; } public void setCigarString(final String value) { mCigarString = value; mCigar = null; mAlignmentBlocks = null; // Clear cached alignment end mAlignmentEnd = NO_ALIGNMENT_START; // Change to cigar could change alignmentEnd, and thus indexing bin setIndexingBin(null); } /** * Do not modify the value returned by this method. If you want to change the Cigar, create a new * Cigar and call setCigar() or call setCigarString() * @return Cigar object for the read, or null if there is none. */ public Cigar getCigar() { if (mCigar == null && mCigarString != null) { mCigar = TextCigarCodec.getSingleton().decode(mCigarString); if (getValidationStringency() != SAMFileReader.ValidationStringency.SILENT && !this.getReadUnmappedFlag()) { // Don't know line number, and don't want to force read name to be decoded. SAMUtils.processValidationErrors(validateCigar(-1L), -1L, getValidationStringency()); } } return mCigar; } /** * This method is preferred over getCigar().getNumElements(), because for BAMRecord it may be faster. * @return number of cigar elements (number + operator) in the cigar string. */ public int getCigarLength() { return getCigar().numCigarElements(); } public void setCigar(final Cigar cigar) { initializeCigar(cigar); // Change to cigar could change alignmentEnd, and thus indexing bin setIndexingBin(null); } /** * For setting the Cigar string when BAMRecord has decoded it. Use this rather than setCigar() * so that indexing bin doesn't get clobbered. */ protected void initializeCigar(final Cigar cigar) { this.mCigar = cigar; mCigarString = null; mAlignmentBlocks = null; // Clear cached alignment end mAlignmentEnd = NO_ALIGNMENT_START; } /** * Get the SAMReadGroupRecord for this SAMRecord. * @return The SAMReadGroupRecord from the SAMFileHeader for this SAMRecord, or null if * 1) this record has no RG tag, or 2) the header doesn't contain the read group with * the given ID. * @throws NullPointerException if this.getHeader() returns null. * @throws ClassCastException if RG tag does not have a String value. */ public SAMReadGroupRecord getReadGroup() { final String rgId = (String)getAttribute(SAMTagUtil.getSingleton().RG); if (rgId == null) { return null; } return getHeader().getReadGroup(rgId); } /** * It is preferrable to use the get*Flag() methods that handle the flag word symbolically. */ public int getFlags() { return mFlags; } public void setFlags(final int value) { mFlags = value; // Could imply change to readUnmapped flag, which could change indexing bin setIndexingBin(null); } /** * the read is paired in sequencing, no matter whether it is mapped in a pair. */ public boolean getReadPairedFlag() { return (mFlags & READ_PAIRED_FLAG) != 0; } private void requireReadPaired() { if (!getReadPairedFlag()) { throw new IllegalStateException("Inappropriate call if not paired read"); } } /** * the read is mapped in a proper pair (depends on the protocol, normally inferred during alignment). */ public boolean getProperPairFlag() { requireReadPaired(); return getProperPairFlagUnchecked(); } private boolean getProperPairFlagUnchecked() { return (mFlags & PROPER_PAIR_FLAG) != 0; } /** * the query sequence itself is unmapped. */ public boolean getReadUnmappedFlag() { return (mFlags & READ_UNMAPPED_FLAG) != 0; } /** * the mate is unmapped. */ public boolean getMateUnmappedFlag() { requireReadPaired(); return getMateUnmappedFlagUnchecked(); } private boolean getMateUnmappedFlagUnchecked() { return (mFlags & MATE_UNMAPPED_FLAG) != 0; } /** * strand of the query (false for forward; true for reverse strand). */ public boolean getReadNegativeStrandFlag() { return (mFlags & READ_STRAND_FLAG) != 0; } /** * strand of the mate (false for forward; true for reverse strand). */ public boolean getMateNegativeStrandFlag() { requireReadPaired(); return getMateNegativeStrandFlagUnchecked(); } private boolean getMateNegativeStrandFlagUnchecked() { return (mFlags & MATE_STRAND_FLAG) != 0; } /** * the read is the first read in a pair. */ public boolean getFirstOfPairFlag() { requireReadPaired(); return getFirstOfPairFlagUnchecked(); } private boolean getFirstOfPairFlagUnchecked() { return (mFlags & FIRST_OF_PAIR_FLAG) != 0; } /** * the read is the second read in a pair. */ public boolean getSecondOfPairFlag() { requireReadPaired(); return getSecondOfPairFlagUnchecked(); } private boolean getSecondOfPairFlagUnchecked() { return (mFlags & SECOND_OF_PAIR_FLAG) != 0; } /** * the alignment is not primary (a read having split hits may have multiple primary alignment records). */ public boolean getNotPrimaryAlignmentFlag() { return (mFlags & NOT_PRIMARY_ALIGNMENT_FLAG) != 0; } /** * the read fails platform/vendor quality checks. */ public boolean getReadFailsVendorQualityCheckFlag() { return (mFlags & READ_FAILS_VENDOR_QUALITY_CHECK_FLAG) != 0; } /** * the read is either a PCR duplicate or an optical duplicate. */ public boolean getDuplicateReadFlag() { return (mFlags & DUPLICATE_READ_FLAG) != 0; } /** * the read is paired in sequencing, no matter whether it is mapped in a pair. */ public void setReadPairedFlag(final boolean flag) { setFlag(flag, READ_PAIRED_FLAG); } /** * the read is mapped in a proper pair (depends on the protocol, normally inferred during alignment). */ public void setProperPairFlag(final boolean flag) { setFlag(flag, PROPER_PAIR_FLAG); } /** * the query sequence itself is unmapped. This method name is misspelled. * Use setReadUnmappedFlag instead. * @deprecated */ public void setReadUmappedFlag(final boolean flag) { setReadUnmappedFlag(flag); } /** * the query sequence itself is unmapped. */ public void setReadUnmappedFlag(final boolean flag) { setFlag(flag, READ_UNMAPPED_FLAG); // Change to readUnmapped could change indexing bin setIndexingBin(null); } /** * the mate is unmapped. */ public void setMateUnmappedFlag(final boolean flag) { setFlag(flag, MATE_UNMAPPED_FLAG); } /** * strand of the query (false for forward; true for reverse strand). */ public void setReadNegativeStrandFlag(final boolean flag) { setFlag(flag, READ_STRAND_FLAG); } /** * strand of the mate (false for forward; true for reverse strand). */ public void setMateNegativeStrandFlag(final boolean flag) { setFlag(flag, MATE_STRAND_FLAG); } /** * the read is the first read in a pair. */ public void setFirstOfPairFlag(final boolean flag) { setFlag(flag, FIRST_OF_PAIR_FLAG); } /** * the read is the second read in a pair. */ public void setSecondOfPairFlag(final boolean flag) { setFlag(flag, SECOND_OF_PAIR_FLAG); } /** * the alignment is not primary (a read having split hits may have multiple primary alignment records). */ public void setNotPrimaryAlignmentFlag(final boolean flag) { setFlag(flag, NOT_PRIMARY_ALIGNMENT_FLAG); } /** * the read fails platform/vendor quality checks. */ public void setReadFailsVendorQualityCheckFlag(final boolean flag) { setFlag(flag, READ_FAILS_VENDOR_QUALITY_CHECK_FLAG); } /** * the read is either a PCR duplicate or an optical duplicate. */ public void setDuplicateReadFlag(final boolean flag) { setFlag(flag, DUPLICATE_READ_FLAG); } private void setFlag(final boolean flag, final int bit) { if (flag) { mFlags |= bit; } else { mFlags &= ~bit; } } public SAMFileReader.ValidationStringency getValidationStringency() { return mValidationStringency; } /** * Control validation of lazily-decoded elements. */ public void setValidationStringency(final SAMFileReader.ValidationStringency validationStringency) { this.mValidationStringency = validationStringency; } /** * Get the value for a SAM tag. * WARNING: Some value types (e.g. byte[]) are mutable. It is dangerous to change one of these values in * place, because some SAMRecord implementations keep track of when attributes have been changed. If you * want to change an attribute value, call setAttribute() to replace the value. * * @param tag Two-character tag name. * @return Appropriately typed tag value, or null if the requested tag is not present. */ public Object getAttribute(final String tag) { return getAttribute(SAMTagUtil.getSingleton().makeBinaryTag(tag)); } /** * Get the tag value and attempt to coerce it into the requested type. * @param tag The requested tag. * @return The value of a tag, converted into an Integer if possible. * @throws RuntimeException If the value is not an integer type, or will not fit in an Integer. */ public Integer getIntegerAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof Integer) { return (Integer)val; } if (!(val instanceof Number)) { throw new RuntimeException("Value for tag " + tag + " is not Number: " + val.getClass()); } final long longVal = ((Number)val).longValue(); if (longVal < Integer.MIN_VALUE || longVal > Integer.MAX_VALUE) { throw new RuntimeException("Value for tag " + tag + " is not in Integer range: " + longVal); } return (int)longVal; } /** * Get the tag value and attempt to coerce it into the requested type. * @param tag The requested tag. * @return The value of a tag, converted into a Short if possible. * @throws RuntimeException If the value is not an integer type, or will not fit in a Short. */ public Short getShortAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof Short) { return (Short)val; } if (!(val instanceof Number)) { throw new RuntimeException("Value for tag " + tag + " is not Number: " + val.getClass()); } final long longVal = ((Number)val).longValue(); if (longVal < Short.MIN_VALUE || longVal > Short.MAX_VALUE) { throw new RuntimeException("Value for tag " + tag + " is not in Short range: " + longVal); } return (short)longVal; } /** * Get the tag value and attempt to coerce it into the requested type. * @param tag The requested tag. * @return The value of a tag, converted into a Byte if possible. * @throws RuntimeException If the value is not an integer type, or will not fit in a Byte. */ public Byte getByteAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof Byte) { return (Byte)val; } if (!(val instanceof Number)) { throw new RuntimeException("Value for tag " + tag + " is not Number: " + val.getClass()); } final long longVal = ((Number)val).longValue(); if (longVal < Byte.MIN_VALUE || longVal > Byte.MAX_VALUE) { throw new RuntimeException("Value for tag " + tag + " is not in Short range: " + longVal); } return (byte)longVal; } public String getStringAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof String) { return (String)val; } throw new SAMException("Value for tag " + tag + " is not a String: " + val.getClass()); } public Character getCharacterAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof Character) { return (Character)val; } throw new SAMException("Value for tag " + tag + " is not a Character: " + val.getClass()); } public Float getFloatAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof Float) { return (Float)val; } throw new SAMException("Value for tag " + tag + " is not a Float: " + val.getClass()); } /** Will work for signed byte array, unsigned byte array, or old-style hex array */ public byte[] getByteArrayAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof byte[]) { return (byte[])val; } throw new SAMException("Value for tag " + tag + " is not a byte[]: " + val.getClass()); } public byte[] getUnsignedByteArrayAttribute(final String tag) { final byte[] ret = getByteArrayAttribute(tag); if (ret != null) requireUnsigned(tag); return ret; } /** Will work for signed byte array or old-style hex array */ public byte[] getSignedByteArrayAttribute(final String tag) { final byte[] ret = getByteArrayAttribute(tag); if (ret != null) requireSigned(tag); return ret; } public short[] getUnsignedShortArrayAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof short[]) { requireUnsigned(tag); return (short[]) val; } throw new SAMException("Value for tag " + tag + " is not a short[]: " + val.getClass()); } public short[] getSignedShortArrayAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof short[]) { requireSigned(tag); return (short[]) val; } throw new SAMException("Value for tag " + tag + " is not a short[]: " + val.getClass()); } public int[] getUnsignedIntArrayAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof int[]) { requireUnsigned(tag); return (int[]) val; } throw new SAMException("Value for tag " + tag + " is not a int[]: " + val.getClass()); } public int[] getSignedIntArrayAttribute(final String tag) { final Object val = getAttribute(tag); if (val == null) return null; if (val instanceof int[]) { requireSigned(tag); return (int[]) val; } throw new SAMException("Value for tag " + tag + " is not a int[]: " + val.getClass()); } public float[] getFloatArrayAttribute(final String tag) { final Object val = getAttribute(tag); if (val != null && !(val instanceof float[])) { throw new SAMException("Value for tag " + tag + " is not a float[]: " + val.getClass()); } return (float[]) val; } /** * @return True if this tag is an unsigned array, else false. * @throws SAMException if the tag is not present. */ public boolean isUnsignedArrayAttribute(final String tag) { final SAMBinaryTagAndValue tmp = this.mAttributes.find(SAMTagUtil.getSingleton().makeBinaryTag(tag)); if (tmp != null) return tmp.isUnsignedArray(); throw new SAMException("Tag " + tag + " is not present in this SAMRecord"); } private void requireSigned(final String tag) { if (isUnsignedArrayAttribute(tag)) throw new SAMException("Value for tag " + tag + " is not signed"); } private void requireUnsigned(final String tag) { if (!isUnsignedArrayAttribute(tag)) throw new SAMException("Value for tag " + tag + " is not unsigned"); } /** * @see SAMRecord#getAttribute(java.lang.String) * @param tag Binary representation of a 2-char String tag as created by SAMTagUtil. */ public Object getAttribute(final short tag) { if (this.mAttributes == null) return null; else { final SAMBinaryTagAndValue tmp = this.mAttributes.find(tag); if (tmp != null) return tmp.value; else return null; } } /** * Set a named attribute onto the SAMRecord. Passing a null value causes the attribute to be cleared. * @param tag two-character tag name. See http://samtools.sourceforge.net/SAM1.pdf for standard and user-defined tags. * @param value Supported types are String, Char, Integer, Float, byte[], short[]. int[], float[]. * If value == null, tag is cleared. * * Byte and Short are allowed but discouraged. If written to a SAM file, these will be converted to Integer, * whereas if written to BAM, getAttribute() will return as Byte or Short, respectively. * * Long with value between 0 and MAX_UINT is allowed for BAM but discouraged. Attempting to write such a value * to SAM will cause an exception to be thrown. * * To set unsigned byte[], unsigned short[] or unsigned int[] (which is discouraged because of poor Java language * support), setUnsignedArrayAttribute() must be used instead of this method. * * String values are not validated to ensure that they conform to SAM spec. */ public void setAttribute(final String tag, final Object value) { if (value != null && value.getClass().isArray() && Array.getLength(value) == 0) { throw new IllegalArgumentException("Empty value passed for tag " + tag); } setAttribute(SAMTagUtil.getSingleton().makeBinaryTag(tag), value); } /** * Because Java does not support unsigned integer types, we think it is a bad idea to encode them in SAM * files. If you must do so, however, you must call this method rather than setAttribute, because calling * this method is the way to indicate that, e.g. a short array should be interpreted as unsigned shorts. * @param value must be one of byte[], short[], int[] */ public void setUnsignedArrayAttribute(final String tag, final Object value) { if (!value.getClass().isArray()) { throw new IllegalArgumentException("Non-array passed to setUnsignedArrayAttribute for tag " + tag); } if (Array.getLength(value) == 0) { throw new IllegalArgumentException("Empty array passed to setUnsignedArrayAttribute for tag " + tag); } setAttribute(SAMTagUtil.getSingleton().makeBinaryTag(tag), value, true); } /** * @see net.sf.samtools.SAMRecord#setAttribute(java.lang.String, java.lang.Object) * @param tag Binary representation of a 2-char String tag as created by SAMTagUtil. */ protected void setAttribute(final short tag, final Object value) { setAttribute(tag, value, false); } protected void setAttribute(final short tag, final Object value, boolean isUnsignedArray) { if (value != null && !(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof String || value instanceof Character || value instanceof Float || value instanceof byte[] || value instanceof short[] || value instanceof int[] || value instanceof float[])) { throw new SAMException("Attribute type " + value.getClass() + " not supported. Tag: " + SAMTagUtil.getSingleton().makeStringTag(tag)); } if (value == null) { if (this.mAttributes != null) this.mAttributes = this.mAttributes.remove(tag); } else { final SAMBinaryTagAndValue tmp; if(!isUnsignedArray) { tmp = new SAMBinaryTagAndValue(tag, value); } else { if (!value.getClass().isArray() || value instanceof float[]) { throw new SAMException("Attribute type " + value.getClass() + " cannot be encoded as an unsigned array. Tag: " + SAMTagUtil.getSingleton().makeStringTag(tag)); } tmp = new SAMBinaryTagAndUnsignedArrayValue(tag, value); } if (this.mAttributes == null) this.mAttributes = tmp; else this.mAttributes = this.mAttributes.insert(tmp); } } /** * Removes all attributes. */ public void clearAttributes() { mAttributes = null; } /** * Replace any existing attributes with the given linked item. */ protected void setAttributes(final SAMBinaryTagAndValue attributes) { mAttributes = attributes; } /** * @return Pointer to the first of the tags. Returns null if there are no tags. */ protected SAMBinaryTagAndValue getBinaryAttributes() { return mAttributes; } /** * Tag name and value of an attribute, for getAttributes() method. */ public static class SAMTagAndValue { public final String tag; public final Object value; public SAMTagAndValue(final String tag, final Object value) { this.tag = tag; this.value = value; } } /** * @return list of {tag, value} tuples */ public List<SAMTagAndValue> getAttributes() { SAMBinaryTagAndValue binaryAttributes = getBinaryAttributes(); final List<SAMTagAndValue> ret = new ArrayList<SAMTagAndValue>(); while (binaryAttributes != null) { ret.add(new SAMTagAndValue(SAMTagUtil.getSingleton().makeStringTag(binaryAttributes.tag), binaryAttributes.value)); binaryAttributes = binaryAttributes.getNext(); } return ret; } Integer getIndexingBin() { return mIndexingBin; } /** * Used internally when writing BAMRecords. * @param mIndexingBin c.f. http://samtools.sourceforge.net/SAM1.pdf */ void setIndexingBin(final Integer mIndexingBin) { this.mIndexingBin = mIndexingBin; } /** * Does not change state of this. * @return indexing bin based on alignment start & end. */ int computeIndexingBin() { // reg2bin has zero-based, half-open API final int alignmentStart = getAlignmentStart()-1; int alignmentEnd = getAlignmentEnd(); if (alignmentEnd <= 0) { // If alignment end cannot be determined (e.g. because this read is not really aligned), // then treat this as a one base alignment for indexing purposes. alignmentEnd = alignmentStart + 1; } return SAMUtils.reg2bin(alignmentStart, alignmentEnd); } public SAMFileHeader getHeader() { return mHeader; } /** * Setting header into SAMRecord facilitates conversion btw reference sequence names and indices * @param header contains sequence dictionary for this SAMRecord */ public void setHeader(final SAMFileHeader header) { this.mHeader = header; } /** * If this record has a valid binary representation of the variable-length portion of a binary record stored, * return that byte array, otherwise return null. This will never be true for SAMRecords. It will be true * for BAMRecords that have not been eagerDecoded(), and for which none of the data in the variable-length * portion has been changed. */ public byte[] getVariableBinaryRepresentation() { return null; } /** * Depending on the concrete implementation, the binary file size of attributes may be known without * computing them all. * @return binary file size of attribute, if known, else -1 */ public int getAttributesBinarySize() { return -1; } /** * * @return String representation of this. * @deprecated This method is not guaranteed to return a valid SAM text representation of the SAMRecord. * To get standard SAM text representation, use net.sf.samtools.SAMRecord#getSAMString(). */ public String format() { final StringBuilder buffer = new StringBuilder(); addField(buffer, getReadName(), null, null); addField(buffer, getFlags(), null, null); addField(buffer, getReferenceName(), null, "*"); addField(buffer, getAlignmentStart(), 0, "*"); addField(buffer, getMappingQuality(), 0, "0"); addField(buffer, getCigarString(), null, "*"); addField(buffer, getMateReferenceName(), null, "*"); addField(buffer, getMateAlignmentStart(), 0, "*"); addField(buffer, getInferredInsertSize(), 0, "*"); addField(buffer, getReadString(), null, "*"); addField(buffer, getBaseQualityString(), null, "*"); if (mAttributes != null) { SAMBinaryTagAndValue entry = getBinaryAttributes(); while (entry != null) { addField(buffer, formatTagValue(entry.tag, entry.value)); entry = entry.getNext(); } } return buffer.toString(); } private void addField(final StringBuilder buffer, final Object value, final Object defaultValue, final String defaultString) { if (safeEquals(value, defaultValue)) { addField(buffer, defaultString); } else if (value == null) { addField(buffer, ""); } else { addField(buffer, value.toString()); } } private void addField(final StringBuilder buffer, final String field) { if (buffer.length() > 0) { buffer.append('\t'); } buffer.append(field); } private String formatTagValue(final short tag, final Object value) { final String tagString = SAMTagUtil.getSingleton().makeStringTag(tag); if (value == null || value instanceof String) { return tagString + ":Z:" + value; } else if (value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte) { return tagString + ":i:" + value; } else if (value instanceof Character) { return tagString + ":A:" + value; } else if (value instanceof Float) { return tagString + ":f:" + value; } else if (value instanceof byte[]) { return tagString + ":H:" + StringUtil.bytesToHexString((byte[]) value); } else { throw new RuntimeException("Unexpected value type for tag " + tagString + ": " + value + " of class " + value.getClass().getName()); } } private boolean safeEquals(final Object o1, final Object o2) { if (o1 == o2) { return true; } else if (o1 == null || o2 == null) { return false; } else { return o1.equals(o2); } } /** * Force all lazily-initialized data members to be initialized. If a subclass overrides this method, * typically it should also call super method. */ protected void eagerDecode() { getCigar(); getCigarString(); } /** * Returns blocks of the read sequence that have been aligned directly to the * reference sequence. Note that clipped portions of the read and inserted and * deleted bases (vs. the reference) are not represented in the alignment blocks. */ public List<AlignmentBlock> getAlignmentBlocks() { if (this.mAlignmentBlocks != null) return this.mAlignmentBlocks; final Cigar cigar = getCigar(); if (cigar == null) return Collections.emptyList(); final List<AlignmentBlock> alignmentBlocks = new ArrayList<AlignmentBlock>(); int readBase = 1; int refBase = getAlignmentStart(); for (final CigarElement e : cigar.getCigarElements()) { switch (e.getOperator()) { case H : break; // ignore hard clips case P : break; // ignore pads case S : readBase += e.getLength(); break; // soft clip read bases case N : refBase += e.getLength(); break; // reference skip case D : refBase += e.getLength(); break; case I : readBase += e.getLength(); break; case M : case EQ : case X : final int length = e.getLength(); alignmentBlocks.add(new AlignmentBlock(readBase, refBase, length)); readBase += length; refBase += length; break; default : throw new IllegalStateException("Case statement didn't deal with cigar op: " + e.getOperator()); } } this.mAlignmentBlocks = Collections.unmodifiableList(alignmentBlocks); return this.mAlignmentBlocks; } /** * Run all validations of CIGAR. These include validation that the CIGAR makes sense independent of * placement, plus validation that CIGAR + placement yields all bases with M operator within the range of the reference. * @param recordNumber For error reporting. -1 if not known. * @return List of errors, or null if no errors. */ public List<SAMValidationError> validateCigar(final long recordNumber) { List<SAMValidationError> ret = null; if (getValidationStringency() != SAMFileReader.ValidationStringency.SILENT && !this.getReadUnmappedFlag()) { // Don't know line number, and don't want to force read name to be decoded. ret = getCigar().isValid(getReadName(), recordNumber); if (getReferenceIndex() != NO_ALIGNMENT_REFERENCE_INDEX) { final SAMSequenceRecord sequence = getHeader().getSequence(getReferenceIndex()); final int referenceSequenceLength = sequence.getSequenceLength(); for (final AlignmentBlock alignmentBlock : getAlignmentBlocks()) { if (alignmentBlock.getReferenceStart() + alignmentBlock.getLength() - 1 > referenceSequenceLength) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.CIGAR_MAPS_OFF_REFERENCE, "CIGAR M operator maps off end of reference", getReadName(), recordNumber)); break; } } } } return ret; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof SAMRecord)) return false; final SAMRecord samRecord = (SAMRecord) o; // First check all the elements that do not require decoding if (mAlignmentStart != samRecord.mAlignmentStart) return false; if (mFlags != samRecord.mFlags) return false; if (mInferredInsertSize != samRecord.mInferredInsertSize) return false; if (mMappingQuality != samRecord.mMappingQuality) return false; if (mMateAlignmentStart != samRecord.mMateAlignmentStart) return false; if (mIndexingBin != null ? !mIndexingBin.equals(samRecord.mIndexingBin) : samRecord.mIndexingBin != null) return false; if (mMateReferenceIndex != null ? !mMateReferenceIndex.equals(samRecord.mMateReferenceIndex) : samRecord.mMateReferenceIndex != null) return false; if (mReferenceIndex != null ? !mReferenceIndex.equals(samRecord.mReferenceIndex) : samRecord.mReferenceIndex != null) return false; eagerDecode(); samRecord.eagerDecode(); if (mReadName != null ? !mReadName.equals(samRecord.mReadName) : samRecord.mReadName != null) return false; if (mAttributes != null ? !mAttributes.equals(samRecord.mAttributes) : samRecord.mAttributes != null) return false; if (!Arrays.equals(mBaseQualities, samRecord.mBaseQualities)) return false; if (mCigar != null ? !mCigar.equals(samRecord.mCigar) : samRecord.mCigar != null) return false; if (mMateReferenceName != null ? !mMateReferenceName.equals(samRecord.mMateReferenceName) : samRecord.mMateReferenceName != null) return false; if (!Arrays.equals(mReadBases, samRecord.mReadBases)) return false; if (mReferenceName != null ? !mReferenceName.equals(samRecord.mReferenceName) : samRecord.mReferenceName != null) return false; return true; } @Override public int hashCode() { eagerDecode(); int result = mReadName != null ? mReadName.hashCode() : 0; result = 31 * result + (mReadBases != null ? Arrays.hashCode(mReadBases) : 0); result = 31 * result + (mBaseQualities != null ? Arrays.hashCode(mBaseQualities) : 0); result = 31 * result + (mReferenceName != null ? mReferenceName.hashCode() : 0); result = 31 * result + mAlignmentStart; result = 31 * result + mMappingQuality; result = 31 * result + (mCigarString != null ? mCigarString.hashCode() : 0); result = 31 * result + mFlags; result = 31 * result + (mMateReferenceName != null ? mMateReferenceName.hashCode() : 0); result = 31 * result + mMateAlignmentStart; result = 31 * result + mInferredInsertSize; result = 31 * result + (mAttributes != null ? mAttributes.hashCode() : 0); result = 31 * result + (mReferenceIndex != null ? mReferenceIndex.hashCode() : 0); result = 31 * result + (mMateReferenceIndex != null ? mMateReferenceIndex.hashCode() : 0); result = 31 * result + (mIndexingBin != null ? mIndexingBin.hashCode() : 0); return result; } /** * Perform various validations of SAMRecord. * Note that this method deliberately returns null rather than Collections.emptyList() if there * are no validation errors, because callers tend to assume that if a non-null list is returned, it is modifiable. * @return null if valid. If invalid, returns a list of error messages. */ public List<SAMValidationError> isValid() { // ret is only instantiate if there are errors to report, in order to reduce GC in the typical case // in which everything is valid. It's ugly, but more efficient. ArrayList<SAMValidationError> ret = null; if (!getReadPairedFlag()) { if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } if (getMateUnmappedFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mate unmapped flag should not be set for unpaired read.", getReadName())); } if (getMateNegativeStrandFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_NEG_STRAND, "Mate negative strand flag should not be set for unpaired read.", getReadName())); } if (getFirstOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_FIRST_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); } if (getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); - ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_SECOND_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); + ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_SECOND_OF_PAIR, "Second of pair flag should not be set for unpaired read.", getReadName())); } if (getMateReferenceIndex() != NO_ALIGNMENT_REFERENCE_INDEX) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MATE_REF_INDEX, "MRNM should not be set for unpaired read.", getReadName())); } } else { final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mMateReferenceIndex, mMateReferenceName, getMateAlignmentStart(), true); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (!hasMateReferenceName() && !getMateUnmappedFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mapped mate should have mate reference name", getReadName())); } if (!getFirstOfPairFlagUnchecked() && !getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.PAIRED_READ_NOT_MARKED_AS_FIRST_OR_SECOND, "Paired read should be marked as first of pair or second of pair.", getReadName())); } /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getMateUnmappedFlag() && getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } */ } if (getInferredInsertSize() > MAX_INSERT_SIZE || getInferredInsertSize() < -MAX_INSERT_SIZE) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INSERT_SIZE, "Insert size out of range", getReadName())); } if (getReadUnmappedFlag()) { if (getNotPrimaryAlignmentFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_NOT_PRIM_ALIGNMENT, "Not primary alignment flag should not be set for unmapped read.", getReadName())); } if (getMappingQuality() != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be 0 for unmapped read.", getReadName())); } /* non-empty CIGAR on unmapped read is now allowed, because there are special reads when SAM is used to store assembly. */ /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unmapped read.", getReadName())); } */ } else { if (getMappingQuality() >= 256) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be < 256.", getReadName())); } if (getCigarLength() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR should have > zero elements for mapped read.", getReadName())); /* todo - will uncomment once unit tests are added } else if (getCigar().getReadLength() != getReadLength()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR read length " + getCigar().getReadLength() + " doesn't match read length " + getReadLength(), getReadName())); */ } if (getHeader().getSequenceDictionary().size() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISSING_SEQUENCE_DICTIONARY, "Empty sequence dictionary.", getReadName())); } if (!hasReferenceName()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_READ_UNMAPPED, "Mapped read should have valid reference name", getReadName())); } /* Oops! We know this is broken in older BAM files, so this having this validation will cause all sorts of problems! if (getIndexingBin() != null && getIndexingBin() != computeIndexingBin()) { ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INDEXING_BIN, "Indexing bin (" + getIndexingBin() + ") does not agree with computed value (" + computeIndexingBin() + ")", getReadName())); } */ } // Validate the RG ID is found in header final String rgId = (String)getAttribute(SAMTagUtil.getSingleton().RG); if (rgId != null && getHeader().getReadGroup(rgId) == null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.READ_GROUP_NOT_FOUND, "RG ID on SAMRecord not found in header: " + rgId, getReadName())); } final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mReferenceIndex, mReferenceName, getAlignmentStart(), false); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (this.getReadLength() == 0 && !this.getNotPrimaryAlignmentFlag()) { Object fz = getAttribute(SAMTagUtil.getSingleton().FZ); if (fz == null) { String cq = (String)getAttribute(SAMTagUtil.getSingleton().CQ); String cs = (String)getAttribute(SAMTagUtil.getSingleton().CS); if (cq == null || cq.length() == 0 || cs == null || cs.length() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.EMPTY_READ, "Zero-length read without FZ, CS or CQ tag", getReadName())); } else if (!getReadUnmappedFlag()) { boolean hasIndel = false; for (CigarElement cigarElement : getCigar().getCigarElements()) { if (cigarElement.getOperator() == CigarOperator.DELETION || cigarElement.getOperator() == CigarOperator.INSERTION) { hasIndel = true; break; } } if (!hasIndel) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.EMPTY_READ, "Colorspace read with zero-length bases but no indel", getReadName())); } } } } if (this.getReadLength() != getBaseQualities().length && !Arrays.equals(getBaseQualities(), NULL_QUALS)) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISMATCH_READ_LENGTH_AND_QUALS_LENGTH, "Read length does not match quals length", getReadName())); } if (ret == null || ret.size() == 0) { return null; } return ret; } /** * Gets the source of this SAM record -- both the reader that retrieved the record and the position on disk from * whence it came. * @return The file source. Note that the reader will be null if not activated using SAMFileReader.enableFileSource(). */ public SAMFileSource getFileSource() { return mFileSource; } /** * Sets a marker providing the source reader for this file and the position in the file from which the read originated. * @param fileSource source of the given file. */ protected void setFileSource(final SAMFileSource fileSource) { mFileSource = fileSource; } private List<SAMValidationError> isValidReferenceIndexAndPosition(final Integer referenceIndex, final String referenceName, final int alignmentStart, final boolean isMate) { final boolean hasReference = hasReferenceName(referenceIndex, referenceName); // ret is only instantiate if there are errors to report, in order to reduce GC in the typical case // in which everything is valid. It's ugly, but more efficient. ArrayList<SAMValidationError> ret = null; if (!hasReference) { if (alignmentStart != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_ALIGNMENT_START, buildMessage("Alignment start should be 0 because reference name = *.", isMate), getReadName())); } } else { if (alignmentStart == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_ALIGNMENT_START, buildMessage("Alignment start should != 0 because reference name != *.", isMate), getReadName())); } if (getHeader().getSequenceDictionary().size() > 0) { final SAMSequenceRecord sequence = (referenceIndex != null? getHeader().getSequence(referenceIndex): getHeader().getSequence(referenceName)); if (sequence == null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_REFERENCE_INDEX, buildMessage("Reference sequence not found in sequence dictionary.", isMate), getReadName())); } else { if (alignmentStart > sequence.getSequenceLength()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_ALIGNMENT_START, buildMessage("Alignment start (" + alignmentStart + ") must be <= reference sequence length (" + sequence.getSequenceLength() + ") on reference " + sequence.getSequenceName(), isMate), getReadName())); } } } } return ret; } private String buildMessage(final String baseMessage, final boolean isMate) { return isMate ? "Mate " + baseMessage : baseMessage; } /** * Note that this does a shallow copy of everything, except for the attribute list, for which a copy of the list * is made, but the attributes themselves are copied by reference. This should be safe because callers should * never modify a mutable value returned by any of the get() methods anyway. */ @Override public Object clone() throws CloneNotSupportedException { final SAMRecord newRecord = (SAMRecord)super.clone(); if (mAttributes != null) { newRecord.mAttributes = this.mAttributes.copy(); } return newRecord; } /** Simple toString() that gives a little bit of useful info about the read. */ @Override public String toString() { StringBuilder builder = new StringBuilder(64); builder.append(getReadName()); if (getReadPairedFlag()) { if (getFirstOfPairFlag()) { builder.append(" 1/2"); } else { builder.append(" 2/2"); } } builder.append(" "); builder.append(String.valueOf(getReadLength())); builder.append("b"); if (getReadUnmappedFlag()) { builder.append(" unmapped read."); } else { builder.append(" aligned read."); } return builder.toString(); } /** Returns the record in the SAM line-based text format. Fields are separated by '\t' characters, and the String is terminated by '\n'. */ public String getSAMString() { return SAMTextWriter.getSAMString(this); } }
true
true
public List<SAMValidationError> isValid() { // ret is only instantiate if there are errors to report, in order to reduce GC in the typical case // in which everything is valid. It's ugly, but more efficient. ArrayList<SAMValidationError> ret = null; if (!getReadPairedFlag()) { if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } if (getMateUnmappedFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mate unmapped flag should not be set for unpaired read.", getReadName())); } if (getMateNegativeStrandFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_NEG_STRAND, "Mate negative strand flag should not be set for unpaired read.", getReadName())); } if (getFirstOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_FIRST_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); } if (getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_SECOND_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); } if (getMateReferenceIndex() != NO_ALIGNMENT_REFERENCE_INDEX) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MATE_REF_INDEX, "MRNM should not be set for unpaired read.", getReadName())); } } else { final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mMateReferenceIndex, mMateReferenceName, getMateAlignmentStart(), true); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (!hasMateReferenceName() && !getMateUnmappedFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mapped mate should have mate reference name", getReadName())); } if (!getFirstOfPairFlagUnchecked() && !getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.PAIRED_READ_NOT_MARKED_AS_FIRST_OR_SECOND, "Paired read should be marked as first of pair or second of pair.", getReadName())); } /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getMateUnmappedFlag() && getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } */ } if (getInferredInsertSize() > MAX_INSERT_SIZE || getInferredInsertSize() < -MAX_INSERT_SIZE) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INSERT_SIZE, "Insert size out of range", getReadName())); } if (getReadUnmappedFlag()) { if (getNotPrimaryAlignmentFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_NOT_PRIM_ALIGNMENT, "Not primary alignment flag should not be set for unmapped read.", getReadName())); } if (getMappingQuality() != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be 0 for unmapped read.", getReadName())); } /* non-empty CIGAR on unmapped read is now allowed, because there are special reads when SAM is used to store assembly. */ /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unmapped read.", getReadName())); } */ } else { if (getMappingQuality() >= 256) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be < 256.", getReadName())); } if (getCigarLength() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR should have > zero elements for mapped read.", getReadName())); /* todo - will uncomment once unit tests are added } else if (getCigar().getReadLength() != getReadLength()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR read length " + getCigar().getReadLength() + " doesn't match read length " + getReadLength(), getReadName())); */ } if (getHeader().getSequenceDictionary().size() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISSING_SEQUENCE_DICTIONARY, "Empty sequence dictionary.", getReadName())); } if (!hasReferenceName()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_READ_UNMAPPED, "Mapped read should have valid reference name", getReadName())); } /* Oops! We know this is broken in older BAM files, so this having this validation will cause all sorts of problems! if (getIndexingBin() != null && getIndexingBin() != computeIndexingBin()) { ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INDEXING_BIN, "Indexing bin (" + getIndexingBin() + ") does not agree with computed value (" + computeIndexingBin() + ")", getReadName())); } */ } // Validate the RG ID is found in header final String rgId = (String)getAttribute(SAMTagUtil.getSingleton().RG); if (rgId != null && getHeader().getReadGroup(rgId) == null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.READ_GROUP_NOT_FOUND, "RG ID on SAMRecord not found in header: " + rgId, getReadName())); } final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mReferenceIndex, mReferenceName, getAlignmentStart(), false); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (this.getReadLength() == 0 && !this.getNotPrimaryAlignmentFlag()) { Object fz = getAttribute(SAMTagUtil.getSingleton().FZ); if (fz == null) { String cq = (String)getAttribute(SAMTagUtil.getSingleton().CQ); String cs = (String)getAttribute(SAMTagUtil.getSingleton().CS); if (cq == null || cq.length() == 0 || cs == null || cs.length() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.EMPTY_READ, "Zero-length read without FZ, CS or CQ tag", getReadName())); } else if (!getReadUnmappedFlag()) { boolean hasIndel = false; for (CigarElement cigarElement : getCigar().getCigarElements()) { if (cigarElement.getOperator() == CigarOperator.DELETION || cigarElement.getOperator() == CigarOperator.INSERTION) { hasIndel = true; break; } } if (!hasIndel) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.EMPTY_READ, "Colorspace read with zero-length bases but no indel", getReadName())); } } } } if (this.getReadLength() != getBaseQualities().length && !Arrays.equals(getBaseQualities(), NULL_QUALS)) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISMATCH_READ_LENGTH_AND_QUALS_LENGTH, "Read length does not match quals length", getReadName())); } if (ret == null || ret.size() == 0) { return null; } return ret; }
public List<SAMValidationError> isValid() { // ret is only instantiate if there are errors to report, in order to reduce GC in the typical case // in which everything is valid. It's ugly, but more efficient. ArrayList<SAMValidationError> ret = null; if (!getReadPairedFlag()) { if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } if (getMateUnmappedFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mate unmapped flag should not be set for unpaired read.", getReadName())); } if (getMateNegativeStrandFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_NEG_STRAND, "Mate negative strand flag should not be set for unpaired read.", getReadName())); } if (getFirstOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_FIRST_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); } if (getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_SECOND_OF_PAIR, "Second of pair flag should not be set for unpaired read.", getReadName())); } if (getMateReferenceIndex() != NO_ALIGNMENT_REFERENCE_INDEX) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MATE_REF_INDEX, "MRNM should not be set for unpaired read.", getReadName())); } } else { final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mMateReferenceIndex, mMateReferenceName, getMateAlignmentStart(), true); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (!hasMateReferenceName() && !getMateUnmappedFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mapped mate should have mate reference name", getReadName())); } if (!getFirstOfPairFlagUnchecked() && !getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.PAIRED_READ_NOT_MARKED_AS_FIRST_OR_SECOND, "Paired read should be marked as first of pair or second of pair.", getReadName())); } /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getMateUnmappedFlag() && getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } */ } if (getInferredInsertSize() > MAX_INSERT_SIZE || getInferredInsertSize() < -MAX_INSERT_SIZE) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INSERT_SIZE, "Insert size out of range", getReadName())); } if (getReadUnmappedFlag()) { if (getNotPrimaryAlignmentFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_NOT_PRIM_ALIGNMENT, "Not primary alignment flag should not be set for unmapped read.", getReadName())); } if (getMappingQuality() != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be 0 for unmapped read.", getReadName())); } /* non-empty CIGAR on unmapped read is now allowed, because there are special reads when SAM is used to store assembly. */ /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unmapped read.", getReadName())); } */ } else { if (getMappingQuality() >= 256) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be < 256.", getReadName())); } if (getCigarLength() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR should have > zero elements for mapped read.", getReadName())); /* todo - will uncomment once unit tests are added } else if (getCigar().getReadLength() != getReadLength()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR read length " + getCigar().getReadLength() + " doesn't match read length " + getReadLength(), getReadName())); */ } if (getHeader().getSequenceDictionary().size() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISSING_SEQUENCE_DICTIONARY, "Empty sequence dictionary.", getReadName())); } if (!hasReferenceName()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_READ_UNMAPPED, "Mapped read should have valid reference name", getReadName())); } /* Oops! We know this is broken in older BAM files, so this having this validation will cause all sorts of problems! if (getIndexingBin() != null && getIndexingBin() != computeIndexingBin()) { ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INDEXING_BIN, "Indexing bin (" + getIndexingBin() + ") does not agree with computed value (" + computeIndexingBin() + ")", getReadName())); } */ } // Validate the RG ID is found in header final String rgId = (String)getAttribute(SAMTagUtil.getSingleton().RG); if (rgId != null && getHeader().getReadGroup(rgId) == null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.READ_GROUP_NOT_FOUND, "RG ID on SAMRecord not found in header: " + rgId, getReadName())); } final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mReferenceIndex, mReferenceName, getAlignmentStart(), false); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (this.getReadLength() == 0 && !this.getNotPrimaryAlignmentFlag()) { Object fz = getAttribute(SAMTagUtil.getSingleton().FZ); if (fz == null) { String cq = (String)getAttribute(SAMTagUtil.getSingleton().CQ); String cs = (String)getAttribute(SAMTagUtil.getSingleton().CS); if (cq == null || cq.length() == 0 || cs == null || cs.length() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.EMPTY_READ, "Zero-length read without FZ, CS or CQ tag", getReadName())); } else if (!getReadUnmappedFlag()) { boolean hasIndel = false; for (CigarElement cigarElement : getCigar().getCigarElements()) { if (cigarElement.getOperator() == CigarOperator.DELETION || cigarElement.getOperator() == CigarOperator.INSERTION) { hasIndel = true; break; } } if (!hasIndel) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.EMPTY_READ, "Colorspace read with zero-length bases but no indel", getReadName())); } } } } if (this.getReadLength() != getBaseQualities().length && !Arrays.equals(getBaseQualities(), NULL_QUALS)) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISMATCH_READ_LENGTH_AND_QUALS_LENGTH, "Read length does not match quals length", getReadName())); } if (ret == null || ret.size() == 0) { return null; } return ret; }
diff --git a/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java b/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java index 72ac843f3..61b4af7c5 100644 --- a/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java +++ b/org.eclipse.mylyn.ide.ui/src/org/eclipse/mylyn/internal/ide/ui/MarkerInterestFilter.java @@ -1,82 +1,81 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.ide.ui; import java.lang.reflect.Method; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.Viewer; import org.eclipse.mylyn.commons.core.StatusHandler; import org.eclipse.mylyn.ide.ui.AbstractMarkerInterestFilter; import org.eclipse.ui.views.markers.MarkerItem; /** * @author Mik Kersten */ public class MarkerInterestFilter extends AbstractMarkerInterestFilter { private Method markerCategoryMethod = null; @Override public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { //$NON-NLS-1$ try { if (markerCategoryMethod == null) { Class<?> markerCategoryClass = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); //$NON-NLS-1$ markerCategoryMethod = markerCategoryClass.getDeclaredMethod("getChildren", new Class[] {}); //$NON-NLS-1$ markerCategoryMethod.setAccessible(true); } Object[] entries = (Object[]) markerCategoryMethod.invoke(element, new Object[] {}); if (entries != null && entries.length == 0) { return false; } else if (entries != null && entries.length != 0) { // PERFORMANCE: need to look down children, so O(n^2) complexity for (Object markerEntry : entries) { if (markerEntry.getClass().getSimpleName().equals("MarkerEntry") //$NON-NLS-1$ && isInteresting(((MarkerItem) markerEntry).getMarker(), viewer, parent)) { return true; } } return false; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, IdeUiBridgePlugin.ID_PLUGIN, - "Could not access marker view elements.")); //$NON-NLS-1$ - e.printStackTrace(); + "Could not access marker view elements.")); //$NON-NLS-1$ } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { //$NON-NLS-1$ return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; } @Override protected boolean isImplicitlyInteresting(IMarker marker) { try { Object severity = marker.getAttribute(IMarker.SEVERITY); return severity != null && severity.equals(IMarker.SEVERITY_ERROR); } catch (CoreException e) { // ignore } return false; } }
true
true
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { //$NON-NLS-1$ try { if (markerCategoryMethod == null) { Class<?> markerCategoryClass = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); //$NON-NLS-1$ markerCategoryMethod = markerCategoryClass.getDeclaredMethod("getChildren", new Class[] {}); //$NON-NLS-1$ markerCategoryMethod.setAccessible(true); } Object[] entries = (Object[]) markerCategoryMethod.invoke(element, new Object[] {}); if (entries != null && entries.length == 0) { return false; } else if (entries != null && entries.length != 0) { // PERFORMANCE: need to look down children, so O(n^2) complexity for (Object markerEntry : entries) { if (markerEntry.getClass().getSimpleName().equals("MarkerEntry") //$NON-NLS-1$ && isInteresting(((MarkerItem) markerEntry).getMarker(), viewer, parent)) { return true; } } return false; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, IdeUiBridgePlugin.ID_PLUGIN, "Could not access marker view elements.")); //$NON-NLS-1$ e.printStackTrace(); } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { //$NON-NLS-1$ return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; }
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof MarkerItem) { if (element.getClass().getSimpleName().equals("MarkerCategory")) { //$NON-NLS-1$ try { if (markerCategoryMethod == null) { Class<?> markerCategoryClass = Class.forName("org.eclipse.ui.internal.views.markers.MarkerCategory"); //$NON-NLS-1$ markerCategoryMethod = markerCategoryClass.getDeclaredMethod("getChildren", new Class[] {}); //$NON-NLS-1$ markerCategoryMethod.setAccessible(true); } Object[] entries = (Object[]) markerCategoryMethod.invoke(element, new Object[] {}); if (entries != null && entries.length == 0) { return false; } else if (entries != null && entries.length != 0) { // PERFORMANCE: need to look down children, so O(n^2) complexity for (Object markerEntry : entries) { if (markerEntry.getClass().getSimpleName().equals("MarkerEntry") //$NON-NLS-1$ && isInteresting(((MarkerItem) markerEntry).getMarker(), viewer, parent)) { return true; } } return false; } } catch (Exception e) { StatusHandler.log(new Status(IStatus.ERROR, IdeUiBridgePlugin.ID_PLUGIN, "Could not access marker view elements.")); //$NON-NLS-1$ } return true; } else if (element.getClass().getSimpleName().equals("MarkerEntry")) { //$NON-NLS-1$ return isInteresting(((MarkerItem) element).getMarker(), viewer, parent); } } return false; }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/EndpointSerializer.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/EndpointSerializer.java index 15692b33a..f3cc33cee 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/EndpointSerializer.java +++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/EndpointSerializer.java @@ -1,124 +1,126 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.config.xml; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.SynapseException; import org.apache.synapse.config.Endpoint; /** * <endpoint name="string" address="url"> * * .. extensibility .. * * <!-- Axis2 Rampart configurations : may be obsolete soon --> * <parameter name="OutflowSecurity"> * ... * </parameter>+ * * <!-- Apache Sandesha configurations : may be obsolete soon --> * <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy".. * xmlns:wsrm="http://ws.apache.org/sandesha2/policy" wsu:Id="RMPolicy"> * ... * </Policy>+ * * <enableRM/>+ * <enableSec/>+ * <enableAddressing/>+ * * </endpoint> */ public class EndpointSerializer { private static Log log = LogFactory.getLog(EndpointSerializer.class); protected static final OMFactory fac = OMAbstractFactory.getOMFactory(); protected static final OMNamespace synNS = fac.createOMNamespace(Constants.SYNAPSE_NAMESPACE, "syn"); protected static final OMNamespace nullNS = fac.createOMNamespace(Constants.NULL_NAMESPACE, ""); public static OMElement serializeEndpoint(Endpoint endpt, OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); // is this an endpoint ref or an actual endpoint if (endpt.getName() == null && endpt.getRef() != null) { endpoint.addAttribute(fac.createOMAttribute( "ref", nullNS, endpt.getRef())); } else { if (endpt.isForcePOX()) { endpoint.addAttribute(fac.createOMAttribute("force", nullNS, "pox")); } else if (endpt.isForceSOAP()) { endpoint.addAttribute(fac.createOMAttribute("force", nullNS, "soap")); } - endpoint.addAttribute(fac.createOMAttribute( - "name", nullNS, endpt.getName())); + if (endpt.getName() != null) { + endpoint.addAttribute(fac.createOMAttribute( + "name", nullNS, endpt.getName())); + } if (endpt.getAddress() != null) { endpoint.addAttribute(fac.createOMAttribute( "address", nullNS, endpt.getAddress())); } else { handleException("Invalid Endpoint. Address is required"); } if (endpt.isAddressingOn()) { OMElement addressing = fac.createOMElement("enableAddressing", synNS); if (endpt.isUseSeparateListener()) { addressing.addAttribute(fac.createOMAttribute( "separateListener", nullNS, "true")); } endpoint.addChild(addressing); } if (endpt.isReliableMessagingOn()) { OMElement rm = fac.createOMElement("enableRM", synNS); if (endpt.getWsRMPolicyKey() != null) { rm.addAttribute(fac.createOMAttribute( "policy", nullNS, endpt.getWsRMPolicyKey())); } endpoint.addChild(rm); } if (endpt.isSecurityOn()) { OMElement sec = fac.createOMElement("enableSec", synNS); if (endpt.getWsSecPolicyKey() != null) { sec.addAttribute(fac.createOMAttribute( "policy", nullNS, endpt.getWsSecPolicyKey())); } endpoint.addChild(sec); } } if (parent != null) { parent.addChild(endpoint); } return endpoint; } private static void handleException(String msg) { log.error(msg); throw new SynapseException(msg); } }
true
true
public static OMElement serializeEndpoint(Endpoint endpt, OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); // is this an endpoint ref or an actual endpoint if (endpt.getName() == null && endpt.getRef() != null) { endpoint.addAttribute(fac.createOMAttribute( "ref", nullNS, endpt.getRef())); } else { if (endpt.isForcePOX()) { endpoint.addAttribute(fac.createOMAttribute("force", nullNS, "pox")); } else if (endpt.isForceSOAP()) { endpoint.addAttribute(fac.createOMAttribute("force", nullNS, "soap")); } endpoint.addAttribute(fac.createOMAttribute( "name", nullNS, endpt.getName())); if (endpt.getAddress() != null) { endpoint.addAttribute(fac.createOMAttribute( "address", nullNS, endpt.getAddress())); } else { handleException("Invalid Endpoint. Address is required"); } if (endpt.isAddressingOn()) { OMElement addressing = fac.createOMElement("enableAddressing", synNS); if (endpt.isUseSeparateListener()) { addressing.addAttribute(fac.createOMAttribute( "separateListener", nullNS, "true")); } endpoint.addChild(addressing); } if (endpt.isReliableMessagingOn()) { OMElement rm = fac.createOMElement("enableRM", synNS); if (endpt.getWsRMPolicyKey() != null) { rm.addAttribute(fac.createOMAttribute( "policy", nullNS, endpt.getWsRMPolicyKey())); } endpoint.addChild(rm); } if (endpt.isSecurityOn()) { OMElement sec = fac.createOMElement("enableSec", synNS); if (endpt.getWsSecPolicyKey() != null) { sec.addAttribute(fac.createOMAttribute( "policy", nullNS, endpt.getWsSecPolicyKey())); } endpoint.addChild(sec); } } if (parent != null) { parent.addChild(endpoint); } return endpoint; }
public static OMElement serializeEndpoint(Endpoint endpt, OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); // is this an endpoint ref or an actual endpoint if (endpt.getName() == null && endpt.getRef() != null) { endpoint.addAttribute(fac.createOMAttribute( "ref", nullNS, endpt.getRef())); } else { if (endpt.isForcePOX()) { endpoint.addAttribute(fac.createOMAttribute("force", nullNS, "pox")); } else if (endpt.isForceSOAP()) { endpoint.addAttribute(fac.createOMAttribute("force", nullNS, "soap")); } if (endpt.getName() != null) { endpoint.addAttribute(fac.createOMAttribute( "name", nullNS, endpt.getName())); } if (endpt.getAddress() != null) { endpoint.addAttribute(fac.createOMAttribute( "address", nullNS, endpt.getAddress())); } else { handleException("Invalid Endpoint. Address is required"); } if (endpt.isAddressingOn()) { OMElement addressing = fac.createOMElement("enableAddressing", synNS); if (endpt.isUseSeparateListener()) { addressing.addAttribute(fac.createOMAttribute( "separateListener", nullNS, "true")); } endpoint.addChild(addressing); } if (endpt.isReliableMessagingOn()) { OMElement rm = fac.createOMElement("enableRM", synNS); if (endpt.getWsRMPolicyKey() != null) { rm.addAttribute(fac.createOMAttribute( "policy", nullNS, endpt.getWsRMPolicyKey())); } endpoint.addChild(rm); } if (endpt.isSecurityOn()) { OMElement sec = fac.createOMElement("enableSec", synNS); if (endpt.getWsSecPolicyKey() != null) { sec.addAttribute(fac.createOMAttribute( "policy", nullNS, endpt.getWsSecPolicyKey())); } endpoint.addChild(sec); } } if (parent != null) { parent.addChild(endpoint); } return endpoint; }
diff --git a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/controller/InteractiveFlexoEditor.java b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/controller/InteractiveFlexoEditor.java index 1ffb5e464..4faf9ab9b 100644 --- a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/controller/InteractiveFlexoEditor.java +++ b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/controller/InteractiveFlexoEditor.java @@ -1,618 +1,621 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenFlexo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.view.controller; import java.util.EventObject; import java.util.Hashtable; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import org.openflexo.ApplicationContext; import org.openflexo.components.ProgressWindow; import org.openflexo.foundation.DefaultFlexoEditor; import org.openflexo.foundation.FlexoException; import org.openflexo.foundation.FlexoModelObject; import org.openflexo.foundation.action.FlexoAction; import org.openflexo.foundation.action.FlexoAction.ExecutionStatus; import org.openflexo.foundation.action.FlexoActionEnableCondition; import org.openflexo.foundation.action.FlexoActionFinalizer; import org.openflexo.foundation.action.FlexoActionInitializer; import org.openflexo.foundation.action.FlexoActionRedoFinalizer; import org.openflexo.foundation.action.FlexoActionRedoInitializer; import org.openflexo.foundation.action.FlexoActionType; import org.openflexo.foundation.action.FlexoActionUndoFinalizer; import org.openflexo.foundation.action.FlexoActionUndoInitializer; import org.openflexo.foundation.action.FlexoActionVisibleCondition; import org.openflexo.foundation.action.FlexoExceptionHandler; import org.openflexo.foundation.action.FlexoGUIAction; import org.openflexo.foundation.action.FlexoUndoableAction; import org.openflexo.foundation.action.UndoManager; import org.openflexo.foundation.dm.DMObject; import org.openflexo.foundation.ie.IEObject; import org.openflexo.foundation.rm.DefaultFlexoResourceUpdateHandler; import org.openflexo.foundation.rm.FlexoProject; import org.openflexo.foundation.rm.ResourceUpdateHandler; import org.openflexo.foundation.utils.FlexoDocFormat; import org.openflexo.foundation.utils.FlexoProgress; import org.openflexo.foundation.utils.FlexoProgressFactory; import org.openflexo.foundation.view.ViewObject; import org.openflexo.foundation.view.action.ActionSchemeActionType; import org.openflexo.foundation.wkf.WKFObject; import org.openflexo.foundation.ws.WSObject; import org.openflexo.localization.FlexoLocalization; import org.openflexo.logging.FlexoLogger; import org.openflexo.module.FlexoModule; import org.openflexo.module.Module; import org.openflexo.module.ModuleLoader; import org.openflexo.module.ModuleLoadingException; public class InteractiveFlexoEditor extends DefaultFlexoEditor { private static final Logger logger = FlexoLogger.getLogger(InteractiveFlexoEditor.class.getPackage().getName()); private static final boolean WARN_MODEL_MODIFICATIONS_OUTSIDE_FLEXO_ACTION_LAYER = false; private final UndoManager _undoManager; private ScenarioRecorder _scenarioRecorder; private final Hashtable<FlexoAction<?, ?, ?>, Vector<FlexoModelObject>> _createdAndNotNotifiedObjects; private final Hashtable<FlexoAction<?, ?, ?>, Vector<FlexoModelObject>> _deletedAndNotNotifiedObjects; private Stack<FlexoAction<?, ?, ?>> _currentlyPerformedActionStack = null; private Stack<FlexoAction<?, ?, ?>> _currentlyUndoneActionStack = null; private Stack<FlexoAction<?, ?, ?>> _currentlyRedoneActionStack = null; private final FlexoProgressFactory _progressFactory; private final ApplicationContext applicationContext; private Map<FlexoModule, ControllerActionInitializer> actionInitializers; public InteractiveFlexoEditor(ApplicationContext applicationContext, FlexoProject project) { super(project); this.applicationContext = applicationContext; actionInitializers = new Hashtable<FlexoModule, ControllerActionInitializer>(); _undoManager = new UndoManager(); if (ScenarioRecorder.ENABLE) { _scenarioRecorder = new ScenarioRecorder(); } _createdAndNotNotifiedObjects = new Hashtable<FlexoAction<?, ?, ?>, Vector<FlexoModelObject>>(); _deletedAndNotNotifiedObjects = new Hashtable<FlexoAction<?, ?, ?>, Vector<FlexoModelObject>>(); _currentlyPerformedActionStack = new Stack<FlexoAction<?, ?, ?>>(); _currentlyUndoneActionStack = new Stack<FlexoAction<?, ?, ?>>(); _currentlyRedoneActionStack = new Stack<FlexoAction<?, ?, ?>>(); _progressFactory = new FlexoProgressFactory() { @Override public FlexoProgress makeFlexoProgress(String title, int steps) { return ProgressWindow.makeProgressWindow(title, steps); } }; } private ModuleLoader getModuleLoader() { return applicationContext.getModuleLoader(); } @Override public ResourceUpdateHandler getResourceUpdateHandler() { return new DefaultFlexoResourceUpdateHandler(); } @Override public boolean isInteractive() { return true; } @Override public <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> A performAction( final A action, final EventObject e) { if (!action.getActionType().isEnabled(action.getFocusedObject(), action.getGlobalSelection())) { return null; } if (!(action instanceof FlexoGUIAction<?, ?, ?>) && action.getFocusedObject() != null && action.getFocusedObject().getProject() != getProject()) { if (logger.isLoggable(Level.INFO)) { logger.info("Cannot execute action because focused object is within another project than the one of this editor"); } return null; } executeAction(action, e); return action; } private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> A executeAction( final A action, final EventObject event) { final boolean progressIsShowing = ProgressWindow.hasInstance(); boolean confirmDoAction = runInitializer(action, event); if (confirmDoAction) { actionWillBePerformed(action); if (action.isLongRunningAction() && SwingUtilities.isEventDispatchThread()) { ProgressWindow.showProgressWindow(action.getLocalizedName(), 100); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { runAction(action); return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); if (e.getCause() instanceof FlexoException) { if (!runExceptionHandler((FlexoException) e.getCause(), action)) { + if (!progressIsShowing) { + ProgressWindow.hideProgressWindow(); + } return; } } else { throw new RuntimeException(FlexoLocalization.localizedForKey("action_failed") + " " + action.getLocalizedName(), e.getCause()); } } runFinalizer(action, event); if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } } }; worker.execute(); return action; } else { try { runAction(action); } catch (FlexoException exception) { if (!runExceptionHandler(exception, action)) { return null; } } runFinalizer(action, event); if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } } } return action; } private <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> boolean runInitializer(A action, EventObject event) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(action.getActionType()); if (actionInitializer != null) { FlexoActionInitializer<A> initializer = actionInitializer.getDefaultInitializer(); if (initializer != null) { return initializer.run(event, action); } } return true; } private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void runAction( final A action) throws FlexoException { if (getProject() != null) { getProject().clearRecentlyCreatedObjects(); } action.doActionInContext(); if (getProject() != null) { getProject().notifyRecentlyCreatedObjects(); } actionHasBeenPerformed(action, true); // Action succeeded } private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void runFinalizer( final A action, EventObject event) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(action.getActionType()); if (actionInitializer != null) { FlexoActionFinalizer<A> finalizer = actionInitializer.getDefaultFinalizer(); if (finalizer != null) { finalizer.run(event, action); } } } private <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> boolean runExceptionHandler( FlexoException exception, final A action) { actionHasBeenPerformed(action, false); // Action failed ProgressWindow.hideProgressWindow(); FlexoExceptionHandler<A> exceptionHandler = null; ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(action.getActionType()); if (actionInitializer != null) { exceptionHandler = actionInitializer.getDefaultExceptionHandler(); } if (exceptionHandler != null) { if (exceptionHandler.handleException(exception, action)) { // The exception has been handled, we may still have to execute finalizer, if any return true; } else { return false; } } else { return false; } } @Override public <A extends FlexoUndoableAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> A performUndoAction( final A action, final EventObject event) { boolean confirmUndoAction = true; ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(action.getActionType()); FlexoActionUndoInitializer<A> initializer = null; if (actionInitializer != null) { initializer = actionInitializer.getDefaultUndoInitializer(); if (initializer != null) { confirmUndoAction = initializer.run(event, action); } } if (confirmUndoAction) { actionWillBeUndone(action); try { if (getProject() != null) { getProject().clearRecentlyCreatedObjects(); } action.doActionInContext(); if (getProject() != null) { getProject().notifyRecentlyCreatedObjects(); } actionHasBeenUndone(action, true); // Action succeeded } catch (FlexoException exception) { actionHasBeenUndone(action, false); // Action failed ProgressWindow.hideProgressWindow(); FlexoExceptionHandler<A> exceptionHandler = null; if (actionInitializer != null) { exceptionHandler = actionInitializer.getDefaultExceptionHandler(); } if (exceptionHandler != null) { if (exceptionHandler.handleException(exception, action)) { // The exception has been handled, we may still have to execute finalizer, if any } else { return action; } } else { return action; } } FlexoActionUndoFinalizer<A> finalizer = null; if (actionInitializer != null) { finalizer = actionInitializer.getDefaultUndoFinalizer(); if (finalizer != null) { confirmUndoAction = finalizer.run(event, action); } } } ProgressWindow.hideProgressWindow(); return action; } @Override public <A extends FlexoUndoableAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> A performRedoAction( A action, EventObject event) { boolean confirmRedoAction = true; ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(action.getActionType()); FlexoActionRedoInitializer<A> initializer = null; if (actionInitializer != null) { initializer = actionInitializer.getDefaultRedoInitializer(); if (initializer != null) { confirmRedoAction = initializer.run(event, action); } } if (confirmRedoAction) { actionWillBeRedone(action); try { if (getProject() != null) { getProject().clearRecentlyCreatedObjects(); } action.redoActionInContext(); if (getProject() != null) { getProject().notifyRecentlyCreatedObjects(); } actionHasBeenRedone(action, true); // Action succeeded } catch (FlexoException exception) { actionHasBeenUndone(action, false); // Action failed ProgressWindow.hideProgressWindow(); FlexoExceptionHandler<A> exceptionHandler = null; if (actionInitializer != null) { exceptionHandler = actionInitializer.getDefaultExceptionHandler(); } if (exceptionHandler != null) { if (exceptionHandler.handleException(exception, action)) { // The exception has been handled, we may still have to execute finalizer, if any } else { return action; } } else { return action; } } FlexoActionRedoFinalizer<A> finalizer = null; if (actionInitializer != null) { finalizer = actionInitializer.getDefaultRedoFinalizer(); if (finalizer != null) { confirmRedoAction = finalizer.run(event, action); } } } ProgressWindow.hideProgressWindow(); return action; } @Override public UndoManager getUndoManager() { return _undoManager; } private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void actionWillBePerformed( A action) { _undoManager.actionWillBePerformed(action); _currentlyPerformedActionStack.push(action); _createdAndNotNotifiedObjects.put(action, new Vector<FlexoModelObject>()); _deletedAndNotNotifiedObjects.put(action, new Vector<FlexoModelObject>()); } private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void actionHasBeenPerformed( A action, boolean success) { _undoManager.actionHasBeenPerformed(action, success); if (success) { if (_scenarioRecorder != null) { if (!action.isEmbedded() || action.getOwnerAction().getExecutionStatus() != ExecutionStatus.EXECUTING_CORE) { _scenarioRecorder.registerDoneAction(action); } } } FlexoAction<?, ?, ?> popAction = _currentlyPerformedActionStack.pop(); if (popAction != action) { logger.warning("Expected to pop " + action + " but found " + popAction); } for (FlexoModelObject o : action.getExecutionContext().getObjectsCreatedWhileExecutingAction().values()) { _createdAndNotNotifiedObjects.get(action).remove(o); } for (FlexoModelObject o : action.getExecutionContext().getObjectsDeletedWhileExecutingAction().values()) { _deletedAndNotNotifiedObjects.get(action).remove(o); } if (WARN_MODEL_MODIFICATIONS_OUTSIDE_FLEXO_ACTION_LAYER) { for (FlexoModelObject o : _createdAndNotNotifiedObjects.get(action)) { logger.warning("FlexoModelObject " + o + " created during action " + action + " but was not notified (see objectCreated(String,FlexoModelObject))"); } for (FlexoModelObject o : _deletedAndNotNotifiedObjects.get(action)) { logger.warning("FlexoModelObject " + o + " deleted during action " + action + " but was not notified (see objectDeleted(String,FlexoModelObject))"); } } _createdAndNotNotifiedObjects.remove(action); _deletedAndNotNotifiedObjects.remove(action); } private <A extends FlexoUndoableAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void actionWillBeUndone( A action) { _undoManager.actionWillBeUndone(action); _currentlyUndoneActionStack.push(action); } private <A extends FlexoUndoableAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void actionHasBeenUndone( A action, boolean success) { _undoManager.actionHasBeenUndone(action, success); FlexoAction<?, ?, ?> popAction = _currentlyUndoneActionStack.pop(); if (popAction != action) { logger.warning("Expected to pop " + action + " but found " + popAction); } } private <A extends FlexoUndoableAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void actionWillBeRedone( A action) { _undoManager.actionWillBeRedone(action); _currentlyRedoneActionStack.push(action); } private <A extends FlexoUndoableAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> void actionHasBeenRedone( A action, boolean success) { _undoManager.actionHasBeenRedone(action, success); FlexoAction<?, ?, ?> popAction = _currentlyRedoneActionStack.pop(); if (popAction != action) { logger.warning("Expected to pop " + action + " but found " + popAction); } } @Override public void notifyObjectCreated(FlexoModelObject object) { if (logger.isLoggable(Level.FINE)) { logger.fine("notifyObjectCreated: " + object); } if (_currentlyPerformedActionStack.isEmpty() && _currentlyUndoneActionStack.isEmpty() && _currentlyRedoneActionStack.isEmpty() && WARN_MODEL_MODIFICATIONS_OUTSIDE_FLEXO_ACTION_LAYER) { logger.warning("FlexoModelObject " + object + " created outside of FlexoAction context !!!"); } else if (!_currentlyPerformedActionStack.isEmpty()) { _createdAndNotNotifiedObjects.get(_currentlyPerformedActionStack.peek()).add(object); } object.setDocFormat(FlexoDocFormat.HTML, false); } @Override public void notifyObjectDeleted(FlexoModelObject object) { if (logger.isLoggable(Level.FINE)) { logger.fine("notifyObjectDeleted: " + object); } if (_currentlyPerformedActionStack.isEmpty() && _currentlyUndoneActionStack.isEmpty() && _currentlyRedoneActionStack.isEmpty() && WARN_MODEL_MODIFICATIONS_OUTSIDE_FLEXO_ACTION_LAYER) { logger.warning("FlexoModelObject " + object + " deleted outside of FlexoAction context !!!"); } else if (!_currentlyPerformedActionStack.isEmpty()) { _deletedAndNotNotifiedObjects.get(_currentlyPerformedActionStack.peek()).add(object); } } @Override public void notifyObjectChanged(FlexoModelObject object) { if (_currentlyPerformedActionStack.isEmpty() && _currentlyUndoneActionStack.isEmpty() && _currentlyRedoneActionStack.isEmpty() && WARN_MODEL_MODIFICATIONS_OUTSIDE_FLEXO_ACTION_LAYER) { logger.warning("setChanged() called for " + object + " outside of FlexoAction context !!!"); } } @Override public boolean performResourceScanning() { return true; } @Override public FlexoProgressFactory getFlexoProgressFactory() { return _progressFactory; } public boolean isTestEditor() { return false; } @Override public void focusOn(FlexoModelObject object) { try { if (object instanceof WKFObject) { getModuleLoader().switchToModule(Module.WKF_MODULE); } else if (object instanceof IEObject) { getModuleLoader().switchToModule(Module.IE_MODULE); } else if (object instanceof DMObject) { getModuleLoader().switchToModule(Module.DM_MODULE); } else if (object instanceof WSObject) { getModuleLoader().switchToModule(Module.WSE_MODULE); } else if (object instanceof ViewObject) { getModuleLoader().switchToModule(Module.VE_MODULE); } } catch (ModuleLoadingException e) { logger.warning("Cannot load module " + e.getModule()); e.printStackTrace(); } // Only interactive editor handle this getModuleLoader().getActiveModule().getFlexoController().setCurrentEditedObjectAsModuleView(object); getModuleLoader().getActiveModule().getFlexoController().getSelectionManager().setSelectedObject(object); } public void registerControllerActionInitializer(ControllerActionInitializer controllerActionInitializer) { actionInitializers.put(controllerActionInitializer.getModule(), controllerActionInitializer); } public void unregisterControllerActionInitializer(ControllerActionInitializer controllerActionInitializer) { actionInitializers.remove(controllerActionInitializer.getModule()); } private ControllerActionInitializer getCurrentControllerActionInitializer() { return actionInitializers.get(getModuleLoader().getActiveModule()); } private <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> ActionInitializer<A, T1, T2> getActionInitializer( FlexoActionType<A, T1, T2> actionType) { ControllerActionInitializer currentControllerActionInitializer = getCurrentControllerActionInitializer(); if (currentControllerActionInitializer != null) { return currentControllerActionInitializer.getActionInitializer(actionType); } return null; } @Override public <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> boolean isActionEnabled( FlexoActionType<A, T1, T2> actionType, T1 focusedObject, Vector<T2> globalSelection) { if (actionType instanceof ActionSchemeActionType) { return true; } if (actionType.isEnabled(focusedObject, globalSelection)) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(actionType); if (actionInitializer != null) { FlexoActionEnableCondition<A, T1, T2> condition = actionInitializer.getEnableCondition(); if (condition != null) { return condition.isEnabled(actionType, focusedObject, globalSelection, this); } } else { return false; } } else { return false; } return true; } @Override public <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> boolean isActionVisible( FlexoActionType<A, T1, T2> actionType, T1 focusedObject, Vector<T2> globalSelection) { if (actionType.isVisibleForSelection(focusedObject, globalSelection)) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(actionType); if (actionInitializer != null) { FlexoActionVisibleCondition<A, T1, T2> condition = actionInitializer.getVisibleCondition(); if (condition != null) { return condition.isVisible(actionType, focusedObject, globalSelection, this); } } else { return false; } } else { return false; } return true; } @Override public <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> Icon getEnabledIconFor( FlexoActionType<A, T1, T2> actionType) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(actionType); if (actionInitializer != null) { return actionInitializer.getEnabledIcon(); } return null; } @Override public <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> Icon getDisabledIconFor( FlexoActionType<A, T1, T2> actionType) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(actionType); if (actionInitializer != null) { return actionInitializer.getDisabledIcon(); } return null; } @Override public <A extends FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> KeyStroke getKeyStrokeFor( FlexoActionType<A, T1, T2> actionType) { ActionInitializer<A, T1, T2> actionInitializer = getActionInitializer(actionType); if (actionInitializer != null) { return actionInitializer.getShortcut(); } return null; } }
true
true
private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> A executeAction( final A action, final EventObject event) { final boolean progressIsShowing = ProgressWindow.hasInstance(); boolean confirmDoAction = runInitializer(action, event); if (confirmDoAction) { actionWillBePerformed(action); if (action.isLongRunningAction() && SwingUtilities.isEventDispatchThread()) { ProgressWindow.showProgressWindow(action.getLocalizedName(), 100); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { runAction(action); return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); if (e.getCause() instanceof FlexoException) { if (!runExceptionHandler((FlexoException) e.getCause(), action)) { return; } } else { throw new RuntimeException(FlexoLocalization.localizedForKey("action_failed") + " " + action.getLocalizedName(), e.getCause()); } } runFinalizer(action, event); if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } } }; worker.execute(); return action; } else { try { runAction(action); } catch (FlexoException exception) { if (!runExceptionHandler(exception, action)) { return null; } } runFinalizer(action, event); if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } } } return action; }
private <A extends org.openflexo.foundation.action.FlexoAction<A, T1, T2>, T1 extends FlexoModelObject, T2 extends FlexoModelObject> A executeAction( final A action, final EventObject event) { final boolean progressIsShowing = ProgressWindow.hasInstance(); boolean confirmDoAction = runInitializer(action, event); if (confirmDoAction) { actionWillBePerformed(action); if (action.isLongRunningAction() && SwingUtilities.isEventDispatchThread()) { ProgressWindow.showProgressWindow(action.getLocalizedName(), 100); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { runAction(action); return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); if (e.getCause() instanceof FlexoException) { if (!runExceptionHandler((FlexoException) e.getCause(), action)) { if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } return; } } else { throw new RuntimeException(FlexoLocalization.localizedForKey("action_failed") + " " + action.getLocalizedName(), e.getCause()); } } runFinalizer(action, event); if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } } }; worker.execute(); return action; } else { try { runAction(action); } catch (FlexoException exception) { if (!runExceptionHandler(exception, action)) { return null; } } runFinalizer(action, event); if (!progressIsShowing) { ProgressWindow.hideProgressWindow(); } } } return action; }
diff --git a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java index 7d3e96ba..634aa2f5 100644 --- a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java +++ b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java @@ -1,2932 +1,2933 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.xs.traversers; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Hashtable; import java.util.Locale; import java.util.Stack; import java.util.Vector; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.xs.DecimalDV; import org.apache.xerces.impl.dv.xs.TypeValidator; import org.apache.xerces.impl.xs.SchemaGrammar; import org.apache.xerces.impl.xs.SchemaNamespaceSupport; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.XMLSchemaException; import org.apache.xerces.impl.xs.XMLSchemaLoader; import org.apache.xerces.impl.xs.XSAttributeGroupDecl; import org.apache.xerces.impl.xs.XSComplexTypeDecl; import org.apache.xerces.impl.xs.XSConstraints; import org.apache.xerces.impl.xs.XSDDescription; import org.apache.xerces.impl.xs.XSDeclarationPool; import org.apache.xerces.impl.xs.XSElementDecl; import org.apache.xerces.impl.xs.XSGrammarBucket; import org.apache.xerces.impl.xs.XSGroupDecl; import org.apache.xerces.impl.xs.XSMessageFormatter; import org.apache.xerces.impl.xs.XSModelGroupImpl; import org.apache.xerces.impl.xs.XSParticleDecl; import org.apache.xerces.impl.xs.opti.ElementImpl; import org.apache.xerces.impl.xs.opti.SchemaDOMParser; import org.apache.xerces.impl.xs.opti.SchemaParsingConfig; import org.apache.xerces.impl.xs.util.SimpleLocator; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.parsers.XML11Configuration; import org.apache.xerces.util.DOMInputSource; import org.apache.xerces.util.DOMUtil; import org.apache.xerces.util.DefaultErrorHandler; import org.apache.xerces.util.SAXInputSource; import org.apache.xerces.util.StAXInputSource; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.URI.MalformedURIException; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.grammars.XMLSchemaDescription; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.XSObject; import org.apache.xerces.xs.XSParticle; import org.apache.xerces.xs.datatypes.XSDecimal; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * The purpose of this class is to co-ordinate the construction of a * grammar object corresponding to a schema. To do this, it must be * prepared to parse several schema documents (for instance if the * schema document originally referred to contains <include> or * <redefined> information items). If any of the schemas imports a * schema, other grammars may be constructed as a side-effect. * * @xerces.internal * * @author Neil Graham, IBM * @author Pavani Mukthipudi, Sun Microsystems * * @version $Id$ */ public class XSDHandler { /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** feature identifier: XML Schema validation */ protected static final String XMLSCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: allow java encodings */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: continue after fatal error */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; /** Feature identifier: allow java encodings */ protected static final String STANDARD_URI_CONFORMANT_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE; /** Feature: disallow doctype*/ protected static final String DISALLOW_DOCTYPE = Constants.XERCES_FEATURE_PREFIX + Constants.DISALLOW_DOCTYPE_DECL_FEATURE; /** Feature: generate synthetic annotations */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE; /** Feature identifier: validate annotations. */ protected static final String VALIDATE_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.VALIDATE_ANNOTATIONS_FEATURE; /** Feature identifier: honour all schemaLocations */ protected static final String HONOUR_ALL_SCHEMALOCATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE; /** Feature identifier: namespace prefixes. */ private static final String NAMESPACE_PREFIXES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE; /** Feature identifier: string interning. */ protected static final String STRING_INTERNING = Constants.SAX_FEATURE_PREFIX + Constants.STRING_INTERNING_FEATURE; /** Property identifier: error handler. */ protected static final String ERROR_HANDLER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: entity manager. */ protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: security manager. */ protected static final String SECURITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; /** Property identifier: locale. */ protected static final String LOCALE = Constants.XERCES_PROPERTY_PREFIX + Constants.LOCALE_PROPERTY; protected static final boolean DEBUG_NODE_POOL = false; // Data // different sorts of declarations; should make lookup and // traverser calling more efficient/less bulky. final static int ATTRIBUTE_TYPE = 1; final static int ATTRIBUTEGROUP_TYPE = 2; final static int ELEMENT_TYPE = 3; final static int GROUP_TYPE = 4; final static int IDENTITYCONSTRAINT_TYPE = 5; final static int NOTATION_TYPE = 6; final static int TYPEDECL_TYPE = 7; // this string gets appended to redefined names; it's purpose is to be // as unlikely as possible to cause collisions. public final static String REDEF_IDENTIFIER = "_fn3dktizrknc9pi"; // //protected data that can be accessable by any traverser // stores <notation> decl protected Hashtable fNotationRegistry = new Hashtable(); protected XSDeclarationPool fDeclPool = null; // These tables correspond to the symbol spaces defined in the // spec. // They are keyed with a QName (that is, String("URI,localpart) and // their values are nodes corresponding to the given name's decl. // By asking the node for its ownerDocument and looking in // XSDocumentInfoRegistry we can easily get the corresponding // XSDocumentInfo object. private Hashtable fUnparsedAttributeRegistry = new Hashtable(); private Hashtable fUnparsedAttributeGroupRegistry = new Hashtable(); private Hashtable fUnparsedElementRegistry = new Hashtable(); private Hashtable fUnparsedGroupRegistry = new Hashtable(); private Hashtable fUnparsedIdentityConstraintRegistry = new Hashtable(); private Hashtable fUnparsedNotationRegistry = new Hashtable(); private Hashtable fUnparsedTypeRegistry = new Hashtable(); // Compensation for the above hashtables to locate XSDocumentInfo, // Since we may take Schema Element directly, so can not get the // corresponding XSDocumentInfo object just using above hashtables. private Hashtable fUnparsedAttributeRegistrySub = new Hashtable(); private Hashtable fUnparsedAttributeGroupRegistrySub = new Hashtable(); private Hashtable fUnparsedElementRegistrySub = new Hashtable(); private Hashtable fUnparsedGroupRegistrySub = new Hashtable(); private Hashtable fUnparsedIdentityConstraintRegistrySub = new Hashtable(); private Hashtable fUnparsedNotationRegistrySub = new Hashtable(); private Hashtable fUnparsedTypeRegistrySub = new Hashtable(); // this is keyed with a documentNode (or the schemaRoot nodes // contained in the XSDocumentInfo objects) and its value is the // XSDocumentInfo object corresponding to that document. // Basically, the function of this registry is to be a link // between the nodes we fetch from calls to the fUnparsed* // arrays and the XSDocumentInfos they live in. private Hashtable fXSDocumentInfoRegistry = new Hashtable(); // this hashtable is keyed on by XSDocumentInfo objects. Its values // are Vectors containing the XSDocumentInfo objects <include>d, // <import>ed or <redefine>d by the key XSDocumentInfo. private Hashtable fDependencyMap = new Hashtable(); // this hashtable is keyed on by a target namespace. Its values // are Vectors containing namespaces imported by schema documents // with the key target namespace. // if an imprted schema has absent namespace, the value "null" is stored. private Hashtable fImportMap = new Hashtable(); // all namespaces that imports other namespaces // if the importing schema has absent namespace, empty string is stored. // (because the key of a hashtable can't be null.) private Vector fAllTNSs = new Vector(); // stores instance document mappings between namespaces and schema hints private Hashtable fLocationPairs = null; private static final Hashtable EMPTY_TABLE = new Hashtable(); // Records which nodes are hidden when the input is a DOMInputSource. Hashtable fHiddenNodes = null; // Conditional inclustion private static final String XSD_VERSION_1_0 = "1.0"; private static final String XSD_VERSION_1_1 = "1.1"; private static final TypeValidator DECIMAL_DV = new DecimalDV(); private static final XSDecimal SUPPORTED_VERSION_1_0 = getSupportedVersion(XSD_VERSION_1_0); private static final XSDecimal SUPPORTED_VERSION_1_1 = getSupportedVersion(XSD_VERSION_1_1); private XSDecimal fSupportedVersion = SUPPORTED_VERSION_1_0; private static XSDecimal getSupportedVersion(String version) { XSDecimal result = null; try { result = (XSDecimal) DECIMAL_DV.getActualValue(version, null); } catch (InvalidDatatypeValueException ide) { } return result; } // convenience methods private String null2EmptyString(String ns) { return ns == null ? XMLSymbols.EMPTY_STRING : ns; } private String emptyString2Null(String ns) { return ns == XMLSymbols.EMPTY_STRING ? null : ns; } // use Schema Element to lookup the SystemId. private String doc2SystemId(Element ele) { String documentURI = null; /** * REVISIT: Casting until DOM Level 3 interfaces are available. -- mrglavas */ if(ele.getOwnerDocument() instanceof org.apache.xerces.impl.xs.opti.SchemaDOM){ documentURI = ((org.apache.xerces.impl.xs.opti.SchemaDOM) ele.getOwnerDocument()).getDocumentURI(); } return documentURI != null ? documentURI : (String) fDoc2SystemId.get(ele); } // This vector stores strings which are combinations of the // publicId and systemId of the inputSource corresponding to a // schema document. This combination is used so that the user's // EntityResolver can provide a consistent way of identifying a // schema document that is included in multiple other schemas. private Hashtable fTraversed = new Hashtable(); // this hashtable contains a mapping from Schema Element to its systemId // this is useful to resolve a uri relative to the referring document private Hashtable fDoc2SystemId = new Hashtable(); // the primary XSDocumentInfo we were called to parse private XSDocumentInfo fRoot = null; // This hashtable's job is to act as a link between the Schema Element and its // XSDocumentInfo object. private Hashtable fDoc2XSDocumentMap = new Hashtable(); // map between <redefine> elements and the XSDocumentInfo // objects that correspond to the documents being redefined. private Hashtable fRedefine2XSDMap = new Hashtable(); // map between <redefine> elements and the namespace support private Hashtable fRedefine2NSSupport = new Hashtable(); // these objects store a mapping between the names of redefining // groups/attributeGroups and the groups/AttributeGroups which // they redefine by restriction (implicitly). It is up to the // Group and AttributeGroup traversers to check these restrictions for // validity. private Hashtable fRedefinedRestrictedAttributeGroupRegistry = new Hashtable(); private Hashtable fRedefinedRestrictedGroupRegistry = new Hashtable(); // a variable storing whether the last schema document // processed (by getSchema) was a duplicate. private boolean fLastSchemaWasDuplicate; // validate annotations feature private boolean fValidateAnnotations = false; //handle multiple import feature private boolean fHonourAllSchemaLocations = false; // the XMLErrorReporter private XMLErrorReporter fErrorReporter; private XMLEntityResolver fEntityResolver; // the XSAttributeChecker private XSAttributeChecker fAttributeChecker; // the symbol table private SymbolTable fSymbolTable; // the GrammarResolver private XSGrammarBucket fGrammarBucket; // the Grammar description private XSDDescription fSchemaGrammarDescription; // the Grammar Pool private XMLGrammarPool fGrammarPool; //************ Traversers ********** XSDAttributeGroupTraverser fAttributeGroupTraverser; XSDAttributeTraverser fAttributeTraverser; XSDComplexTypeTraverser fComplexTypeTraverser; XSDElementTraverser fElementTraverser; XSDGroupTraverser fGroupTraverser; XSDKeyrefTraverser fKeyrefTraverser; XSDNotationTraverser fNotationTraverser; XSDSimpleTypeTraverser fSimpleTypeTraverser; XSDTypeAlternativeTraverser fTypeAlternativeTraverser; XSDUniqueOrKeyTraverser fUniqueOrKeyTraverser; XSDWildcardTraverser fWildCardTraverser; SchemaDOMParser fSchemaParser; SchemaContentHandler fXSContentHandler; StAXSchemaParser fStAXSchemaParser; XML11Configuration fAnnotationValidator; XSAnnotationGrammarPool fGrammarBucketAdapter; // flag to indicate schema 1.1 support short fSchemaVersion; // XML Schema constraint checker XSConstraints fXSConstraints; // these data members are needed for the deferred traversal // of local elements. // the initial size of the array to store deferred local elements private static final int INIT_STACK_SIZE = 30; // the incremental size of the array to store deferred local elements private static final int INC_STACK_SIZE = 10; // current position of the array (# of deferred local elements) private int fLocalElemStackPos = 0; private XSParticleDecl[] fParticle = new XSParticleDecl[INIT_STACK_SIZE]; private Element[] fLocalElementDecl = new Element[INIT_STACK_SIZE]; private XSDocumentInfo[] fLocalElementDecl_schema = new XSDocumentInfo[INIT_STACK_SIZE]; //JACK private int[] fAllContext = new int[INIT_STACK_SIZE]; private XSObject[] fParent = new XSObject[INIT_STACK_SIZE]; private String [][] fLocalElemNamespaceContext = new String [INIT_STACK_SIZE][1]; // these data members are needed for the deferred traversal // of keyrefs. // the initial size of the array to store deferred keyrefs private static final int INIT_KEYREF_STACK = 2; // the incremental size of the array to store deferred keyrefs private static final int INC_KEYREF_STACK_AMOUNT = 2; // current position of the array (# of deferred keyrefs) private int fKeyrefStackPos = 0; private Element [] fKeyrefs = new Element[INIT_KEYREF_STACK]; private XSDocumentInfo [] fKeyrefsMapXSDocumentInfo = new XSDocumentInfo[INIT_KEYREF_STACK]; private XSElementDecl [] fKeyrefElems = new XSElementDecl [INIT_KEYREF_STACK]; private String [][] fKeyrefNamespaceContext = new String[INIT_KEYREF_STACK][1]; // Constructors public XSDHandler(short schemaVersion, XSConstraints xsConstraints){ fSchemaVersion = schemaVersion; fXSConstraints = xsConstraints; fHiddenNodes = new Hashtable(); fSchemaParser = new SchemaDOMParser(new SchemaParsingConfig()); fSchemaParser.setSupportedVersion(fSupportedVersion); //REVISIT: pass to constructor? } // it should be possible to use the same XSDHandler to parse // multiple schema documents; this will allow one to be // constructed. public XSDHandler (XSGrammarBucket gBucket, short schemaVersion, XSConstraints xsConstraints) { this(schemaVersion, xsConstraints); fGrammarBucket = gBucket; // Note: don't use SchemaConfiguration internally // we will get stack overflaw because // XMLSchemaValidator will be instantiating XSDHandler... fSchemaGrammarDescription = new XSDDescription(); } // end constructor /** * This method initiates the parse of a schema. It will likely be * called from the Validator and it will make the * resulting grammar available; it returns a reference to this object just * in case. A reset(XMLComponentManager) must be called before this methods is called. * @param is * @param desc * @param locationPairs * @return the SchemaGrammar * @throws IOException */ public SchemaGrammar parseSchema(XMLInputSource is, XSDDescription desc, Hashtable locationPairs) throws IOException { fLocationPairs = locationPairs; fSchemaParser.resetNodePool(); SchemaGrammar grammar = null; String schemaNamespace = null; short referType = desc.getContextType(); // if loading using JAXP schemaSource property, or using grammar caching loadGrammar // the desc.targetNamespace is always null. // Therefore we should not attempt to find out if // the schema is already in the bucket, since in the case we have // no namespace schema in the bucket, findGrammar will always return the // no namespace schema. if (referType != XSDDescription.CONTEXT_PREPARSE){ // first try to find it in the bucket/pool, return if one is found if(fHonourAllSchemaLocations && referType == XSDDescription.CONTEXT_IMPORT && isExistingGrammar(desc)) { grammar = fGrammarBucket.getGrammar(desc.getTargetNamespace()); } else { grammar = findGrammar(desc); } if (grammar != null) return grammar; schemaNamespace = desc.getTargetNamespace(); // handle empty string URI as null if (schemaNamespace != null) { schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); } } // before parsing a schema, need to clear registries associated with // parsing schemas prepareForParse(); Element schemaRoot = null; // first phase: construct trees. if (is instanceof DOMInputSource) { schemaRoot = getSchemaDocument(schemaNamespace, (DOMInputSource) is, referType == XSDDescription.CONTEXT_PREPARSE, referType, null); } // DOMInputSource else if (is instanceof SAXInputSource) { schemaRoot = getSchemaDocument(schemaNamespace, (SAXInputSource) is, referType == XSDDescription.CONTEXT_PREPARSE, referType, null); } // SAXInputSource else if (is instanceof StAXInputSource) { schemaRoot = getSchemaDocument(schemaNamespace, (StAXInputSource) is, referType == XSDDescription.CONTEXT_PREPARSE, referType, null); } // StAXInputSource else { schemaRoot = getSchemaDocument(schemaNamespace, is, referType == XSDDescription.CONTEXT_PREPARSE, referType, null); } //is instanceof XMLInputSource if (schemaRoot == null) { // something went wrong right off the hop return null; } if (referType == XSDDescription.CONTEXT_PREPARSE) { Element schemaElem = schemaRoot; schemaNamespace = DOMUtil.getAttrValue(schemaElem, SchemaSymbols.ATT_TARGETNAMESPACE); if(schemaNamespace != null && schemaNamespace.length() > 0) { // Since now we've discovered a namespace, we need to update xsd key // and store this schema in traversed schemas bucket schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); desc.setTargetNamespace(schemaNamespace); } else { schemaNamespace = null; } grammar = findGrammar(desc); if (grammar != null) return grammar; String schemaId = XMLEntityManager.expandSystemId(is.getSystemId(), is.getBaseSystemId(), false); XSDKey key = new XSDKey(schemaId, referType, schemaNamespace); fTraversed.put(key, schemaRoot); if (schemaId != null) { fDoc2SystemId.put(schemaRoot, schemaId); } } // before constructing trees and traversing a schema, need to reset // all traversers and clear all registries prepareForTraverse(); fRoot = constructTrees(schemaRoot, is.getSystemId(), desc); if (fRoot == null) { return null; } // second phase: fill global registries. buildGlobalNameRegistries(); // third phase: call traversers ArrayList annotationInfo = fValidateAnnotations ? new ArrayList() : null; traverseSchemas(annotationInfo); // fourth phase: handle local element decls traverseLocalElements(); // fifth phase: handle Keyrefs resolveKeyRefs(); // sixth phase: validate attribute of non-schema namespaces // REVISIT: skip this for now. we really don't want to do it. //fAttributeChecker.checkNonSchemaAttributes(fGrammarBucket); // seventh phase: store imported grammars // for all grammars with <import>s for (int i = fAllTNSs.size() - 1; i >= 0; i--) { // get its target namespace String tns = (String)fAllTNSs.elementAt(i); // get all namespaces it imports Vector ins = (Vector)fImportMap.get(tns); // get the grammar SchemaGrammar sg = fGrammarBucket.getGrammar(emptyString2Null(tns)); if (sg == null) continue; SchemaGrammar isg; // for imported namespace int count = 0; for (int j = 0; j < ins.size(); j++) { // get imported grammar isg = fGrammarBucket.getGrammar((String)ins.elementAt(j)); // reuse the same vector if (isg != null) ins.setElementAt(isg, count++); } ins.setSize(count); // set the imported grammars sg.setImportedGrammars(ins); } /** validate annotations **/ if (fValidateAnnotations && annotationInfo.size() > 0) { validateAnnotations(annotationInfo); } // and return. return fGrammarBucket.getGrammar(fRoot.fTargetNamespace); } // end parseSchema private void validateAnnotations(ArrayList annotationInfo) { if (fAnnotationValidator == null) { createAnnotationValidator(); } final int size = annotationInfo.size(); final XMLInputSource src = new XMLInputSource(null, null, null); fGrammarBucketAdapter.refreshGrammars(fGrammarBucket); for (int i = 0; i < size; i += 2) { src.setSystemId((String) annotationInfo.get(i)); XSAnnotationInfo annotation = (XSAnnotationInfo) annotationInfo.get(i+1); while (annotation != null) { src.setCharacterStream(new StringReader(annotation.fAnnotation)); try { fAnnotationValidator.parse(src); } catch (IOException exc) {} annotation = annotation.next; } } } private void createAnnotationValidator() { fAnnotationValidator = new XML11Configuration(); fGrammarBucketAdapter = new XSAnnotationGrammarPool(); fAnnotationValidator.setFeature(VALIDATION, true); fAnnotationValidator.setFeature(XMLSCHEMA_VALIDATION, true); fAnnotationValidator.setProperty(XMLGRAMMAR_POOL, fGrammarBucketAdapter); /** Set error handler. **/ XMLErrorHandler errorHandler = fErrorReporter.getErrorHandler(); fAnnotationValidator.setProperty(ERROR_HANDLER, (errorHandler != null) ? errorHandler : new DefaultErrorHandler()); /** Set locale. **/ Locale locale = fErrorReporter.getLocale(); fAnnotationValidator.setProperty(LOCALE, locale); } /** * Pull the grammar out of the bucket simply using * its TNS as a key */ SchemaGrammar getGrammar(String tns) { return fGrammarBucket.getGrammar(tns); } /** * First try to find a grammar in the bucket, if failed, consult the * grammar pool. If a grammar is found in the pool, then add it (and all * imported ones) into the bucket. */ protected SchemaGrammar findGrammar(XSDDescription desc) { SchemaGrammar sg = fGrammarBucket.getGrammar(desc.getTargetNamespace()); if (sg == null) { if (fGrammarPool != null) { sg = (SchemaGrammar)fGrammarPool.retrieveGrammar(desc); if (sg != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(sg, true)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? reportSchemaWarning("GrammarConflict", null, null); sg = null; } } } } return sg; } // may wish to have setter methods for ErrorHandler, // EntityResolver... private static final String[][] NS_ERROR_CODES = { {"src-include.2.1", "src-include.2.1"}, {"src-redefine.3.1", "src-redefine.3.1"}, {"src-import.3.1", "src-import.3.2"}, null, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"} }; private static final String[] ELE_ERROR_CODES = { "src-include.1", "src-redefine.2", "src-import.2", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4" }; // This method does several things: // It constructs an instance of an XSDocumentInfo object using the // schemaRoot node. Then, for each <include>, // <redefine>, and <import> children, it attempts to resolve the // requested schema document, initiates a DOM parse, and calls // itself recursively on that document's root. It also records in // the DependencyMap object what XSDocumentInfo objects its XSDocumentInfo // depends on. // It also makes sure the targetNamespace of the schema it was // called to parse is correct. protected XSDocumentInfo constructTrees(Element schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { // note that attributes are freed at end of traverseSchemas() currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, schemaRoot); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, schemaRoot); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // for instance and import, the two NS's must be the same else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace); } else if(fHonourAllSchemaLocations && referType == XSDDescription.CONTEXT_IMPORT) { sg = findGrammar(desc); if(sg == null) { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone(), fSymbolTable); fGrammarBucket.putGrammar(sg); } } else { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone(), fSymbolTable); fGrammarBucket.putGrammar(sg); } // store the document and its location // REVISIT: don't expose the DOM tree sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaElement)); fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = schemaRoot; Element newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] importAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)importAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)importAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); // a document can't import another document with the same namespace if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError(schemaNamespace != null ? "src-import.1.1" : "src-import.1.2", new Object [] {schemaNamespace}, child); } // check contents and process optional annotations Element importChild = DOMUtil.getFirstChildElement(child); if(importChild != null ) { String importComponentType = DOMUtil.getLocalName(importChild); if (importComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // promoting annotations to parent component sg.addAnnotation( fElementTraverser.traverseAnnotationDecl(importChild, importAttrs, true, currSchemaInfo)); } else { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", importComponentType}, child); } if(DOMUtil.getNextSiblingElement(importChild) != null) { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", DOMUtil.getLocalName(DOMUtil.getNextSiblingElement(importChild))}, child); } } else { String text = DOMUtil.getSyntheticAnnotation(child); if (text != null) { sg.addAnnotation(fElementTraverser.traverseSyntheticAnnotation(child, text, importAttrs, true, currSchemaInfo)); } } fAttributeChecker.returnAttrArray(importAttrs, currSchemaInfo); // if this namespace has not been imported by this document, // then import if multiple imports support is enabled. if(currSchemaInfo.isAllowedNS(schemaNamespace)) { if(!fHonourAllSchemaLocations) continue; } else { currSchemaInfo.addAllowedNS(schemaNamespace); } // also record the fact that one namespace imports another one // convert null to "" String tns = null2EmptyString(currSchemaInfo.fTargetNamespace); // get all namespaces imported by this one Vector ins = (Vector)fImportMap.get(tns); // if no namespace was imported, create new Vector if (ins == null) { // record that this one imports other(s) fAllTNSs.addElement(tns); ins = new Vector(); fImportMap.put(tns, ins); ins.addElement(schemaNamespace); } else if (!ins.contains(schemaNamespace)){ ins.addElement(schemaNamespace); } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId(doc2SystemId(schemaRoot)); + fSchemaGrammarDescription.setLiteralSystemId(schemaHint); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); // if a grammar with the same namespace and location exists (or being // built), ignore this one (don't traverse it). if ((!fHonourAllSchemaLocations && findGrammar(fSchemaGrammarDescription) != null) || isExistingGrammar(fSchemaGrammarDescription)) continue; // If "findGrammar" returns a grammar, then this is not the // the first time we see a location for a given namespace. // Don't consult the location pair hashtable in this case, // otherwise the location will be ignored because it'll get // resolved to the same location as the first hint. newSchemaRoot = resolveSchema(fSchemaGrammarDescription, false, child, findGrammar(fSchemaGrammarDescription) == null); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; // store the namespace decls of the redefine element if (localName.equals(SchemaSymbols.ELT_REDEFINE)) { fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport)); } // check annotations. Must do this here to avoid having to // re-parse attributes later if(localName.equals(SchemaSymbols.ELT_INCLUDE)) { Element includeChild = DOMUtil.getFirstChildElement(child); if(includeChild != null ) { String includeComponentType = DOMUtil.getLocalName(includeChild); if (includeComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // promoting annotations to parent component sg.addAnnotation( fElementTraverser.traverseAnnotationDecl(includeChild, includeAttrs, true, currSchemaInfo)); } else { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", includeComponentType}, child); } if(DOMUtil.getNextSiblingElement(includeChild) != null) { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", DOMUtil.getLocalName(DOMUtil.getNextSiblingElement(includeChild))}, child); } } else { String text = DOMUtil.getSyntheticAnnotation(child); if (text != null) { sg.addAnnotation(fElementTraverser.traverseSyntheticAnnotation(child, text, includeAttrs, true, currSchemaInfo)); } } } else { for (Element redefinedChild = DOMUtil.getFirstChildElement(child); redefinedChild != null; redefinedChild = DOMUtil.getNextSiblingElement(redefinedChild)) { String redefinedComponentType = DOMUtil.getLocalName(redefinedChild); if (redefinedComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // promoting annotations to parent component sg.addAnnotation( fElementTraverser.traverseAnnotationDecl(redefinedChild, includeAttrs, true, currSchemaInfo)); DOMUtil.setHidden(redefinedChild, fHiddenNodes); } else { String text = DOMUtil.getSyntheticAnnotation(child); if (text != null) { sg.addAnnotation(fElementTraverser.traverseSyntheticAnnotation(child, text, includeAttrs, true, currSchemaInfo)); } } // catch all other content errors later } } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) { reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); } // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId(doc2SystemId(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = resolveSchema(fSchemaGrammarDescription, mustResolve, child, true); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = newSchemaRoot == null ? null : (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees private boolean isExistingGrammar(XSDDescription desc) { SchemaGrammar sg = fGrammarBucket.getGrammar(desc.getTargetNamespace()); if(sg == null) { return findGrammar(desc) != null; } else { try { return sg.getDocumentLocations().contains(XMLEntityManager.expandSystemId(desc.getLiteralSystemId(), desc.getBaseSystemId(), false)); } catch (MalformedURIException e) { return false; } } } // This method builds registries for all globally-referenceable // names. A registry will be built for each symbol space defined // by the spec. It is also this method's job to rename redefined // components, and to record which components redefine others (so // that implicit redefinitions of groups and attributeGroups can be handled). protected void buildGlobalNameRegistries() { // Starting with fRoot, we examine each child of the schema // element. Skipping all imports and includes, we record the names // of all other global components (and children of <redefine>). We // also put <redefine> names in a registry that we look through in // case something needs renaming. Once we're done with a schema we // set its Document node to hidden so that we don't try to traverse // it again; then we look to its Dependency map entry. We keep a // stack of schemas that we haven't yet finished processing; this // is a depth-first traversal. Stack schemasToProcess = new Stack(); schemasToProcess.push(fRoot); while (!schemasToProcess.empty()) { XSDocumentInfo currSchemaDoc = (XSDocumentInfo)schemasToProcess.pop(); Element currDoc = currSchemaDoc.fSchemaElement; if(DOMUtil.isHidden(currDoc, fHiddenNodes)){ // must have processed this already! continue; } Element currRoot = currDoc; // process this schema's global decls boolean dependenciesCanOccur = true; for (Element globalComp = DOMUtil.getFirstChildElement(currRoot); globalComp != null; globalComp = DOMUtil.getNextSiblingElement(globalComp)) { // this loop makes sure the <schema> element ordering is // also valid. if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_ANNOTATION)) { //skip it; traverse it later continue; } else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_INCLUDE) || DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_IMPORT)) { if (!dependenciesCanOccur) { reportSchemaError("s4s-elt-invalid-content.3", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } DOMUtil.setHidden(globalComp, fHiddenNodes); } else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) { if (!dependenciesCanOccur) { reportSchemaError("s4s-elt-invalid-content.3", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } for (Element redefineComp = DOMUtil.getFirstChildElement(globalComp); redefineComp != null; redefineComp = DOMUtil.getNextSiblingElement(redefineComp)) { String lName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME); if (lName.length() == 0) // an error we'll catch later continue; String qName = currSchemaDoc.fTargetNamespace == null ? ","+lName: currSchemaDoc.fTargetNamespace +","+lName; String componentType = DOMUtil.getLocalName(redefineComp); if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, fUnparsedAttributeGroupRegistrySub, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kkids: renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_ATTRIBUTEGROUP, lName, targetLName); } else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) || (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) { checkForDuplicateNames(qName, fUnparsedTypeRegistry, fUnparsedTypeRegistrySub, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME) + REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kkids: if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_COMPLEXTYPE, lName, targetLName); } else { // must be simpleType renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_SIMPLETYPE, lName, targetLName); } } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { checkForDuplicateNames(qName, fUnparsedGroupRegistry, fUnparsedGroupRegistrySub, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kids: renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_GROUP, lName, targetLName); } } // end march through <redefine> children // and now set as traversed //DOMUtil.setHidden(globalComp); } else { String lName = DOMUtil.getAttrValue(globalComp, SchemaSymbols.ATT_NAME); String componentType = DOMUtil.getLocalName(globalComp); // In XML Schema 1.1, a defaultOpenContent element may occur if (componentType.equals(SchemaSymbols.ELT_DEFAULTOPENCONTENT)) { if (fSchemaVersion < Constants.SCHEMA_VERSION_1_1 || !dependenciesCanOccur) { reportSchemaError("s4s-elt-invalid-content.3", new Object [] {componentType}, globalComp); } // skip it; traverse it later dependenciesCanOccur = false; continue; } dependenciesCanOccur = false; if (lName.length() == 0) // an error we'll catch later continue; String qName = currSchemaDoc.fTargetNamespace == null? ","+lName: currSchemaDoc.fTargetNamespace +","+lName; if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) { checkForDuplicateNames(qName, fUnparsedAttributeRegistry, fUnparsedAttributeRegistrySub, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, fUnparsedAttributeGroupRegistrySub, globalComp, currSchemaDoc); } else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) || (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) { checkForDuplicateNames(qName, fUnparsedTypeRegistry, fUnparsedTypeRegistrySub, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) { checkForDuplicateNames(qName, fUnparsedElementRegistry, fUnparsedElementRegistrySub, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { checkForDuplicateNames(qName, fUnparsedGroupRegistry, fUnparsedGroupRegistrySub, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) { checkForDuplicateNames(qName, fUnparsedNotationRegistry, fUnparsedNotationRegistrySub, globalComp, currSchemaDoc); } } } // end for // now we're done with this one! DOMUtil.setHidden(currDoc, fHiddenNodes); // now add the schemas this guy depends on Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc); for (int i = 0; i < currSchemaDepends.size(); i++) { schemasToProcess.push(currSchemaDepends.elementAt(i)); } } // while } // end buildGlobalNameRegistries // Beginning at the first schema processing was requested for // (fRoot), this method // examines each child (global schema information item) of each // schema document (and of each <redefine> element) // corresponding to an XSDocumentInfo object. If the // readOnly field on that node has not been set, it calls an // appropriate traverser to traverse it. Once all global decls in // an XSDocumentInfo object have been traversed, it marks that object // as traversed (or hidden) in order to avoid infinite loops. It completes // when it has visited all XSDocumentInfo objects in the // DependencyMap and marked them as traversed. protected void traverseSchemas(ArrayList annotationInfo) { // the process here is very similar to that in // buildGlobalRegistries, except we can't set our schemas as // hidden for a second time; so make them all visible again // first! setSchemasVisible(fRoot); Stack schemasToProcess = new Stack(); schemasToProcess.push(fRoot); while (!schemasToProcess.empty()) { XSDocumentInfo currSchemaDoc = (XSDocumentInfo)schemasToProcess.pop(); Element currDoc = currSchemaDoc.fSchemaElement; SchemaGrammar currSG = fGrammarBucket.getGrammar(currSchemaDoc.fTargetNamespace); if(DOMUtil.isHidden(currDoc, fHiddenNodes)) { // must have processed this already! continue; } Element currRoot = currDoc; boolean sawAnnotation = false; // if XML Schema 1.1, set default attribute group if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1) { // Check that we have a 'defaultAttributes' and that we have not already processed it if (currSchemaDoc.fDefaultAttributes != null && currSchemaDoc.fDefaultAGroup != null) { currSchemaDoc.fDefaultAGroup = (XSAttributeGroupDecl) getGlobalDecl( currSchemaDoc, XSDHandler.ATTRIBUTEGROUP_TYPE, currSchemaDoc.fDefaultAttributes, currRoot); } } // traverse this schema's global decls for (Element globalComp = DOMUtil.getFirstVisibleChildElement(currRoot, fHiddenNodes); globalComp != null; globalComp = DOMUtil.getNextVisibleSiblingElement(globalComp, fHiddenNodes)) { DOMUtil.setHidden(globalComp, fHiddenNodes); String componentType = DOMUtil.getLocalName(globalComp); // includes and imports will not show up here! if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) { // use the namespace decls for the redefine, instead of for the parent <schema> currSchemaDoc.backupNSSupport((SchemaNamespaceSupport)fRedefine2NSSupport.get(globalComp)); for (Element redefinedComp = DOMUtil.getFirstVisibleChildElement(globalComp, fHiddenNodes); redefinedComp != null; redefinedComp = DOMUtil.getNextVisibleSiblingElement(redefinedComp, fHiddenNodes)) { String redefinedComponentType = DOMUtil.getLocalName(redefinedComp); DOMUtil.setHidden(redefinedComp, fHiddenNodes); if (redefinedComponentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fAttributeGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { fComplexTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_GROUP)) { fGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { fSimpleTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } // annotations will have been processed already; this is now // unnecessary //else if (redefinedComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // fElementTraverser.traverseAnnotationDecl(redefinedComp, null, true, currSchemaDoc); //} else { reportSchemaError("s4s-elt-must-match.1", new Object [] {DOMUtil.getLocalName(globalComp), "(annotation | (simpleType | complexType | group | attributeGroup))*", redefinedComponentType}, redefinedComp); } } // end march through <redefine> children currSchemaDoc.restoreNSSupport(); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) { fAttributeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fAttributeGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { fComplexTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) { fElementTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { fGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) { fNotationTraverser.traverse(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { fSimpleTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ANNOTATION)) { currSG.addAnnotation(fElementTraverser.traverseAnnotationDecl(globalComp, currSchemaDoc.getSchemaAttrs(), true, currSchemaDoc)); sawAnnotation = true; } else if (fSchemaVersion == Constants.SCHEMA_VERSION_1_1 && componentType.equals(SchemaSymbols.ELT_DEFAULTOPENCONTENT)) { currSchemaDoc.fDefaultOpenContent = fComplexTypeTraverser.traverseOpenContent(globalComp, currSchemaDoc, currSG, true); } else { reportSchemaError("s4s-elt-invalid-content.1", new Object [] {SchemaSymbols.ELT_SCHEMA, DOMUtil.getLocalName(globalComp)}, globalComp); } } // end for if (!sawAnnotation) { String text = DOMUtil.getSyntheticAnnotation(currRoot); if (text != null) { currSG.addAnnotation(fElementTraverser.traverseSyntheticAnnotation(currRoot, text, currSchemaDoc.getSchemaAttrs(), true, currSchemaDoc)); } } /** Collect annotation information for validation. **/ if (annotationInfo != null) { XSAnnotationInfo info = currSchemaDoc.getAnnotations(); /** Only add annotations to the list if there were any in this document. **/ if (info != null) { annotationInfo.add(doc2SystemId(currDoc)); annotationInfo.add(info); } } // now we're done with this one! currSchemaDoc.returnSchemaAttrs(); DOMUtil.setHidden(currDoc, fHiddenNodes); // now add the schemas this guy depends on Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc); for (int i = 0; i < currSchemaDepends.size(); i++) { schemasToProcess.push(currSchemaDepends.elementAt(i)); } } // while } // end traverseSchemas // store whether we have reported an error about that no grammar // is found for the given namespace uri private Vector fReportedTNS = null; // check whether we need to report an error against the given uri. // if we have reported an error, then we don't need to report again; // otherwise we reported the error, and remember this fact. private final boolean needReportTNSError(String uri) { if (fReportedTNS == null) fReportedTNS = new Vector(); else if (fReportedTNS.contains(uri)) return false; fReportedTNS.addElement(uri); return true; } private static final String[] COMP_TYPE = { null, // index 0 "attribute declaration", "attribute group", "element declaration", "group", "identity constraint", "notation", "type definition", }; private static final String[] CIRCULAR_CODES = { "Internal-Error", "Internal-Error", "src-attribute_group.3", "e-props-correct.6", "mg-props-correct.2", "Internal-Error", "Internal-Error", "st-props-correct.2", //or ct-props-correct.3 }; // since it is forbidden for traversers to talk to each other // directly (except wen a traverser encounters a local declaration), // this provides a generic means for a traverser to call // for the traversal of some declaration. An XSDocumentInfo is // required because the XSDocumentInfo that the traverser is traversing // may bear no relation to the one the handler is operating on. // This method will: // 1. See if a global definition matching declToTraverse exists; // 2. if so, determine if there is a path from currSchema to the // schema document where declToTraverse lives (i.e., do a lookup // in DependencyMap); // 3. depending on declType (which will be relevant to step 1 as // well), call the appropriate traverser with the appropriate // XSDocumentInfo object. // This method returns whatever the traverser it called returned; // this will be an Object of some kind // that lives in the Grammar. protected Object getGlobalDecl(XSDocumentInfo currSchema, int declType, QName declToTraverse, Element elmNode) { if (DEBUG_NODE_POOL) { System.out.println("TRAVERSE_GL: "+declToTraverse.toString()); } // from the schema spec, all built-in types are present in all schemas, // so if the requested component is a type, and could be found in the // default schema grammar, we should return that type. // otherwise (since we would support user-defined schema grammar) we'll // use the normal way to get the decl if (declToTraverse.uri != null && declToTraverse.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { if (declType == TYPEDECL_TYPE) { Object retObj = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(declToTraverse.localpart); if (retObj != null) return retObj; } } // now check whether this document can access the requsted namespace if (!currSchema.isAllowedNS(declToTraverse.uri)) { // cannot get to this schema from the one containing the requesting decl if (currSchema.needReportTNSError(declToTraverse.uri)) { String code = declToTraverse.uri == null ? "src-resolve.4.1" : "src-resolve.4.2"; reportSchemaError(code, new Object[]{fDoc2SystemId.get(currSchema.fSchemaElement), declToTraverse.uri, declToTraverse.rawname}, elmNode); } return null; } // check whether there is grammar for the requested namespace SchemaGrammar sGrammar = fGrammarBucket.getGrammar(declToTraverse.uri); if (sGrammar == null) { if (needReportTNSError(declToTraverse.uri)) reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode); return null; } // if there is such grammar, check whether the requested component is in the grammar Object retObj = null; switch (declType) { case ATTRIBUTE_TYPE : retObj = sGrammar.getGlobalAttributeDecl(declToTraverse.localpart); break; case ATTRIBUTEGROUP_TYPE : retObj = sGrammar.getGlobalAttributeGroupDecl(declToTraverse.localpart); break; case ELEMENT_TYPE : retObj = sGrammar.getGlobalElementDecl(declToTraverse.localpart); break; case GROUP_TYPE : retObj = sGrammar.getGlobalGroupDecl(declToTraverse.localpart); break; case IDENTITYCONSTRAINT_TYPE : retObj = sGrammar.getIDConstraintDecl(declToTraverse.localpart); break; case NOTATION_TYPE : retObj = sGrammar.getGlobalNotationDecl(declToTraverse.localpart); break; case TYPEDECL_TYPE : retObj = sGrammar.getGlobalTypeDecl(declToTraverse.localpart); break; } // if the component is parsed, return it if (retObj != null) return retObj; XSDocumentInfo schemaWithDecl = null; Element decl = null; XSDocumentInfo declDoc = null; // the component is not parsed, try to find a DOM element for it String declKey = declToTraverse.uri == null? ","+declToTraverse.localpart: declToTraverse.uri+","+declToTraverse.localpart; switch (declType) { case ATTRIBUTE_TYPE : decl = (Element)fUnparsedAttributeRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedAttributeRegistrySub.get(declKey); break; case ATTRIBUTEGROUP_TYPE : decl = (Element)fUnparsedAttributeGroupRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedAttributeGroupRegistrySub.get(declKey); break; case ELEMENT_TYPE : decl = (Element)fUnparsedElementRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedElementRegistrySub.get(declKey); break; case GROUP_TYPE : decl = (Element)fUnparsedGroupRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedGroupRegistrySub.get(declKey); break; case IDENTITYCONSTRAINT_TYPE : decl = (Element)fUnparsedIdentityConstraintRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedIdentityConstraintRegistrySub.get(declKey); break; case NOTATION_TYPE : decl = (Element)fUnparsedNotationRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedNotationRegistrySub.get(declKey); break; case TYPEDECL_TYPE : decl = (Element)fUnparsedTypeRegistry.get(declKey); declDoc = (XSDocumentInfo)fUnparsedTypeRegistrySub.get(declKey); break; default: reportSchemaError("Internal-Error", new Object [] {"XSDHandler asked to locate component of type " + declType + "; it does not recognize this type!"}, elmNode); } // no DOM element found, so the component can't be located if (decl == null) { reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode); return null; } // get the schema doc containing the component to be parsed // it should always return non-null value, but since null-checking // comes for free, let's be safe and check again schemaWithDecl = findXSDocumentForDecl(currSchema, decl, declDoc); if (schemaWithDecl == null) { // cannot get to this schema from the one containing the requesting decl String code = declToTraverse.uri == null ? "src-resolve.4.1" : "src-resolve.4.2"; reportSchemaError(code, new Object[]{fDoc2SystemId.get(currSchema.fSchemaElement), declToTraverse.uri, declToTraverse.rawname}, elmNode); return null; } // a component is hidden, meaning either it's traversed, or being traversed. // but we didn't find it in the grammar, so it's the latter case, and // a circular reference. error! if (DOMUtil.isHidden(decl, fHiddenNodes)) { String code = CIRCULAR_CODES[declType]; if (declType == TYPEDECL_TYPE) { if (SchemaSymbols.ELT_COMPLEXTYPE.equals(DOMUtil.getLocalName(decl))) code = "ct-props-correct.3"; } // decl must not be null if we're here... reportSchemaError(code, new Object [] {declToTraverse.prefix+":"+declToTraverse.localpart}, elmNode); return null; } DOMUtil.setHidden(decl, fHiddenNodes); SchemaNamespaceSupport nsSupport = null; // if the parent is <redefine> use the namespace delcs for it. Element parent = DOMUtil.getParent(decl); if (DOMUtil.getLocalName(parent).equals(SchemaSymbols.ELT_REDEFINE)) nsSupport = (SchemaNamespaceSupport)fRedefine2NSSupport.get(parent); // back up the current SchemaNamespaceSupport, because we need to provide // a fresh one to the traverseGlobal methods. schemaWithDecl.backupNSSupport(nsSupport); // traverse the referenced global component switch (declType) { case ATTRIBUTE_TYPE : retObj = fAttributeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case ATTRIBUTEGROUP_TYPE : retObj = fAttributeGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case ELEMENT_TYPE : retObj = fElementTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case GROUP_TYPE : retObj = fGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case IDENTITYCONSTRAINT_TYPE : // identity constraints should have been parsed already... // we should never get here retObj = null; break; case NOTATION_TYPE : retObj = fNotationTraverser.traverse(decl, schemaWithDecl, sGrammar); break; case TYPEDECL_TYPE : if (DOMUtil.getLocalName(decl).equals(SchemaSymbols.ELT_COMPLEXTYPE)) retObj = fComplexTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); else retObj = fSimpleTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); } // restore the previous SchemaNamespaceSupport, so that the caller can get // proper namespace binding. schemaWithDecl.restoreNSSupport(); return retObj; } // getGlobalDecl(XSDocumentInfo, int, QName): Object // This method determines whether there is a group // (attributeGroup) which the given one has redefined by // restriction. If so, it returns it; else it returns null. // @param type: whether what's been redefined is an // attributeGroup or a group; // @param name: the QName of the component doing the redefining. // @param currSchema: schema doc in which the redefining component lives. // @return: Object representing decl redefined if present, null // otherwise. Object getGrpOrAttrGrpRedefinedByRestriction(int type, QName name, XSDocumentInfo currSchema, Element elmNode) { String realName = name.uri != null?name.uri+","+name.localpart: ","+name.localpart; String nameToFind = null; switch (type) { case ATTRIBUTEGROUP_TYPE: nameToFind = (String)fRedefinedRestrictedAttributeGroupRegistry.get(realName); break; case GROUP_TYPE: nameToFind = (String)fRedefinedRestrictedGroupRegistry.get(realName); break; default: return null; } if (nameToFind == null) return null; int commaPos = nameToFind.indexOf(","); QName qNameToFind = new QName(XMLSymbols.EMPTY_STRING, nameToFind.substring(commaPos+1), nameToFind.substring(commaPos), (commaPos == 0)? null : nameToFind.substring(0, commaPos)); Object retObj = getGlobalDecl(currSchema, type, qNameToFind, elmNode); if(retObj == null) { switch (type) { case ATTRIBUTEGROUP_TYPE: reportSchemaError("src-redefine.7.2.1", new Object []{name.localpart}, elmNode); break; case GROUP_TYPE: reportSchemaError("src-redefine.6.2.1", new Object []{name.localpart}, elmNode); break; } return null; } return retObj; } // getGrpOrAttrGrpRedefinedByRestriction(int, QName, XSDocumentInfo): Object // Since ID constraints can occur in local elements, unless we // wish to completely traverse all our DOM trees looking for ID // constraints while we're building our global name registries, // which seems terribly inefficient, we need to resolve keyrefs // after all parsing is complete. This we can simply do by running through // fIdentityConstraintRegistry and calling traverseKeyRef on all // of the KeyRef nodes. This unfortunately removes this knowledge // from the elementTraverser class (which must ignore keyrefs), // but there seems to be no efficient way around this... protected void resolveKeyRefs() { for (int i=0; i<fKeyrefStackPos; i++) { XSDocumentInfo keyrefSchemaDoc = fKeyrefsMapXSDocumentInfo[i]; keyrefSchemaDoc.fNamespaceSupport.makeGlobal(); keyrefSchemaDoc.fNamespaceSupport.setEffectiveContext( fKeyrefNamespaceContext[i] ); SchemaGrammar keyrefGrammar = fGrammarBucket.getGrammar(keyrefSchemaDoc.fTargetNamespace); // need to set <keyref> to hidden before traversing it, // because it has global scope DOMUtil.setHidden(fKeyrefs[i], fHiddenNodes); fKeyrefTraverser.traverse(fKeyrefs[i], fKeyrefElems[i], keyrefSchemaDoc, keyrefGrammar); } } // end resolveKeyRefs // an accessor method. Just makes sure callers // who want the Identity constraint registry vaguely know what they're about. protected Hashtable getIDRegistry() { return fUnparsedIdentityConstraintRegistry; } // an accessor method. protected Hashtable getIDRegistry_sub() { return fUnparsedIdentityConstraintRegistrySub; } // This method squirrels away <keyref> declarations--along with the element // decls and namespace bindings they might find handy. protected void storeKeyRef (Element keyrefToStore, XSDocumentInfo schemaDoc, XSElementDecl currElemDecl) { String keyrefName = DOMUtil.getAttrValue(keyrefToStore, SchemaSymbols.ATT_NAME); if (keyrefName.length() != 0) { String keyrefQName = schemaDoc.fTargetNamespace == null? "," + keyrefName: schemaDoc.fTargetNamespace+","+keyrefName; checkForDuplicateNames(keyrefQName, fUnparsedIdentityConstraintRegistry, fUnparsedIdentityConstraintRegistrySub, keyrefToStore, schemaDoc); } // now set up all the registries we'll need... // check array sizes if (fKeyrefStackPos == fKeyrefs.length) { Element [] elemArray = new Element [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefs, 0, elemArray, 0, fKeyrefStackPos); fKeyrefs = elemArray; XSElementDecl [] declArray = new XSElementDecl [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefElems, 0, declArray, 0, fKeyrefStackPos); fKeyrefElems = declArray; String[][] stringArray = new String [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT][]; System.arraycopy(fKeyrefNamespaceContext, 0, stringArray, 0, fKeyrefStackPos); fKeyrefNamespaceContext = stringArray; XSDocumentInfo [] xsDocumentInfo = new XSDocumentInfo [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefsMapXSDocumentInfo, 0, xsDocumentInfo, 0, fKeyrefStackPos); fKeyrefsMapXSDocumentInfo = xsDocumentInfo; } fKeyrefs[fKeyrefStackPos] = keyrefToStore; fKeyrefElems[fKeyrefStackPos] = currElemDecl; fKeyrefNamespaceContext[fKeyrefStackPos] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext(); fKeyrefsMapXSDocumentInfo[fKeyrefStackPos++] = schemaDoc; } // storeKeyref (Element, XSDocumentInfo, XSElementDecl): void /** * resolveSchema method is responsible for resolving location of the schema (using XMLEntityResolver), * and if it was succefully resolved getting the schema Document. * @param desc * @param mustResolve * @param referElement * @return A schema Element or null. */ private Element resolveSchema(XSDDescription desc, boolean mustResolve, Element referElement, boolean usePairs) { XMLInputSource schemaSource = null; try { Hashtable pairs = usePairs ? fLocationPairs : EMPTY_TABLE; schemaSource = XMLSchemaLoader.resolveDocument(desc, pairs, fEntityResolver); } catch (IOException ex) { if (mustResolve) { reportSchemaError("schema_reference.4", new Object[]{desc.getLocationHints()[0]}, referElement); } else { reportSchemaWarning("schema_reference.4", new Object[]{desc.getLocationHints()[0]}, referElement); } } if (schemaSource instanceof DOMInputSource) { return getSchemaDocument(desc.getTargetNamespace(), (DOMInputSource) schemaSource, mustResolve, desc.getContextType(), referElement); } // DOMInputSource else if (schemaSource instanceof SAXInputSource) { return getSchemaDocument(desc.getTargetNamespace(), (SAXInputSource) schemaSource, mustResolve, desc.getContextType(), referElement); } // SAXInputSource else if (schemaSource instanceof StAXInputSource) { return getSchemaDocument(desc.getTargetNamespace(), (StAXInputSource) schemaSource, mustResolve, desc.getContextType(), referElement); } // StAXInputSource return getSchemaDocument(desc.getTargetNamespace(), schemaSource, mustResolve, desc.getContextType(), referElement); } // getSchema(String, String, String, boolean, short): Document /** * getSchemaDocument method uses XMLInputSource to parse a schema document. * @param schemaNamespace * @param schemaSource * @param mustResolve * @param referType * @param referElement * @return A schema Element. */ private Element getSchemaDocument(String schemaNamespace, XMLInputSource schemaSource, boolean mustResolve, short referType, Element referElement) { boolean hasInput = true; // contents of this method will depend on the system we adopt for entity resolution--i.e., XMLEntityHandler, EntityHandler, etc. Element schemaElement = null; try { // when the system id and byte stream and character stream // of the input source are all null, it's // impossible to find the schema document. so we skip in // this case. otherwise we'll receive some NPE or // file not found errors. but schemaHint=="" is perfectly // legal for import. if (schemaSource != null && (schemaSource.getSystemId() != null || schemaSource.getByteStream() != null || schemaSource.getCharacterStream() != null)) { // When the system id of the input source is used, first try to // expand it, and check whether the same document has been // parsed before. If so, return the document corresponding to // that system id. XSDKey key = null; String schemaId = null; if (referType != XSDDescription.CONTEXT_PREPARSE){ schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); key = new XSDKey(schemaId, referType, schemaNamespace); if((schemaElement = (Element)fTraversed.get(key)) != null) { fLastSchemaWasDuplicate = true; return schemaElement; } } fSchemaParser.parse(schemaSource); Document schemaDocument = fSchemaParser.getDocument(); schemaElement = schemaDocument != null ? DOMUtil.getRoot(schemaDocument) : null; return getSchemaDocument0(key, schemaId, schemaElement); } else { hasInput = false; } } catch (IOException ex) { } return getSchemaDocument1(mustResolve, hasInput, schemaSource, referElement); } // getSchemaDocument(String, XMLInputSource, boolean, short, Element): Element /** * getSchemaDocument method uses SAXInputSource to parse a schema document. * @param schemaNamespace * @param schemaSource * @param mustResolve * @param referType * @param referElement * @return A schema Element. */ private Element getSchemaDocument(String schemaNamespace, SAXInputSource schemaSource, boolean mustResolve, short referType, Element referElement) { XMLReader parser = schemaSource.getXMLReader(); InputSource inputSource = schemaSource.getInputSource(); boolean hasInput = true; Element schemaElement = null; try { if (inputSource != null && (inputSource.getSystemId() != null || inputSource.getByteStream() != null || inputSource.getCharacterStream() != null)) { // check whether the same document has been parsed before. // If so, return the document corresponding to that system id. XSDKey key = null; String schemaId = null; if (referType != XSDDescription.CONTEXT_PREPARSE) { schemaId = XMLEntityManager.expandSystemId(inputSource.getSystemId(), schemaSource.getBaseSystemId(), false); key = new XSDKey(schemaId, referType, schemaNamespace); if ((schemaElement = (Element) fTraversed.get(key)) != null) { fLastSchemaWasDuplicate = true; return schemaElement; } } boolean namespacePrefixes = false; if (parser != null) { try { namespacePrefixes = parser.getFeature(NAMESPACE_PREFIXES); } catch (SAXException se) {} } else { try { parser = XMLReaderFactory.createXMLReader(); } // If something went wrong with the factory // just use our own SAX parser. catch (SAXException se) { parser = new SAXParser(); } try { parser.setFeature(NAMESPACE_PREFIXES, true); namespacePrefixes = true; } catch (SAXException se) {} } // If XML names and Namespace URIs are already internalized we // can avoid running them through the SymbolTable. boolean stringsInternalized = false; try { stringsInternalized = parser.getFeature(STRING_INTERNING); } catch (SAXException exc) { // The feature isn't recognized or getting it is not supported. // In either case, assume that strings are not internalized. } if (fXSContentHandler == null) { fXSContentHandler = new SchemaContentHandler(); } fXSContentHandler.reset(fSchemaParser, fSymbolTable, namespacePrefixes, stringsInternalized); parser.setContentHandler(fXSContentHandler); parser.setErrorHandler(fErrorReporter.getSAXErrorHandler()); parser.parse(inputSource); // Disconnect the schema loader and other objects from the XMLReader try { parser.setContentHandler(null); parser.setErrorHandler(null); } // Ignore any exceptions thrown by the XMLReader. Old versions of SAX // required an XMLReader to throw a NullPointerException if an attempt // to set a handler to null was made. catch (Exception e) {} Document schemaDocument = fXSContentHandler.getDocument(); schemaElement = schemaDocument != null ? DOMUtil.getRoot(schemaDocument) : null; return getSchemaDocument0(key, schemaId, schemaElement); } else { hasInput = false; } } catch (SAXException se) { } catch (IOException ioe) { } return getSchemaDocument1(mustResolve, hasInput, schemaSource, referElement); } // getSchemaDocument(String, SAXInputSource, boolean, short, Element): Element /** * getSchemaDocument method uses DOMInputSource to parse a schema document. * @param schemaNamespace * @param schemaSource * @param mustResolve * @param referType * @param referElement * @return A schema Element. */ private Element getSchemaDocument(String schemaNamespace, DOMInputSource schemaSource, boolean mustResolve, short referType, Element referElement) { boolean hasInput = true; Element schemaElement = null; Element schemaRootElement = null; final Node node = schemaSource.getNode(); short nodeType = -1; if (node != null) { nodeType = node.getNodeType(); if (nodeType == Node.DOCUMENT_NODE) { schemaRootElement = DOMUtil.getRoot((Document) node); } else if (nodeType == Node.ELEMENT_NODE) { schemaRootElement = (Element) node; } } try { if (schemaRootElement != null) { // check whether the same document has been parsed before. // If so, return the document corresponding to that system id. XSDKey key = null; String schemaId = null; if (referType != XSDDescription.CONTEXT_PREPARSE) { schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); boolean isDocument = (nodeType == Node.DOCUMENT_NODE); if (!isDocument) { Node parent = schemaRootElement.getParentNode(); if (parent != null) { isDocument = (parent.getNodeType() == Node.DOCUMENT_NODE); } } if (isDocument) { key = new XSDKey(schemaId, referType, schemaNamespace); if ((schemaElement = (Element) fTraversed.get(key)) != null) { fLastSchemaWasDuplicate = true; return schemaElement; } } } schemaElement = schemaRootElement; return getSchemaDocument0(key, schemaId, schemaElement); } else { hasInput = false; } } catch (IOException ioe) { } return getSchemaDocument1(mustResolve, hasInput, schemaSource, referElement); } // getSchemaDocument(String, DOMInputSource, boolean, short, Element): Element /** * getSchemaDocument method uses StAXInputSource to parse a schema document. * @param schemaNamespace * @param schemaSource * @param mustResolve * @param referType * @param referElement * @return A schema Element. */ private Element getSchemaDocument(String schemaNamespace, StAXInputSource schemaSource, boolean mustResolve, short referType, Element referElement) { Element schemaElement = null; try { final boolean consumeRemainingContent = schemaSource.shouldConsumeRemainingContent(); final XMLStreamReader streamReader = schemaSource.getXMLStreamReader(); final XMLEventReader eventReader = schemaSource.getXMLEventReader(); // check whether the same document has been parsed before. // If so, return the document corresponding to that system id. XSDKey key = null; String schemaId = null; if (referType != XSDDescription.CONTEXT_PREPARSE) { schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); boolean isDocument = consumeRemainingContent; if (!isDocument) { if (streamReader != null) { isDocument = (streamReader.getEventType() == XMLStreamReader.START_DOCUMENT); } else { isDocument = eventReader.peek().isStartDocument(); } } if (isDocument) { key = new XSDKey(schemaId, referType, schemaNamespace); if ((schemaElement = (Element) fTraversed.get(key)) != null) { fLastSchemaWasDuplicate = true; return schemaElement; } } } if (fStAXSchemaParser == null) { fStAXSchemaParser = new StAXSchemaParser(); } fStAXSchemaParser.reset(fSchemaParser, fSymbolTable); if (streamReader != null) { fStAXSchemaParser.parse(streamReader); if (consumeRemainingContent) { while (streamReader.hasNext()) { streamReader.next(); } } } else { fStAXSchemaParser.parse(eventReader); if (consumeRemainingContent) { while (eventReader.hasNext()) { eventReader.nextEvent(); } } } Document schemaDocument = fStAXSchemaParser.getDocument(); schemaElement = schemaDocument != null ? DOMUtil.getRoot(schemaDocument) : null; return getSchemaDocument0(key, schemaId, schemaElement); } catch (XMLStreamException e) { } catch (IOException e) { } return getSchemaDocument1(mustResolve, true, schemaSource, referElement); } // getSchemaDocument(String, StAXInputSource, boolean, short, Element): Element /** * Code shared between the various getSchemaDocument() methods which * stores mapping information for the document. */ private Element getSchemaDocument0(XSDKey key, String schemaId, Element schemaElement) { // now we need to store the mapping information from system id // to the document. also from the document to the system id. if (key != null) { fTraversed.put(key, schemaElement); } if (schemaId != null) { fDoc2SystemId.put(schemaElement, schemaId); } fLastSchemaWasDuplicate = false; return schemaElement; } // getSchemaDocument0(XSDKey, String, Element): Element /** * Error handling code shared between the various getSchemaDocument() methods. */ private Element getSchemaDocument1(boolean mustResolve, boolean hasInput, XMLInputSource schemaSource, Element referElement) { // either an error occured (exception), or empty input source was // returned, we need to report an error or a warning if (mustResolve) { if (hasInput) { reportSchemaError("schema_reference.4", new Object[]{schemaSource.getSystemId()}, referElement); } else { reportSchemaError("schema_reference.4", new Object[]{schemaSource == null ? "" : schemaSource.getSystemId()}, referElement); } } else if (hasInput) { reportSchemaWarning("schema_reference.4", new Object[]{schemaSource.getSystemId()}, referElement); } fLastSchemaWasDuplicate = false; return null; } // getSchemaDocument1(boolean, boolean, XMLInputSource, Element): Element // initialize all the traversers. // this should only need to be called once during the construction // of this object; it creates the traversers that will be used to // construct schemaGrammars. private void createTraversers() { fAttributeChecker = new XSAttributeChecker(this); fAttributeGroupTraverser = new XSDAttributeGroupTraverser(this, fAttributeChecker); fAttributeTraverser = new XSDAttributeTraverser(this, fAttributeChecker); fComplexTypeTraverser = new XSDComplexTypeTraverser(this, fAttributeChecker); fElementTraverser = new XSDElementTraverser(this, fAttributeChecker); fGroupTraverser = new XSDGroupTraverser(this, fAttributeChecker); fKeyrefTraverser = new XSDKeyrefTraverser(this, fAttributeChecker); fNotationTraverser = new XSDNotationTraverser(this, fAttributeChecker); fSimpleTypeTraverser = new XSDSimpleTypeTraverser(this, fAttributeChecker); fTypeAlternativeTraverser = new XSDTypeAlternativeTraverser(this, fAttributeChecker); fUniqueOrKeyTraverser = new XSDUniqueOrKeyTraverser(this, fAttributeChecker); fWildCardTraverser = new XSDWildcardTraverser(this, fAttributeChecker); } // createTraversers() // before parsing a schema, need to clear registries associated with // parsing schemas void prepareForParse() { fTraversed.clear(); fDoc2SystemId.clear(); fHiddenNodes.clear(); fLastSchemaWasDuplicate = false; } // before traversing a schema's parse tree, need to reset all traversers and // clear all registries void prepareForTraverse() { fUnparsedAttributeRegistry.clear(); fUnparsedAttributeGroupRegistry.clear(); fUnparsedElementRegistry.clear(); fUnparsedGroupRegistry.clear(); fUnparsedIdentityConstraintRegistry.clear(); fUnparsedNotationRegistry.clear(); fUnparsedTypeRegistry.clear(); fUnparsedAttributeRegistrySub.clear(); fUnparsedAttributeGroupRegistrySub.clear(); fUnparsedElementRegistrySub.clear(); fUnparsedGroupRegistrySub.clear(); fUnparsedIdentityConstraintRegistrySub.clear(); fUnparsedNotationRegistrySub.clear(); fUnparsedTypeRegistrySub.clear(); fXSDocumentInfoRegistry.clear(); fDependencyMap.clear(); fDoc2XSDocumentMap.clear(); fRedefine2XSDMap.clear(); fRedefine2NSSupport.clear(); fAllTNSs.removeAllElements(); fImportMap.clear(); fRoot = null; // clear local element stack for (int i = 0; i < fLocalElemStackPos; i++) { fParticle[i] = null; fLocalElementDecl[i] = null; fLocalElementDecl_schema[i] = null; fLocalElemNamespaceContext[i] = null; } fLocalElemStackPos = 0; // and do same for keyrefs. for (int i = 0; i < fKeyrefStackPos; i++) { fKeyrefs[i] = null; fKeyrefElems[i] = null; fKeyrefNamespaceContext[i] = null; fKeyrefsMapXSDocumentInfo[i] = null; } fKeyrefStackPos = 0; // create traversers if necessary if (fAttributeChecker == null) { createTraversers(); } // reset traversers Locale locale = fErrorReporter.getLocale(); fAttributeChecker.reset(fSymbolTable); fAttributeGroupTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fAttributeTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fComplexTypeTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fElementTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fGroupTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fKeyrefTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fNotationTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fSimpleTypeTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fTypeAlternativeTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fUniqueOrKeyTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fWildCardTraverser.reset(fSymbolTable, fValidateAnnotations, locale); fRedefinedRestrictedAttributeGroupRegistry.clear(); fRedefinedRestrictedGroupRegistry.clear(); } public void setDeclPool (XSDeclarationPool declPool){ fDeclPool = declPool; } public void reset(XMLComponentManager componentManager) { // set symbol table fSymbolTable = (SymbolTable) componentManager.getProperty(SYMBOL_TABLE); //set entity resolver fEntityResolver = (XMLEntityResolver) componentManager.getProperty(ENTITY_MANAGER); XMLEntityResolver er = (XMLEntityResolver)componentManager.getProperty(ENTITY_RESOLVER); if (er != null) fSchemaParser.setEntityResolver(er); // set error reporter fErrorReporter = (XMLErrorReporter) componentManager.getProperty(ERROR_REPORTER); try { XMLErrorHandler currErrorHandler = fErrorReporter.getErrorHandler(); // Setting a parser property can be much more expensive // than checking its value. Don't set the ERROR_HANDLER // or LOCALE properties unless they've actually changed. if (currErrorHandler != fSchemaParser.getProperty(ERROR_HANDLER)) { fSchemaParser.setProperty(ERROR_HANDLER, (currErrorHandler != null) ? currErrorHandler : new DefaultErrorHandler()); if (fAnnotationValidator != null) { fAnnotationValidator.setProperty(ERROR_HANDLER, (currErrorHandler != null) ? currErrorHandler : new DefaultErrorHandler()); } } Locale currentLocale = fErrorReporter.getLocale(); if (currentLocale != fSchemaParser.getProperty(LOCALE)) { fSchemaParser.setProperty(LOCALE, currentLocale); if (fAnnotationValidator != null) { fAnnotationValidator.setProperty(LOCALE, currentLocale); } } } catch (XMLConfigurationException e) {} try { fValidateAnnotations = componentManager.getFeature(VALIDATE_ANNOTATIONS); } catch (XMLConfigurationException e) { fValidateAnnotations = false; } try { fHonourAllSchemaLocations = componentManager.getFeature(HONOUR_ALL_SCHEMALOCATIONS); } catch (XMLConfigurationException e) { fHonourAllSchemaLocations = false; } try { fSchemaParser.setFeature( CONTINUE_AFTER_FATAL_ERROR, fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); } catch (XMLConfigurationException e) { } try { fSchemaParser.setFeature( ALLOW_JAVA_ENCODINGS, componentManager.getFeature(ALLOW_JAVA_ENCODINGS)); } catch (XMLConfigurationException e) { } try { fSchemaParser.setFeature( STANDARD_URI_CONFORMANT_FEATURE, componentManager.getFeature(STANDARD_URI_CONFORMANT_FEATURE)); } catch (XMLConfigurationException e) { } try { fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e) { fGrammarPool = null; } // security features try { fSchemaParser.setFeature( DISALLOW_DOCTYPE, componentManager.getFeature(DISALLOW_DOCTYPE)); } catch (XMLConfigurationException e) { } try { Object security = componentManager.getProperty(SECURITY_MANAGER); if (security != null){ fSchemaParser.setProperty(SECURITY_MANAGER, security); } } catch (XMLConfigurationException e) { } } // reset(XMLComponentManager) /** * Traverse all the deferred local elements. This method should be called * by traverseSchemas after we've done with all the global declarations. */ void traverseLocalElements() { fElementTraverser.fDeferTraversingLocalElements = false; for (int i = 0; i < fLocalElemStackPos; i++) { Element currElem = fLocalElementDecl[i]; //XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem)); //XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getRoot(DOMUtil.getDocument(currElem))); XSDocumentInfo currSchema = fLocalElementDecl_schema[i]; SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace); fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]); // If it's an empty particle, remove it from the containing component. if (fParticle[i].fType == XSParticleDecl.PARTICLE_EMPTY) { XSModelGroupImpl group = null; if (fParent[i] instanceof XSComplexTypeDecl) { XSParticle p = ((XSComplexTypeDecl)fParent[i]).getParticle(); if (p != null) group = (XSModelGroupImpl)p.getTerm(); } else { group = ((XSGroupDecl)fParent[i]).fModelGroup; } if (group != null) removeParticle(group, fParticle[i]); } } } private boolean removeParticle(XSModelGroupImpl group, XSParticleDecl particle) { XSParticleDecl member; for (int i = 0; i < group.fParticleCount; i++) { member = group.fParticles[i]; if (member == particle) { for (int j = i; j < group.fParticleCount-1; j++) group.fParticles[j] = group.fParticles[j+1]; group.fParticleCount--; return true; } if (member.fType == XSParticleDecl.PARTICLE_MODELGROUP) { if (removeParticle((XSModelGroupImpl)member.fValue, particle)) return true; } } return false; } // the purpose of this method is to keep up-to-date structures // we'll need for the feferred traversal of local elements. void fillInLocalElemInfo(Element elmDecl, XSDocumentInfo schemaDoc, int allContextFlags, XSObject parent, XSParticleDecl particle) { // if the stack is full, increase the size if (fParticle.length == fLocalElemStackPos) { // increase size XSParticleDecl[] newStackP = new XSParticleDecl[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fParticle, 0, newStackP, 0, fLocalElemStackPos); fParticle = newStackP; Element[] newStackE = new Element[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fLocalElementDecl, 0, newStackE, 0, fLocalElemStackPos); fLocalElementDecl = newStackE; XSDocumentInfo [] newStackE_schema = new XSDocumentInfo[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fLocalElementDecl_schema, 0, newStackE_schema, 0, fLocalElemStackPos); fLocalElementDecl_schema = newStackE_schema; int[] newStackI = new int[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fAllContext, 0, newStackI, 0, fLocalElemStackPos); fAllContext = newStackI; XSObject[] newStackC = new XSObject[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fParent, 0, newStackC, 0, fLocalElemStackPos); fParent = newStackC; String [][] newStackN = new String [fLocalElemStackPos+INC_STACK_SIZE][]; System.arraycopy(fLocalElemNamespaceContext, 0, newStackN, 0, fLocalElemStackPos); fLocalElemNamespaceContext = newStackN; } fParticle[fLocalElemStackPos] = particle; fLocalElementDecl[fLocalElemStackPos] = elmDecl; fLocalElementDecl_schema[fLocalElemStackPos] = schemaDoc; fAllContext[fLocalElemStackPos] = allContextFlags; fParent[fLocalElemStackPos] = parent; fLocalElemNamespaceContext[fLocalElemStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext(); } // end fillInLocalElemInfo(...) /** This method makes sure that * if this component is being redefined that it lives in the * right schema. It then renames the component correctly. If it * detects a collision--a duplicate definition--then it complains. * Note that redefines must be handled carefully: if there * is a collision, it may be because we're redefining something we know about * or because we've found the thing we're redefining. */ void checkForDuplicateNames(String qName, Hashtable registry, Hashtable registry_sub, Element currComp, XSDocumentInfo currSchema) { Object objElem = null; // REVISIT: when we add derivation checking, we'll have to make // sure that ID constraint collisions don't necessarily result in error messages. if ((objElem = registry.get(qName)) == null) { // just add it in! registry.put(qName, currComp); registry_sub.put(qName, currSchema); } else { Element collidingElem = (Element)objElem; XSDocumentInfo collidingElemSchema = (XSDocumentInfo)registry_sub.get(qName); if (collidingElem == currComp) return; Element elemParent = null; XSDocumentInfo redefinedSchema = null; // case where we've collided with a redefining element // (the parent of the colliding element is a redefine) boolean collidedWithRedefine = true; if ((DOMUtil.getLocalName((elemParent = DOMUtil.getParent(collidingElem))).equals(SchemaSymbols.ELT_REDEFINE))) { redefinedSchema = (XSDocumentInfo)(fRedefine2XSDMap.get(elemParent)); // case where we're a redefining element. } else if ((DOMUtil.getLocalName(DOMUtil.getParent(currComp)).equals(SchemaSymbols.ELT_REDEFINE))) { redefinedSchema = collidingElemSchema; collidedWithRedefine = false; } if (redefinedSchema != null) { //redefinition involved somehow // If both components belong to the same document then // report an error and return. if(collidingElemSchema == currSchema){ reportSchemaError("sch-props-correct.2", new Object[]{qName}, currComp); return; } String newName = qName.substring(qName.lastIndexOf(',')+1)+REDEF_IDENTIFIER; if (redefinedSchema == currSchema) { // object comp. okay here // now have to do some renaming... currComp.setAttribute(SchemaSymbols.ATT_NAME, newName); if (currSchema.fTargetNamespace == null){ registry.put(","+newName, currComp); registry_sub.put(","+newName, currSchema); } else{ registry.put(currSchema.fTargetNamespace+","+newName, currComp); registry_sub.put(currSchema.fTargetNamespace+","+newName, currSchema); } // and take care of nested redefines by calling recursively: if (currSchema.fTargetNamespace == null) checkForDuplicateNames(","+newName, registry, registry_sub, currComp, currSchema); else checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, registry_sub, currComp, currSchema); } else { // we may be redefining the wrong schema if (collidedWithRedefine) { if (currSchema.fTargetNamespace == null) checkForDuplicateNames(","+newName, registry, registry_sub, currComp, currSchema); else checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, registry_sub, currComp, currSchema); } else { // error that redefined element in wrong schema reportSchemaError("sch-props-correct.2", new Object [] {qName}, currComp); } } } else { // we've just got a flat-out collision reportSchemaError("sch-props-correct.2", new Object []{qName}, currComp); } } } // checkForDuplicateNames(String, Hashtable, Element, XSDocumentInfo):void // the purpose of this method is to take the component of the // specified type and rename references to itself so that they // refer to the object being redefined. It takes special care of // <group>s and <attributeGroup>s to ensure that information // relating to implicit restrictions is preserved for those // traversers. private void renameRedefiningComponents(XSDocumentInfo currSchema, Element child, String componentType, String oldName, String newName) { if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { Element grandKid = DOMUtil.getFirstChildElement(child); if (grandKid == null) { reportSchemaError("src-redefine.5.a.a", null, child); } else { String grandKidName = DOMUtil.getLocalName(grandKid); if (grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = DOMUtil.getNextSiblingElement(grandKid); } if (grandKid == null) { reportSchemaError("src-redefine.5.a.a", null, child); } else { grandKidName = DOMUtil.getLocalName(grandKid); if (!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) { reportSchemaError("src-redefine.5.a.b", new Object[]{grandKidName}, child); } else { Object[] attrs = fAttributeChecker.checkAttributes(grandKid, false, currSchema); QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE]; if (derivedBase == null || derivedBase.uri != currSchema.fTargetNamespace || !derivedBase.localpart.equals(oldName)) { reportSchemaError("src-redefine.5.a.c", new Object[]{grandKidName, (currSchema.fTargetNamespace==null?"":currSchema.fTargetNamespace) + "," + oldName}, child); } else { // now we have to do the renaming... if (derivedBase.prefix != null && derivedBase.prefix.length() > 0) grandKid.setAttribute( SchemaSymbols.ATT_BASE, derivedBase.prefix + ":" + newName ); else grandKid.setAttribute( SchemaSymbols.ATT_BASE, newName ); // return true; } fAttributeChecker.returnAttrArray(attrs, currSchema); } } } } else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { Element grandKid = DOMUtil.getFirstChildElement(child); if (grandKid == null) { reportSchemaError("src-redefine.5.b.a", null, child); } else { if (DOMUtil.getLocalName(grandKid).equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = DOMUtil.getNextSiblingElement(grandKid); } if (grandKid == null) { reportSchemaError("src-redefine.5.b.a", null, child); } else { // have to go one more level down; let another pass worry whether complexType is valid. Element greatGrandKid = DOMUtil.getFirstChildElement(grandKid); if (greatGrandKid == null) { reportSchemaError("src-redefine.5.b.b", null, grandKid); } else { String greatGrandKidName = DOMUtil.getLocalName(greatGrandKid); if (greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { greatGrandKid = DOMUtil.getNextSiblingElement(greatGrandKid); } if (greatGrandKid == null) { reportSchemaError("src-redefine.5.b.b", null, grandKid); } else { greatGrandKidName = DOMUtil.getLocalName(greatGrandKid); if (!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) && !greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) { reportSchemaError("src-redefine.5.b.c", new Object[]{greatGrandKidName}, greatGrandKid); } else { Object[] attrs = fAttributeChecker.checkAttributes(greatGrandKid, false, currSchema); QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE]; if (derivedBase == null || derivedBase.uri != currSchema.fTargetNamespace || !derivedBase.localpart.equals(oldName)) { reportSchemaError("src-redefine.5.b.d", new Object[]{greatGrandKidName, (currSchema.fTargetNamespace==null?"":currSchema.fTargetNamespace) + "," + oldName}, greatGrandKid); } else { // now we have to do the renaming... if (derivedBase.prefix != null && derivedBase.prefix.length() > 0) greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, derivedBase.prefix + ":" + newName ); else greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, newName ); // return true; } } } } } } } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { String processedBaseName = (currSchema.fTargetNamespace == null)? ","+oldName:currSchema.fTargetNamespace+","+oldName; int attGroupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema); if (attGroupRefsCount > 1) { reportSchemaError("src-redefine.7.1", new Object []{new Integer(attGroupRefsCount)}, child); } else if (attGroupRefsCount == 1) { // return true; } else if (currSchema.fTargetNamespace == null) fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, ","+newName); else fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { String processedBaseName = (currSchema.fTargetNamespace == null)? ","+oldName:currSchema.fTargetNamespace+","+oldName; int groupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema); if (groupRefsCount > 1) { reportSchemaError("src-redefine.6.1.1", new Object []{new Integer(groupRefsCount)}, child); } else if (groupRefsCount == 1) { // return true; } else { if (currSchema.fTargetNamespace == null) fRedefinedRestrictedGroupRegistry.put(processedBaseName, ","+newName); else fRedefinedRestrictedGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName); } } else { reportSchemaError("Internal-Error", new Object [] {"could not handle this particular <redefine>; please submit your schemas and instance document in a bug report!"}, child); } // if we get here then we must have reported an error and failed somewhere... // return false; } // renameRedefiningComponents(XSDocumentInfo, Element, String, String, String):void // this method takes a name of the form a:b, determines the URI mapped // to by a in the current SchemaNamespaceSupport object, and returns this // information in the form (nsURI,b) suitable for lookups in the global // decl Hashtables. // REVISIT: should have it return QName, instead of String. this would // save lots of string concatenation time. we can use // QName#equals() to compare two QNames, and use QName directly // as a key to the SymbolHash. // And when the DV's are ready to return compiled values from // validate() method, we should just call QNameDV.validate() // in this method. private String findQName(String name, XSDocumentInfo schemaDoc) { SchemaNamespaceSupport currNSMap = schemaDoc.fNamespaceSupport; int colonPtr = name.indexOf(':'); String prefix = XMLSymbols.EMPTY_STRING; if (colonPtr > 0) prefix = name.substring(0, colonPtr); String uri = currNSMap.getURI(fSymbolTable.addSymbol(prefix)); String localpart = (colonPtr == 0)?name:name.substring(colonPtr+1); if (prefix == XMLSymbols.EMPTY_STRING && uri == null && schemaDoc.fIsChameleonSchema) uri = schemaDoc.fTargetNamespace; if (uri == null) return ","+localpart; return uri+","+localpart; } // findQName(String, XSDocumentInfo): String // This function looks among the children of curr for an element of type elementSought. // If it finds one, it evaluates whether its ref attribute contains a reference // to originalQName. If it does, it returns 1 + the value returned by // calls to itself on all other children. In all other cases it returns 0 plus // the sum of the values returned by calls to itself on curr's children. // It also resets the value of ref so that it will refer to the renamed type from the schema // being redefined. private int changeRedefineGroup(String originalQName, String elementSought, String newName, Element curr, XSDocumentInfo schemaDoc) { int result = 0; for (Element child = DOMUtil.getFirstChildElement(curr); child != null; child = DOMUtil.getNextSiblingElement(child)) { String name = DOMUtil.getLocalName(child); if (!name.equals(elementSought)) result += changeRedefineGroup(originalQName, elementSought, newName, child, schemaDoc); else { String ref = child.getAttribute( SchemaSymbols.ATT_REF ); if (ref.length() != 0) { String processedRef = findQName(ref, schemaDoc); if (originalQName.equals(processedRef)) { String prefix = XMLSymbols.EMPTY_STRING; int colonptr = ref.indexOf(":"); if (colonptr > 0) { prefix = ref.substring(0,colonptr); child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName); } else child.setAttribute(SchemaSymbols.ATT_REF, newName); result++; if (elementSought.equals(SchemaSymbols.ELT_GROUP)) { String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS ); String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS ); if (!((maxOccurs.length() == 0 || maxOccurs.equals("1")) && (minOccurs.length() == 0 || minOccurs.equals("1")))) { reportSchemaError("src-redefine.6.1.2", new Object [] {ref}, child); } } } } // if ref was null some other stage of processing will flag the error } } return result; } // changeRedefineGroup // this method returns the XSDocumentInfo object that contains the // component corresponding to decl. If components from this // document cannot be referred to from those of currSchema, this // method returns null; it's up to the caller to throw an error. // @param: currSchema: the XSDocumentInfo object containing the // decl ref'ing us. // @param: decl: the declaration being ref'd. // this method is superficial now. ---Jack private XSDocumentInfo findXSDocumentForDecl(XSDocumentInfo currSchema, Element decl, XSDocumentInfo decl_Doc) { if (DEBUG_NODE_POOL) { System.out.println("DOCUMENT NS:"+ currSchema.fTargetNamespace+" hashcode:"+ ((Object)currSchema.fSchemaElement).hashCode()); } Object temp = decl_Doc; if (temp == null) { // something went badly wrong; we don't know this doc? return null; } XSDocumentInfo declDocInfo = (XSDocumentInfo)temp; return declDocInfo; /********* Logic here is unnecessary after schema WG's recent decision to allow schema components from one document to refer to components of any other, so long as there's some include/import/redefine path amongst them. If they rver reverse this decision the code's right here though... - neilg // now look in fDependencyMap to see if this is reachable if(((Vector)fDependencyMap.get(currSchema)).contains(declDocInfo)) { return declDocInfo; } // obviously the requesting doc didn't include, redefine or // import the one containing decl... return null; **********/ } // findXSDocumentForDecl(XSDocumentInfo, Element): XSDocumentInfo // returns whether more than <annotation>s occur in children of elem private boolean nonAnnotationContent(Element elem) { for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) { if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true; } return false; } // nonAnnotationContent(Element): boolean private void setSchemasVisible(XSDocumentInfo startSchema) { if (DOMUtil.isHidden(startSchema.fSchemaElement, fHiddenNodes)) { // make it visible DOMUtil.setVisible(startSchema.fSchemaElement, fHiddenNodes); Vector dependingSchemas = (Vector)fDependencyMap.get(startSchema); for (int i = 0; i < dependingSchemas.size(); i++) { setSchemasVisible((XSDocumentInfo)dependingSchemas.elementAt(i)); } } // if it's visible already than so must be its children } // setSchemasVisible(XSDocumentInfo): void private SimpleLocator xl = new SimpleLocator(); /** * Extract location information from an Element node, and create a * new SimpleLocator object from such information. Returning null means * no information can be retrieved from the element. */ public SimpleLocator element2Locator(Element e) { if (!( e instanceof ElementImpl)) return null; SimpleLocator l = new SimpleLocator(); return element2Locator(e, l) ? l : null; } /** * Extract location information from an Element node, store such * information in the passed-in SimpleLocator object, then return * true. Returning false means can't extract or store such information. */ public boolean element2Locator(Element e, SimpleLocator l) { if (l == null) return false; if (e instanceof ElementImpl) { ElementImpl ele = (ElementImpl)e; // get system id from document object Document doc = ele.getOwnerDocument(); String sid = (String)fDoc2SystemId.get(DOMUtil.getRoot(doc)); // line/column numbers are stored in the element node int line = ele.getLineNumber(); int column = ele.getColumnNumber(); l.setValues(sid, sid, line, column, ele.getCharacterOffset()); return true; } return false; } void reportSchemaError(String key, Object[] args, Element ele) { if (element2Locator(ele, xl)) { fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } else { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } } void reportSchemaWarning(String key, Object[] args, Element ele) { if (element2Locator(ele, xl)) { fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_WARNING); } else { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_WARNING); } } /** * Grammar pool used for validating annotations. This will return all of the * grammars from the grammar bucket. It will also return an object for the * schema for schemas which will contain at least the relevant declarations * for annotations. */ private static class XSAnnotationGrammarPool implements XMLGrammarPool { private XSGrammarBucket fGrammarBucket; private Grammar [] fInitialGrammarSet; public Grammar[] retrieveInitialGrammarSet(String grammarType) { if (grammarType == XMLGrammarDescription.XML_SCHEMA) { if (fInitialGrammarSet == null) { if (fGrammarBucket == null) { fInitialGrammarSet = new Grammar [] {SchemaGrammar.Schema4Annotations.INSTANCE}; } else { SchemaGrammar [] schemaGrammars = fGrammarBucket.getGrammars(); /** * If the grammar bucket already contains the schema for schemas * then we already have the definitions for the parts relevant * to annotations. */ for (int i = 0; i < schemaGrammars.length; ++i) { if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(schemaGrammars[i].getTargetNamespace())) { fInitialGrammarSet = schemaGrammars; return fInitialGrammarSet; } } Grammar [] grammars = new Grammar[schemaGrammars.length + 1]; System.arraycopy(schemaGrammars, 0, grammars, 0, schemaGrammars.length); grammars[grammars.length - 1] = SchemaGrammar.Schema4Annotations.INSTANCE; fInitialGrammarSet = grammars; } } return fInitialGrammarSet; } return new Grammar[0]; } public void cacheGrammars(String grammarType, Grammar[] grammars) { } public Grammar retrieveGrammar(XMLGrammarDescription desc) { if (desc.getGrammarType() == XMLGrammarDescription.XML_SCHEMA) { final String tns = ((XMLSchemaDescription) desc).getTargetNamespace(); if (fGrammarBucket != null) { Grammar grammar = fGrammarBucket.getGrammar(tns); if (grammar != null) { return grammar; } } if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(tns)) { return SchemaGrammar.Schema4Annotations.INSTANCE; } } return null; } public void refreshGrammars(XSGrammarBucket gBucket) { fGrammarBucket = gBucket; fInitialGrammarSet = null; } public void lockPool() {} public void unlockPool() {} public void clear() {} } /** * used to identify a reference to a schema document * if the same document is referenced twice with the same key, then * we only need to parse it once. * * When 2 XSDKey's are compared, the following table can be used to * determine whether they are equal: * inc red imp pre ins * inc N/L ? N/L N/L N/L * red ? N/L ? ? ? * imp N/L ? N/P N/P N/P * pre N/L ? N/P N/P N/P * ins N/L ? N/P N/P N/P * * Where: N/L: duplicate when they have the same namespace and location. * ? : not clear from the spec. * REVISIT: to simplify the process, also considering * it's very rare, we treat them as not duplicate. * N/P: not possible. imp/pre/ins are referenced by namespace. * when the first time we encounter a schema document for a * namespace, we create a grammar and store it in the grammar * bucket. when we see another reference to the same namespace, * we first check whether a grammar with the same namespace is * already in the bucket, which is true in this case, so we * won't create another XSDKey. * * Conclusion from the table: two XSDKey's are duplicate only when all of * the following are true: * 1. They are both "redefine", or neither is "redefine"; * 2. They have the same namespace; * 3. They have the same non-null location. * * About 3: if neither has a non-null location, then it's the case where * 2 input streams are provided, but no system ID is provided. We can't tell * whether the 2 streams have the same content, so we treat them as not * duplicate. */ private static class XSDKey { String systemId; short referType; // for inclue/redefine, this is the enclosing namespace // for import/preparse/instance, this is the target namespace String referNS; XSDKey(String systemId, short referType, String referNS) { this.systemId = systemId; this.referType = referType; this.referNS = referNS; } public int hashCode() { // according to the description at the beginning of this class, // we use the hashcode of the namespace as the hashcoe of this key. return referNS == null ? 0 : referNS.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof XSDKey)) { return false; } XSDKey key = (XSDKey)obj; // condition 1: both are redefine /** if (referType == XSDDescription.CONTEXT_REDEFINE || key.referType == XSDDescription.CONTEXT_REDEFINE) { if (referType != key.referType) return false; }**/ // condition 2: same namespace if (referNS != key.referNS) return false; // condition 3: same non-null location if (systemId == null || !systemId.equals(key.systemId)) { return false; } return true; } } /** * @param state */ public void setGenerateSyntheticAnnotations(boolean state) { fSchemaParser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS, state); } /** * Set schema 1.1 support * * @param state */ public void setSchemaVersionInfo(short version, XSConstraints xsConstraints) { fSchemaVersion = version; fXSConstraints = xsConstraints; if (version < Constants.SCHEMA_VERSION_1_1) { fSupportedVersion = SUPPORTED_VERSION_1_0; } else { fSupportedVersion = SUPPORTED_VERSION_1_1; } fSchemaParser.setSupportedVersion(fSupportedVersion); } public short getSchemaVersion() { return fSchemaVersion; } } // XSDHandler
true
true
protected XSDocumentInfo constructTrees(Element schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { // note that attributes are freed at end of traverseSchemas() currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, schemaRoot); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, schemaRoot); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // for instance and import, the two NS's must be the same else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace); } else if(fHonourAllSchemaLocations && referType == XSDDescription.CONTEXT_IMPORT) { sg = findGrammar(desc); if(sg == null) { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone(), fSymbolTable); fGrammarBucket.putGrammar(sg); } } else { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone(), fSymbolTable); fGrammarBucket.putGrammar(sg); } // store the document and its location // REVISIT: don't expose the DOM tree sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaElement)); fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = schemaRoot; Element newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] importAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)importAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)importAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); // a document can't import another document with the same namespace if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError(schemaNamespace != null ? "src-import.1.1" : "src-import.1.2", new Object [] {schemaNamespace}, child); } // check contents and process optional annotations Element importChild = DOMUtil.getFirstChildElement(child); if(importChild != null ) { String importComponentType = DOMUtil.getLocalName(importChild); if (importComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // promoting annotations to parent component sg.addAnnotation( fElementTraverser.traverseAnnotationDecl(importChild, importAttrs, true, currSchemaInfo)); } else { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", importComponentType}, child); } if(DOMUtil.getNextSiblingElement(importChild) != null) { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", DOMUtil.getLocalName(DOMUtil.getNextSiblingElement(importChild))}, child); } } else { String text = DOMUtil.getSyntheticAnnotation(child); if (text != null) { sg.addAnnotation(fElementTraverser.traverseSyntheticAnnotation(child, text, importAttrs, true, currSchemaInfo)); } } fAttributeChecker.returnAttrArray(importAttrs, currSchemaInfo); // if this namespace has not been imported by this document, // then import if multiple imports support is enabled. if(currSchemaInfo.isAllowedNS(schemaNamespace)) { if(!fHonourAllSchemaLocations) continue; } else { currSchemaInfo.addAllowedNS(schemaNamespace); } // also record the fact that one namespace imports another one // convert null to "" String tns = null2EmptyString(currSchemaInfo.fTargetNamespace); // get all namespaces imported by this one Vector ins = (Vector)fImportMap.get(tns); // if no namespace was imported, create new Vector if (ins == null) { // record that this one imports other(s) fAllTNSs.addElement(tns); ins = new Vector(); fImportMap.put(tns, ins); ins.addElement(schemaNamespace); } else if (!ins.contains(schemaNamespace)){ ins.addElement(schemaNamespace); } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId(doc2SystemId(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); // if a grammar with the same namespace and location exists (or being // built), ignore this one (don't traverse it). if ((!fHonourAllSchemaLocations && findGrammar(fSchemaGrammarDescription) != null) || isExistingGrammar(fSchemaGrammarDescription)) continue; // If "findGrammar" returns a grammar, then this is not the // the first time we see a location for a given namespace. // Don't consult the location pair hashtable in this case, // otherwise the location will be ignored because it'll get // resolved to the same location as the first hint. newSchemaRoot = resolveSchema(fSchemaGrammarDescription, false, child, findGrammar(fSchemaGrammarDescription) == null); }
protected XSDocumentInfo constructTrees(Element schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { // note that attributes are freed at end of traverseSchemas() currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, schemaRoot); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, schemaRoot); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // for instance and import, the two NS's must be the same else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, schemaRoot); return null; } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace); } else if(fHonourAllSchemaLocations && referType == XSDDescription.CONTEXT_IMPORT) { sg = findGrammar(desc); if(sg == null) { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone(), fSymbolTable); fGrammarBucket.putGrammar(sg); } } else { sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone(), fSymbolTable); fGrammarBucket.putGrammar(sg); } // store the document and its location // REVISIT: don't expose the DOM tree sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaElement)); fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = schemaRoot; Element newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] importAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)importAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)importAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); // a document can't import another document with the same namespace if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError(schemaNamespace != null ? "src-import.1.1" : "src-import.1.2", new Object [] {schemaNamespace}, child); } // check contents and process optional annotations Element importChild = DOMUtil.getFirstChildElement(child); if(importChild != null ) { String importComponentType = DOMUtil.getLocalName(importChild); if (importComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // promoting annotations to parent component sg.addAnnotation( fElementTraverser.traverseAnnotationDecl(importChild, importAttrs, true, currSchemaInfo)); } else { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", importComponentType}, child); } if(DOMUtil.getNextSiblingElement(importChild) != null) { reportSchemaError("s4s-elt-must-match.1", new Object [] {localName, "annotation?", DOMUtil.getLocalName(DOMUtil.getNextSiblingElement(importChild))}, child); } } else { String text = DOMUtil.getSyntheticAnnotation(child); if (text != null) { sg.addAnnotation(fElementTraverser.traverseSyntheticAnnotation(child, text, importAttrs, true, currSchemaInfo)); } } fAttributeChecker.returnAttrArray(importAttrs, currSchemaInfo); // if this namespace has not been imported by this document, // then import if multiple imports support is enabled. if(currSchemaInfo.isAllowedNS(schemaNamespace)) { if(!fHonourAllSchemaLocations) continue; } else { currSchemaInfo.addAllowedNS(schemaNamespace); } // also record the fact that one namespace imports another one // convert null to "" String tns = null2EmptyString(currSchemaInfo.fTargetNamespace); // get all namespaces imported by this one Vector ins = (Vector)fImportMap.get(tns); // if no namespace was imported, create new Vector if (ins == null) { // record that this one imports other(s) fAllTNSs.addElement(tns); ins = new Vector(); fImportMap.put(tns, ins); ins.addElement(schemaNamespace); } else if (!ins.contains(schemaNamespace)){ ins.addElement(schemaNamespace); } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId(doc2SystemId(schemaRoot)); fSchemaGrammarDescription.setLiteralSystemId(schemaHint); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); // if a grammar with the same namespace and location exists (or being // built), ignore this one (don't traverse it). if ((!fHonourAllSchemaLocations && findGrammar(fSchemaGrammarDescription) != null) || isExistingGrammar(fSchemaGrammarDescription)) continue; // If "findGrammar" returns a grammar, then this is not the // the first time we see a location for a given namespace. // Don't consult the location pair hashtable in this case, // otherwise the location will be ignored because it'll get // resolved to the same location as the first hint. newSchemaRoot = resolveSchema(fSchemaGrammarDescription, false, child, findGrammar(fSchemaGrammarDescription) == null); }
diff --git a/src/replicatorg/app/ui/modeling/MoveTool.java b/src/replicatorg/app/ui/modeling/MoveTool.java index 75a80046..c896a5a0 100644 --- a/src/replicatorg/app/ui/modeling/MoveTool.java +++ b/src/replicatorg/app/ui/modeling/MoveTool.java @@ -1,168 +1,168 @@ package replicatorg.app.ui.modeling; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import javax.media.j3d.Transform3D; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFormattedTextField; import javax.swing.JPanel; import javax.vecmath.Vector3d; import net.miginfocom.swing.MigLayout; import replicatorg.app.Base; import replicatorg.app.ui.modeling.PreviewPanel.DragMode; public class MoveTool extends Tool { public MoveTool(ToolPanel parent) { super(parent); } Transform3D vt; public Icon getButtonIcon() { return null; } public String getButtonName() { return "Move"; } JCheckBox lockZ; JFormattedTextField transX, transY, transZ; public JPanel getControls() { JPanel p = new JPanel(new MigLayout("fillx,filly,gap 0")); JButton centerButton = createToolButton("Center","images/center-object.png"); centerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { parent.getModel().center(); } }); p.add(centerButton,"growx,wrap,spanx"); JButton lowerButton = createToolButton("Put on platform","images/center-object.png"); lowerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { parent.getModel().putOnPlatform(); } }); p.add(lowerButton,"growx,wrap,spanx"); transX = new JFormattedTextField(Base.getLocalFormat()); Dimension d = transX.getPreferredSize(); d.width = 800; transX.setPreferredSize(d); transY = new JFormattedTextField(Base.getLocalFormat()); transZ = new JFormattedTextField(Base.getLocalFormat()); transX.setValue(10); transY.setValue(10); transZ.setValue(10); JButton transXplus = new JButton("X+"); JButton transYplus = new JButton("Y+"); JButton transZplus = new JButton("Z+"); JButton transXminus = new JButton("X-"); JButton transYminus = new JButton("Y-"); JButton transZminus = new JButton("Z-"); p.add(transXminus); p.add(transX,"growx"); p.add(transXplus,"wrap"); p.add(transYminus); p.add(transY,"growx"); p.add(transYplus,"wrap"); p.add(transZminus); p.add(transZ,"growx"); p.add(transZplus,"wrap"); transXplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transXval = ((Number)transX.getValue()).doubleValue(); parent.getModel().translateObject(transXval, 0, 0); } }); transXminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transXval = ((Number)transX.getValue()).doubleValue(); parent.getModel().translateObject(-transXval, 0, 0); } }); transYplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transYval = ((Number)transY.getValue()).doubleValue(); - parent.getModel().translateObject(transYval, 0, 0); + parent.getModel().translateObject(0, transYval, 0); } }); transYminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transYval = ((Number)transY.getValue()).doubleValue(); - parent.getModel().translateObject(-transYval, 0, 0); + parent.getModel().translateObject(0, -transYval, 0); } }); transZplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transZval = ((Number)transZ.getValue()).doubleValue(); - parent.getModel().translateObject(transZval, 0, 0); + parent.getModel().translateObject(0, 0, transZval); } }); transZminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transZval = ((Number)transZ.getValue()).doubleValue(); - parent.getModel().translateObject(-transZval, 0, 0); + parent.getModel().translateObject(0, 0, -transZval); } }); lockZ = new JCheckBox("Lock height"); p.add(lockZ,"growx,wrap,spanx"); return p; } public String getInstructions() { return Base.isMacOS()? "<html><body>Drag to move object<br>Shift-drag to rotate view<br>Mouse wheel to zoom</body></html>": "<html><body>Left drag to move object<br>Right drag to rotate view<br>Mouse wheel to zoom</body></html>"; } public String getTitle() { return "Move Object"; } public void mouseDragged(MouseEvent e) { if (startPoint == null) return; Point p = e.getPoint(); DragMode mode = DragMode.NONE; if (Base.isMacOS()) { if (button == MouseEvent.BUTTON1 && !e.isShiftDown()) { mode = DragMode.TRANSLATE_OBJECT; } } else { if (button == MouseEvent.BUTTON1) { mode = DragMode.TRANSLATE_OBJECT; } } double xd = (double)(p.x - startPoint.x); double yd = -(double)(p.y - startPoint.y); switch (mode) { case NONE: super.mouseDragged(e); break; case TRANSLATE_OBJECT: doTranslate(xd,yd); break; } startPoint = p; } public void mousePressed(MouseEvent e) { // Set up view transform vt = parent.preview.getViewTransform(); super.mousePressed(e); } void doTranslate(double deltaX, double deltaY) { Vector3d v = new Vector3d(deltaX,deltaY,0d); vt.transform(v); if (lockZ.isSelected()) { v.z = 0d; } parent.getModel().translateObject(v.x,v.y,v.z); } }
false
true
public JPanel getControls() { JPanel p = new JPanel(new MigLayout("fillx,filly,gap 0")); JButton centerButton = createToolButton("Center","images/center-object.png"); centerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { parent.getModel().center(); } }); p.add(centerButton,"growx,wrap,spanx"); JButton lowerButton = createToolButton("Put on platform","images/center-object.png"); lowerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { parent.getModel().putOnPlatform(); } }); p.add(lowerButton,"growx,wrap,spanx"); transX = new JFormattedTextField(Base.getLocalFormat()); Dimension d = transX.getPreferredSize(); d.width = 800; transX.setPreferredSize(d); transY = new JFormattedTextField(Base.getLocalFormat()); transZ = new JFormattedTextField(Base.getLocalFormat()); transX.setValue(10); transY.setValue(10); transZ.setValue(10); JButton transXplus = new JButton("X+"); JButton transYplus = new JButton("Y+"); JButton transZplus = new JButton("Z+"); JButton transXminus = new JButton("X-"); JButton transYminus = new JButton("Y-"); JButton transZminus = new JButton("Z-"); p.add(transXminus); p.add(transX,"growx"); p.add(transXplus,"wrap"); p.add(transYminus); p.add(transY,"growx"); p.add(transYplus,"wrap"); p.add(transZminus); p.add(transZ,"growx"); p.add(transZplus,"wrap"); transXplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transXval = ((Number)transX.getValue()).doubleValue(); parent.getModel().translateObject(transXval, 0, 0); } }); transXminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transXval = ((Number)transX.getValue()).doubleValue(); parent.getModel().translateObject(-transXval, 0, 0); } }); transYplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transYval = ((Number)transY.getValue()).doubleValue(); parent.getModel().translateObject(transYval, 0, 0); } }); transYminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transYval = ((Number)transY.getValue()).doubleValue(); parent.getModel().translateObject(-transYval, 0, 0); } }); transZplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transZval = ((Number)transZ.getValue()).doubleValue(); parent.getModel().translateObject(transZval, 0, 0); } }); transZminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transZval = ((Number)transZ.getValue()).doubleValue(); parent.getModel().translateObject(-transZval, 0, 0); } }); lockZ = new JCheckBox("Lock height"); p.add(lockZ,"growx,wrap,spanx"); return p; }
public JPanel getControls() { JPanel p = new JPanel(new MigLayout("fillx,filly,gap 0")); JButton centerButton = createToolButton("Center","images/center-object.png"); centerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { parent.getModel().center(); } }); p.add(centerButton,"growx,wrap,spanx"); JButton lowerButton = createToolButton("Put on platform","images/center-object.png"); lowerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { parent.getModel().putOnPlatform(); } }); p.add(lowerButton,"growx,wrap,spanx"); transX = new JFormattedTextField(Base.getLocalFormat()); Dimension d = transX.getPreferredSize(); d.width = 800; transX.setPreferredSize(d); transY = new JFormattedTextField(Base.getLocalFormat()); transZ = new JFormattedTextField(Base.getLocalFormat()); transX.setValue(10); transY.setValue(10); transZ.setValue(10); JButton transXplus = new JButton("X+"); JButton transYplus = new JButton("Y+"); JButton transZplus = new JButton("Z+"); JButton transXminus = new JButton("X-"); JButton transYminus = new JButton("Y-"); JButton transZminus = new JButton("Z-"); p.add(transXminus); p.add(transX,"growx"); p.add(transXplus,"wrap"); p.add(transYminus); p.add(transY,"growx"); p.add(transYplus,"wrap"); p.add(transZminus); p.add(transZ,"growx"); p.add(transZplus,"wrap"); transXplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transXval = ((Number)transX.getValue()).doubleValue(); parent.getModel().translateObject(transXval, 0, 0); } }); transXminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transXval = ((Number)transX.getValue()).doubleValue(); parent.getModel().translateObject(-transXval, 0, 0); } }); transYplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transYval = ((Number)transY.getValue()).doubleValue(); parent.getModel().translateObject(0, transYval, 0); } }); transYminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transYval = ((Number)transY.getValue()).doubleValue(); parent.getModel().translateObject(0, -transYval, 0); } }); transZplus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transZval = ((Number)transZ.getValue()).doubleValue(); parent.getModel().translateObject(0, 0, transZval); } }); transZminus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double transZval = ((Number)transZ.getValue()).doubleValue(); parent.getModel().translateObject(0, 0, -transZval); } }); lockZ = new JCheckBox("Lock height"); p.add(lockZ,"growx,wrap,spanx"); return p; }
diff --git a/src/com/bukkit/N4th4/NuxGrief/NGPlayerListener.java b/src/com/bukkit/N4th4/NuxGrief/NGPlayerListener.java index bc2ded6..c1848bb 100644 --- a/src/com/bukkit/N4th4/NuxGrief/NGPlayerListener.java +++ b/src/com/bukkit/N4th4/NuxGrief/NGPlayerListener.java @@ -1,33 +1,36 @@ package com.bukkit.N4th4.NuxGrief; import org.bukkit.Material; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerPickupItemEvent; public class NGPlayerListener extends PlayerListener { public final NuxGrief plugin; public NGPlayerListener(NuxGrief instance) { plugin = instance; } public void onPlayerPickupItem(PlayerPickupItemEvent event) { if(!plugin.permissions.has(event.getPlayer(), "nuxgrief.pickup")) { event.setCancelled(true); } } public void onPlayerInteract(PlayerInteractEvent event) { + if (event.getClickedBlock() == null) { + return; + } if (event.getClickedBlock().getType() == Material.CHEST && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.chests")) { event.setCancelled(true); } else if (event.getClickedBlock().getType() == Material.FURNACE && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.furnaces")) { event.setCancelled(true); } else if (event.getClickedBlock().getType() == Material.STORAGE_MINECART && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.storage_minecarts")) { event.setCancelled(true); } } }
true
true
public void onPlayerInteract(PlayerInteractEvent event) { if (event.getClickedBlock().getType() == Material.CHEST && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.chests")) { event.setCancelled(true); } else if (event.getClickedBlock().getType() == Material.FURNACE && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.furnaces")) { event.setCancelled(true); } else if (event.getClickedBlock().getType() == Material.STORAGE_MINECART && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.storage_minecarts")) { event.setCancelled(true); } }
public void onPlayerInteract(PlayerInteractEvent event) { if (event.getClickedBlock() == null) { return; } if (event.getClickedBlock().getType() == Material.CHEST && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.chests")) { event.setCancelled(true); } else if (event.getClickedBlock().getType() == Material.FURNACE && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.furnaces")) { event.setCancelled(true); } else if (event.getClickedBlock().getType() == Material.STORAGE_MINECART && !plugin.permissions.has(event.getPlayer(), "nuxgrief.interact.storage_minecarts")) { event.setCancelled(true); } }
diff --git a/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/util/ModelUtils.java b/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/util/ModelUtils.java index d0c157839..d014a4a23 100644 --- a/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/util/ModelUtils.java +++ b/plugins/org.eclipse.emf.compare/src/org/eclipse/emf/compare/util/ModelUtils.java @@ -1,272 +1,273 @@ /******************************************************************************* * Copyright (c) 2006, 2007 Obeo. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.emf.compare.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.compare.Messages; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl; /** * Utility class for model loading/saving and serialization. * * @author Cedric Brun <a href="mailto:[email protected]">[email protected]</a> */ public final class ModelUtils { /** Will determine if the URIs must be encoded depending on the current system. */ private static final boolean ENCODE_PLATFORM_RESOURCE_URIS = System .getProperty("org.eclipse.emf.common.util.URI.encodePlatformResourceURIs") != null && //$NON-NLS-1$ !System .getProperty("org.eclipse.emf.common.util.URI.encodePlatformResourceURIs").equalsIgnoreCase("false"); //$NON-NLS-1$ //$NON-NLS-2$ /** Constant for the file encoding system property. */ private static final String ENCODING_PROPERTY = "file.encoding"; //$NON-NLS-1$ /** * Utility classes don't need to (and shouldn't) be instantiated. */ private ModelUtils() { // prevents instantiation } /** * This will create a {@link Resource} given the model extension it is intended for. * * @param modelURI * {@link org.eclipse.emf.common.util.URI URI} where the model is stored. * @return The {@link Resource} given the model extension it is intended for. */ public static Resource createResource(URI modelURI) { return createResource(modelURI, new ResourceSetImpl()); } /** * This will create a {@link Resource} given the model extension it is intended for and a ResourceSet. * * @param modelURI * {@link org.eclipse.emf.common.util.URI URI} where the model is stored. * @param resourceSet * The {@link ResourceSet} to load the model in. * @return The {@link Resource} given the model extension it is intended for. */ public static Resource createResource(URI modelURI, ResourceSet resourceSet) { String fileExtension = modelURI.fileExtension(); - if (fileExtension.indexOf('.') > 0) - fileExtension = fileExtension.substring(fileExtension.indexOf('.') + 1); + if (fileExtension == null || fileExtension.length() == 0) { + fileExtension = Resource.Factory.Registry.DEFAULT_EXTENSION; + } final Resource.Factory.Registry registry = Resource.Factory.Registry.INSTANCE; final Object resourceFactory = registry.getExtensionToFactoryMap().get(fileExtension); if (resourceFactory != null) { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, resourceFactory); } else { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, new XMIResourceFactoryImpl()); } return resourceSet.createResource(modelURI); } /** * Loads the models contained by the given directory. * * @param directory * The directory from which to load the models. * @return The models contained by the given directory. * @throws IOException * Thrown if an I/O operation has failed or been interrupted. */ public static List<EObject> getModelsFrom(File directory) throws IOException { final List<EObject> models = new ArrayList<EObject>(); if (directory.exists() && directory.isDirectory() && directory.listFiles() != null) { final File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { final File aFile = files[i]; final ResourceSet resourceSet = new ResourceSetImpl(); if (!aFile.isDirectory() && !aFile.getName().startsWith(".")) { //$NON-NLS-1$ models.add(load(aFile, resourceSet)); } } } return models; } /** * Loads a model from a {@link java.io.File File} in a given {@link ResourceSet}. * * @param file * {@link java.io.File File} containing the model to be loaded. * @param resourceSet * The {@link ResourceSet} to load the model in. * @return The model loaded from the file. * @throws IOException * If the given file does not exist. */ public static EObject load(File file, ResourceSet resourceSet) throws IOException { return load(URI.createFileURI(file.getPath()), resourceSet); } /** * Loads a model from an {@link org.eclipse.core.resources.IFile IFile} in a given {@link ResourceSet}. * * @param file * {@link org.eclipse.core.resources.IFile IFile} containing the model to be loaded. * @param resourceSet * The {@link ResourceSet} to load the model in. * @return The model loaded from the file. * @throws IOException * If the given file does not exist. */ @SuppressWarnings("unchecked") public static EObject load(IFile file, ResourceSet resourceSet) throws IOException { EObject result = null; final Resource modelResource = createResource(URI.createPlatformResourceURI(file.getFullPath() .toOSString(), ENCODE_PLATFORM_RESOURCE_URIS), resourceSet); final Map<String, String> options = new EMFCompareMap<String, String>(); options.put(XMLResource.OPTION_ENCODING, System.getProperty(ENCODING_PROPERTY)); modelResource.load(options); if (modelResource.getContents().size() > 0) result = modelResource.getContents().get(0); return result; } /** * Load a model from an {@link java.io.InputStream InputStream} in a given {@link ResourceSet}. * * @param stream * The inputstream to load from * @param fileName * The original filename * @param resourceSet * The {@link ResourceSet} to load the model in. * @return The loaded model * @throws IOException * If the given file does not exist. */ @SuppressWarnings("unchecked") public static EObject load(InputStream stream, String fileName, ResourceSet resourceSet) throws IOException { if (stream == null) throw new NullPointerException(Messages.getString("ModelUtils.NullInputStream")); //$NON-NLS-1$ EObject result = null; final Resource modelResource = createResource(URI.createURI(fileName), resourceSet); final Map<String, String> options = new EMFCompareMap<String, String>(); options.put(XMLResource.OPTION_ENCODING, System.getProperty(ENCODING_PROPERTY)); modelResource.load(stream, options); if (modelResource.getContents().size() > 0) result = modelResource.getContents().get(0); return result; } /** * Loads a model from an {@link IPath} in a given {@link ResourceSet}. * * @param path * {@link IPath} where the model lies. * @param resourceSet * The {@link ResourceSet} to load the model in. * @return The model loaded from the path. * @throws IOException * If the given file does not exist. */ public static EObject load(IPath path, ResourceSet resourceSet) throws IOException { return load(ResourcesPlugin.getWorkspace().getRoot().getFile(path), resourceSet); } /** * Loads a model from an {@link org.eclipse.emf.common.util.URI URI} in a given {@link ResourceSet}. * * @param modelURI * {@link org.eclipse.emf.common.util.URI URI} where the model is stored. * @param resourceSet * The {@link ResourceSet} to load the model in. * @return The model loaded from the URI. * @throws IOException * If the given file does not exist. */ @SuppressWarnings("unchecked") public static EObject load(URI modelURI, ResourceSet resourceSet) throws IOException { EObject result = null; final Resource modelResource = createResource(modelURI, resourceSet); final Map<String, String> options = new EMFCompareMap<String, String>(); options.put(XMLResource.OPTION_ENCODING, System.getProperty(ENCODING_PROPERTY)); modelResource.load(options); if (modelResource.getContents().size() > 0) result = modelResource.getContents().get(0); return result; } /** * Saves a model as a file to the given path. * * @param root * Root of the objects to be serialized in a file. * @param path * File where the objects have to be saved. * @throws IOException * Thrown if an I/O operation has failed or been interrupted during the saving process. */ @SuppressWarnings("unchecked") public static void save(EObject root, String path) throws IOException { if (root == null) throw new NullPointerException(Messages.getString("ModelUtils.NullSaveRoot")); //$NON-NLS-1$ final Resource newModelResource = createResource(URI.createFileURI(path)); newModelResource.getContents().add(root); final Map<String, String> options = new EMFCompareMap<String, String>(); options.put(XMLResource.OPTION_ENCODING, System.getProperty(ENCODING_PROPERTY)); newModelResource.save(options); } /** * Serializes the given EObjet as a String. * * @param root * Root of the objects to be serialized. * @return The given EObjet serialized as a String. * @throws IOException * Thrown if an I/O operation has failed or been interrupted during the saving process. */ @SuppressWarnings("unchecked") public static String serialize(EObject root) throws IOException { if (root == null) throw new NullPointerException(Messages.getString("ModelUtils.NullSaveRoot")); //$NON-NLS-1$ final XMIResourceImpl newResource = new XMIResourceImpl(); final StringWriter writer = new StringWriter(); newResource.getContents().add(root); newResource.save(writer, Collections.EMPTY_MAP); return writer.toString(); } }
true
true
public static Resource createResource(URI modelURI, ResourceSet resourceSet) { String fileExtension = modelURI.fileExtension(); if (fileExtension.indexOf('.') > 0) fileExtension = fileExtension.substring(fileExtension.indexOf('.') + 1); final Resource.Factory.Registry registry = Resource.Factory.Registry.INSTANCE; final Object resourceFactory = registry.getExtensionToFactoryMap().get(fileExtension); if (resourceFactory != null) { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, resourceFactory); } else { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, new XMIResourceFactoryImpl()); } return resourceSet.createResource(modelURI); }
public static Resource createResource(URI modelURI, ResourceSet resourceSet) { String fileExtension = modelURI.fileExtension(); if (fileExtension == null || fileExtension.length() == 0) { fileExtension = Resource.Factory.Registry.DEFAULT_EXTENSION; } final Resource.Factory.Registry registry = Resource.Factory.Registry.INSTANCE; final Object resourceFactory = registry.getExtensionToFactoryMap().get(fileExtension); if (resourceFactory != null) { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, resourceFactory); } else { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, new XMIResourceFactoryImpl()); } return resourceSet.createResource(modelURI); }
diff --git a/client/cpw/mods/fml/client/GuiModList.java b/client/cpw/mods/fml/client/GuiModList.java index 1e9d548b..2085f15e 100644 --- a/client/cpw/mods/fml/client/GuiModList.java +++ b/client/cpw/mods/fml/client/GuiModList.java @@ -1,178 +1,180 @@ /* * The FML Forge Mod Loader suite. * Copyright (C) 2012 cpw * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package cpw.mods.fml.client; import java.awt.Dimension; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.lwjgl.opengl.GL11; import cpw.mods.fml.common.FMLModContainer; import cpw.mods.fml.common.FMLDummyContainer; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; import net.minecraft.client.Minecraft; import net.minecraft.src.FontRenderer; import net.minecraft.src.GuiButton; import net.minecraft.src.GuiScreen; import net.minecraft.src.GuiSmallButton; import net.minecraft.src.StringTranslate; import net.minecraft.src.Tessellator; /** * @author cpw * */ public class GuiModList extends GuiScreen { private GuiScreen mainMenu; private GuiSlotModList modList; private int selected = -1; private ModContainer selectedMod; private int listWidth; private ArrayList<ModContainer> mods; /** * @param guiMainMenu */ public GuiModList(GuiScreen mainMenu) { this.mainMenu=mainMenu; this.mods=new ArrayList<ModContainer>(); FMLClientHandler.instance().addSpecialModEntries(mods); for (ModContainer mod : Loader.instance().getModList()) { if (mod.getMetadata()!=null && mod.getMetadata().parentMod != null) { continue; } mods.add(mod); } } @Override public void func_73866_w_() { for (ModContainer mod : mods) { listWidth=Math.max(listWidth,getFontRenderer().func_78256_a(mod.getName()) + 10); listWidth=Math.max(listWidth,getFontRenderer().func_78256_a(mod.getVersion()) + 10); } listWidth=Math.min(listWidth, 150); StringTranslate translations = StringTranslate.func_74808_a(); this.field_73887_h.add(new GuiSmallButton(6, this.field_73880_f / 2 - 75, this.field_73881_g - 38, translations.func_74805_b("gui.done"))); this.modList=new GuiSlotModList(this, mods, listWidth); this.modList.registerScrollButtons(this.field_73887_h, 7, 8); } @Override protected void func_73875_a(GuiButton button) { if (button.field_73742_g) { switch (button.field_73741_f) { case 6: this.field_73882_e.func_71373_a(this.mainMenu); return; } } super.func_73875_a(button); } public int drawLine(String line, int offset, int shifty) { this.field_73886_k.func_78276_b(line, offset, shifty, 0xd7edea); return shifty + 10; } @Override public void func_73863_a(int p_571_1_, int p_571_2_, float p_571_3_) { this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_); this.func_73732_a(this.field_73886_k, "Mod List", this.field_73880_f / 2, 16, 0xFFFFFF); int offset = this.listWidth + 20; if (selectedMod != null) { + GL11.glEnable(GL11.GL_BLEND); if (!selectedMod.getMetadata().autogenerated) { int shifty = 35; if (!selectedMod.getMetadata().logoFile.isEmpty()) { int texture = this.field_73882_e.field_71446_o.func_78341_b(selectedMod.getMetadata().logoFile); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.field_73882_e.field_71446_o.func_78342_b(texture); Dimension dim = TextureFXManager.instance().getTextureDimensions(texture); int top = 32; Tessellator tess = Tessellator.field_78398_a; tess.func_78382_b(); tess.func_78374_a(offset, top + dim.height, field_73735_i, 0, 1); tess.func_78374_a(offset + dim.width, top + dim.height, field_73735_i, 1, 1); tess.func_78374_a(offset + dim.width, top, field_73735_i, 1, 0); tess.func_78374_a(offset, top, field_73735_i, 0, 0); tess.func_78381_a(); shifty += 65; } this.field_73886_k.func_78261_a(selectedMod.getMetadata().name, offset, shifty, 0xFFFFFF); shifty += 12; shifty = drawLine(String.format("Version: %s (%s)", selectedMod.getMetadata().version, selectedMod.getVersion()), offset, shifty); shifty = drawLine(String.format("Mod State: %s", Loader.instance().getModState(selectedMod)), offset, shifty); if (!selectedMod.getMetadata().credits.isEmpty()) { shifty = drawLine(String.format("Credits: %s", selectedMod.getMetadata().credits), offset, shifty); } shifty = drawLine(String.format("Authors: %s", selectedMod.getMetadata().getAuthorList()), offset, shifty); shifty = drawLine(String.format("URL: %s", selectedMod.getMetadata().url), offset, shifty); shifty = drawLine(selectedMod.getMetadata().childMods.isEmpty() ? "No child mods for this mod" : String.format("Child mods: %s", selectedMod.getMetadata().getChildModList()), offset, shifty); this.getFontRenderer().func_78279_b(selectedMod.getMetadata().description, offset, shifty + 10, this.field_73880_f - offset - 20, 0xDDDDDD); } else { offset = ( this.listWidth + this.field_73880_f ) / 2; this.func_73732_a(this.field_73886_k, selectedMod.getName(), offset, 35, 0xFFFFFF); this.func_73732_a(this.field_73886_k, String.format("Version: %s",selectedMod.getVersion()), offset, 45, 0xFFFFFF); this.func_73732_a(this.field_73886_k, String.format("Mod State: %s",Loader.instance().getModState(selectedMod)), offset, 55, 0xFFFFFF); this.func_73732_a(this.field_73886_k, "No mod information found", offset, 65, 0xDDDDDD); this.func_73732_a(this.field_73886_k, "Ask your mod author to provide a mod mcmod.info file", offset, 75, 0xDDDDDD); } + GL11.glDisable(GL11.GL_BLEND); } super.func_73863_a(p_571_1_, p_571_2_, p_571_3_); } Minecraft getMinecraftInstance() { return field_73882_e; } FontRenderer getFontRenderer() { return field_73886_k; } /** * @param var1 */ public void selectModIndex(int var1) { this.selected=var1; if (var1>=0 && var1<=mods.size()) { this.selectedMod=mods.get(selected); } else { this.selectedMod=null; } } /** * @param var1 * @return */ public boolean modIndexSelected(int var1) { return var1==selected; } }
false
true
public void func_73863_a(int p_571_1_, int p_571_2_, float p_571_3_) { this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_); this.func_73732_a(this.field_73886_k, "Mod List", this.field_73880_f / 2, 16, 0xFFFFFF); int offset = this.listWidth + 20; if (selectedMod != null) { if (!selectedMod.getMetadata().autogenerated) { int shifty = 35; if (!selectedMod.getMetadata().logoFile.isEmpty()) { int texture = this.field_73882_e.field_71446_o.func_78341_b(selectedMod.getMetadata().logoFile); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.field_73882_e.field_71446_o.func_78342_b(texture); Dimension dim = TextureFXManager.instance().getTextureDimensions(texture); int top = 32; Tessellator tess = Tessellator.field_78398_a; tess.func_78382_b(); tess.func_78374_a(offset, top + dim.height, field_73735_i, 0, 1); tess.func_78374_a(offset + dim.width, top + dim.height, field_73735_i, 1, 1); tess.func_78374_a(offset + dim.width, top, field_73735_i, 1, 0); tess.func_78374_a(offset, top, field_73735_i, 0, 0); tess.func_78381_a(); shifty += 65; } this.field_73886_k.func_78261_a(selectedMod.getMetadata().name, offset, shifty, 0xFFFFFF); shifty += 12; shifty = drawLine(String.format("Version: %s (%s)", selectedMod.getMetadata().version, selectedMod.getVersion()), offset, shifty); shifty = drawLine(String.format("Mod State: %s", Loader.instance().getModState(selectedMod)), offset, shifty); if (!selectedMod.getMetadata().credits.isEmpty()) { shifty = drawLine(String.format("Credits: %s", selectedMod.getMetadata().credits), offset, shifty); } shifty = drawLine(String.format("Authors: %s", selectedMod.getMetadata().getAuthorList()), offset, shifty); shifty = drawLine(String.format("URL: %s", selectedMod.getMetadata().url), offset, shifty); shifty = drawLine(selectedMod.getMetadata().childMods.isEmpty() ? "No child mods for this mod" : String.format("Child mods: %s", selectedMod.getMetadata().getChildModList()), offset, shifty); this.getFontRenderer().func_78279_b(selectedMod.getMetadata().description, offset, shifty + 10, this.field_73880_f - offset - 20, 0xDDDDDD); } else { offset = ( this.listWidth + this.field_73880_f ) / 2; this.func_73732_a(this.field_73886_k, selectedMod.getName(), offset, 35, 0xFFFFFF); this.func_73732_a(this.field_73886_k, String.format("Version: %s",selectedMod.getVersion()), offset, 45, 0xFFFFFF); this.func_73732_a(this.field_73886_k, String.format("Mod State: %s",Loader.instance().getModState(selectedMod)), offset, 55, 0xFFFFFF); this.func_73732_a(this.field_73886_k, "No mod information found", offset, 65, 0xDDDDDD); this.func_73732_a(this.field_73886_k, "Ask your mod author to provide a mod mcmod.info file", offset, 75, 0xDDDDDD); } } super.func_73863_a(p_571_1_, p_571_2_, p_571_3_); }
public void func_73863_a(int p_571_1_, int p_571_2_, float p_571_3_) { this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_); this.func_73732_a(this.field_73886_k, "Mod List", this.field_73880_f / 2, 16, 0xFFFFFF); int offset = this.listWidth + 20; if (selectedMod != null) { GL11.glEnable(GL11.GL_BLEND); if (!selectedMod.getMetadata().autogenerated) { int shifty = 35; if (!selectedMod.getMetadata().logoFile.isEmpty()) { int texture = this.field_73882_e.field_71446_o.func_78341_b(selectedMod.getMetadata().logoFile); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.field_73882_e.field_71446_o.func_78342_b(texture); Dimension dim = TextureFXManager.instance().getTextureDimensions(texture); int top = 32; Tessellator tess = Tessellator.field_78398_a; tess.func_78382_b(); tess.func_78374_a(offset, top + dim.height, field_73735_i, 0, 1); tess.func_78374_a(offset + dim.width, top + dim.height, field_73735_i, 1, 1); tess.func_78374_a(offset + dim.width, top, field_73735_i, 1, 0); tess.func_78374_a(offset, top, field_73735_i, 0, 0); tess.func_78381_a(); shifty += 65; } this.field_73886_k.func_78261_a(selectedMod.getMetadata().name, offset, shifty, 0xFFFFFF); shifty += 12; shifty = drawLine(String.format("Version: %s (%s)", selectedMod.getMetadata().version, selectedMod.getVersion()), offset, shifty); shifty = drawLine(String.format("Mod State: %s", Loader.instance().getModState(selectedMod)), offset, shifty); if (!selectedMod.getMetadata().credits.isEmpty()) { shifty = drawLine(String.format("Credits: %s", selectedMod.getMetadata().credits), offset, shifty); } shifty = drawLine(String.format("Authors: %s", selectedMod.getMetadata().getAuthorList()), offset, shifty); shifty = drawLine(String.format("URL: %s", selectedMod.getMetadata().url), offset, shifty); shifty = drawLine(selectedMod.getMetadata().childMods.isEmpty() ? "No child mods for this mod" : String.format("Child mods: %s", selectedMod.getMetadata().getChildModList()), offset, shifty); this.getFontRenderer().func_78279_b(selectedMod.getMetadata().description, offset, shifty + 10, this.field_73880_f - offset - 20, 0xDDDDDD); } else { offset = ( this.listWidth + this.field_73880_f ) / 2; this.func_73732_a(this.field_73886_k, selectedMod.getName(), offset, 35, 0xFFFFFF); this.func_73732_a(this.field_73886_k, String.format("Version: %s",selectedMod.getVersion()), offset, 45, 0xFFFFFF); this.func_73732_a(this.field_73886_k, String.format("Mod State: %s",Loader.instance().getModState(selectedMod)), offset, 55, 0xFFFFFF); this.func_73732_a(this.field_73886_k, "No mod information found", offset, 65, 0xDDDDDD); this.func_73732_a(this.field_73886_k, "Ask your mod author to provide a mod mcmod.info file", offset, 75, 0xDDDDDD); } GL11.glDisable(GL11.GL_BLEND); } super.func_73863_a(p_571_1_, p_571_2_, p_571_3_); }
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/impl/DvnRGraphServiceImpl.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/impl/DvnRGraphServiceImpl.java index 65160474d..311f95f4e 100644 --- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/impl/DvnRGraphServiceImpl.java +++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/ingest/dsb/impl/DvnRGraphServiceImpl.java @@ -1,724 +1,724 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dvn.ingest.dsb.impl; import edu.harvard.iq.dvn.ingest.dsb.*; import java.io.*; import static java.lang.System.*; import java.util.*; import java.util.logging.*; import java.lang.reflect.*; import java.util.regex.*; import org.rosuda.REngine.*; import org.rosuda.REngine.Rserve.*; import org.apache.commons.lang.*; import org.apache.commons.lang.builder.*; /** * * @author landreev */ public class DvnRGraphServiceImpl{ // - static filelds private static Logger dbgLog = Logger.getLogger(DvnRGraphServiceImpl.class.getPackage().getName()); // - constants for defining the subset queries: public static String RSUBSETFUNCTION = "RSUBSETFUNCTION"; // - different kinds of subset functions: public static String MANUAL_QUERY_SUBSET = "MANUAL_QUERY_SUBSET"; public static String MANUAL_QUERY_TYPE = "MANUAL_QUERY_TYPE"; public static String MANUAL_QUERY = "MANUAL_QUERY"; public static String ELIMINATE_DISCONNECTED = "ELIMINATE_DISCONNECTED"; public static String EDGE_SUBSET = "EDGE_SUBSET"; public static String VERTEX_SUBSET = "VERTEX_SUBSET"; public static String AUTOMATIC_QUERY = "AUTOMATIC_QUERY"; public static String N_VALUE = "N_VALUE"; public static String NTH_LARGEST = "NTH_LARGEST"; public static String NETWORK_MEASURE = "NETWORK_MEASURE"; public static String NETWORK_MEASURE_TYPE = "NETWORK_MEASURE_TYPE"; public static String NETWORK_MEASURE_DEGREE = "NETWORK_MEASURE_DEGREE"; public static String NETWORK_MEASURE_RANK = "NETWORK_MEASURE_RANK"; public static String NETWORK_MEASURE_PARAMETER = "NETWORK_MEASURE_PARAMETER"; // - arguments for the subset functions above: public static String SAVED_RWORK_SPACE = "SAVED_RWORK_SPACE"; public static String NUMBER_OF_VERTICES = "NUMBER_OF_VERTICES"; public static String NUMBER_OF_EDGES = "NUMBER_OF_EDGES"; public static String DVN_TMP_DIR=null; public static String DSB_TMP_DIR=null; private static String GRAPHML_FILE_NAME = "iGraph"; public static String GRAPHML_FILE_EXT =".xml"; private static String RDATA_FILE_NAME = "iGraph"; public static String RDATA_FILE_EXT =".RData"; private static String RSERVE_HOST = null; private static String RSERVE_USER = null; private static String RSERVE_PWD = null; private static int RSERVE_PORT; private static String DSB_HOST_PORT= null; private static Map<String, Method> runMethods = new HashMap<String, Method>(); private static String regexForRunMethods = "^run(\\w+)Request$" ; public static String TEMP_DIR = System.getProperty("java.io.tmpdir"); static { DSB_TMP_DIR = System.getProperty("vdc.dsb.temp.dir"); // fallout case: last resort if (DSB_TMP_DIR == null){ DVN_TMP_DIR ="/tmp/VDC"; DSB_TMP_DIR = DVN_TMP_DIR + "/DSB"; } RSERVE_HOST = System.getProperty("vdc.dsb.host"); DSB_HOST_PORT = System.getProperty("vdc.dsb.port"); if (DSB_HOST_PORT == null){ DSB_HOST_PORT= "80"; } RSERVE_USER = System.getProperty("vdc.dsb.rserve.user"); if (RSERVE_USER == null){ RSERVE_USER= "rserve"; } RSERVE_PWD = System.getProperty("vdc.dsb.rserve.pwrd"); if (RSERVE_PWD == null){ RSERVE_PWD= "rserve"; } if (System.getProperty("vdc.dsb.rserve.port") == null ){ RSERVE_PORT= 6311; } else { RSERVE_PORT = Integer.parseInt(System.getProperty("vdc.dsb.rserve.port")); } } static String librarySetup= "library('NetworkUtils');"; boolean DEBUG = true; // ----------------------------------------------------- instance filelds public String IdSuffix = null; public String GraphMLfileNameRemote = null; public String RDataFileName = null; public String wrkdir = null; public String requestdir = null; public List<String> historyEntry = new ArrayList<String>(); public List<String> replicationFile = new LinkedList<String>(); // ----------------------------------------------------- constructor public DvnRGraphServiceImpl(){ // initialization IdSuffix = RandomStringUtils.randomNumeric(6); requestdir = "Grph_" + IdSuffix; wrkdir = DSB_TMP_DIR + "/" + requestdir; RDataFileName = DSB_TMP_DIR + "/" + RDATA_FILE_NAME +"." + IdSuffix + RDATA_FILE_EXT; GraphMLfileNameRemote = DSB_TMP_DIR + "/" + GRAPHML_FILE_NAME + "." + IdSuffix + GRAPHML_FILE_EXT; } public void setupWorkingDirectories(RConnection c){ try{ // set up the working directory // parent dir; // the 4 lines below are R code being sent over to Rserve; // it looks kinda messy, true. String checkWrkDir = "if (file_test('-d', '"+DSB_TMP_DIR+"')) {Sys.chmod('"+ DVN_TMP_DIR+"', mode = '0777'); Sys.chmod('"+DSB_TMP_DIR+"', mode = '0777');} else {dir.create('"+DSB_TMP_DIR+"', showWarnings = FALSE, recursive = TRUE);Sys.chmod('"+DVN_TMP_DIR+"', mode = '0777');Sys.chmod('"+ DSB_TMP_DIR+"', mode = '0777');}"; dbgLog.fine("w permission="+checkWrkDir); c.voidEval(checkWrkDir); // wrkdir String checkWrkDr = "if (file_test('-d', '"+wrkdir+"')) {Sys.chmod('"+ wrkdir+"', mode = '0777'); } else {dir.create('"+wrkdir+"', showWarnings = FALSE, recursive = TRUE);Sys.chmod('"+wrkdir+"', mode = '0777');}"; dbgLog.fine("w permission:wrkdir="+checkWrkDr); c.voidEval(checkWrkDr); } catch (RserveException rse) { rse.printStackTrace(); } } public void setupWorkingDirectory(RConnection c){ try{ // set up the working directory // parent dir String checkWrkDir = "if (file_test('-d', '"+DSB_TMP_DIR+"')) {Sys.chmod('"+ DVN_TMP_DIR+"', mode = '0777'); Sys.chmod('"+DSB_TMP_DIR+"', mode = '0777');} else {dir.create('"+DSB_TMP_DIR+"', showWarnings = FALSE, recursive = TRUE);Sys.chmod('"+DVN_TMP_DIR+"', mode = '0777');Sys.chmod('"+ DSB_TMP_DIR+"', mode = '0777');}"; dbgLog.fine("w permission="+checkWrkDir); c.voidEval(checkWrkDir); } catch (RserveException rse) { rse.printStackTrace(); } } /** ************************************************************* * Execute an R-based dvn analysis request on a Graph object * * @param sro a DvnRJobRequest object that contains various parameters * @return a Map that contains various information about results */ public Map<String, String> execute(DvnRJobRequest sro) { // set the return object Map<String, String> result = new HashMap<String, String>(); try { if ( sro != null ) { dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE)); } else { result.put("RexecError", "true"); result.put("RexecErrorDescription", "NULL R JOB OBJECT"); return result; } // Set up an Rserve connection dbgLog.fine("RSERVE_USER="+RSERVE_USER+"[default=rserve]"); dbgLog.fine("RSERVE_PWD="+RSERVE_PWD+"[default=rserve]"); dbgLog.fine("RSERVE_PORT="+RSERVE_PORT+"[default=6311]"); RConnection c = new RConnection(RSERVE_HOST, RSERVE_PORT); dbgLog.fine("hostname="+RSERVE_HOST); c.login(RSERVE_USER, RSERVE_PWD); dbgLog.fine(">" + c.eval("R.version$version.string").asString() + "<"); dbgLog.fine("wrkdir="+wrkdir); historyEntry.add(librarySetup); c.voidEval(librarySetup); String SavedRworkSpace = null; String CachedRworkSpace = sro.getCachedRworkSpace(); Map <String, Object> SubsetParameters = sro.getParametersForGraphSubset(); if ( SubsetParameters != null ) { SavedRworkSpace = (String) SubsetParameters.get(SAVED_RWORK_SPACE); } if ( SavedRworkSpace != null ) { RDataFileName = SavedRworkSpace; } else if ( CachedRworkSpace != null ) { // send data file to the Rserve side InputStream inb = new BufferedInputStream(new FileInputStream(CachedRworkSpace)); int bufsize; byte[] bffr = new byte[1024]; RFileOutputStream os = c.createFile(RDataFileName); while ((bufsize = inb.read(bffr)) != -1) { os.write(bffr, 0, bufsize); } os.close(); inb.close(); c.voidEval("load_and_clear('"+RDataFileName+"')"); result.put(SAVED_RWORK_SPACE, RDataFileName); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); c.close(); return result; } dbgLog.fine("RDataFile="+RDataFileName); historyEntry.add("load_and_clear('"+RDataFileName+"')"); c.voidEval("load_and_clear('"+RDataFileName+"')"); // check working directories setupWorkingDirectories(c); // subsetting String GraphSubsetType = (String) SubsetParameters.get(RSUBSETFUNCTION); if ( GraphSubsetType != null ) { if ( GraphSubsetType.equals(NTH_LARGEST) ) { int n = Integer.parseInt((String) SubsetParameters.get(N_VALUE)); String componentFunction = "component(g, " + n + ")"; dbgLog.fine("componentFunction="+componentFunction); historyEntry.add(componentFunction); c.voidEval(componentFunction); } else if ( GraphSubsetType.equals(MANUAL_QUERY_SUBSET) ) { String manualQueryType = (String) SubsetParameters.get(MANUAL_QUERY_TYPE); String manualQuery = (String) SubsetParameters.get(MANUAL_QUERY); String subsetCommand = null; if ( manualQueryType != null ) { if (manualQueryType.equals(EDGE_SUBSET)) { String dropDisconnected = (String) SubsetParameters.get(ELIMINATE_DISCONNECTED); if ( dropDisconnected != null ) { - subsetCommand = "edge_subset(g, "+manualQuery+", "+dropDisconnected+")"; + subsetCommand = "edge_subset(g, '"+manualQuery+"', "+dropDisconnected+")"; } else { - subsetCommand = "edge_subset(g, "+manualQuery+", "+")"; + subsetCommand = "edge_subset(g, '"+manualQuery+"', "+")"; } } else if (manualQueryType.equals(VERTEX_SUBSET)){ - subsetCommand = "edge_subset(g, "+manualQuery+")"; + subsetCommand = "vertex_subset(g, '"+manualQuery+"')"; } dbgLog.fine("manualQuerySubset="+subsetCommand); historyEntry.add(subsetCommand); c.voidEval(subsetCommand); } } else if ( GraphSubsetType.equals(NETWORK_MEASURE) ) { String networkMeasureType = (String) SubsetParameters.get(NETWORK_MEASURE_TYPE); String networkMeasureCommand = null; if ( networkMeasureType != null ) { if ( networkMeasureType.equals(NETWORK_MEASURE_DEGREE) ) { networkMeasureCommand = "add_degree"; } else if ( networkMeasureType.equals(NETWORK_MEASURE_RANK) ) { networkMeasureCommand = "add_rank"; } } } else if ( GraphSubsetType.equals(AUTOMATIC_QUERY) ) { int n = Integer.parseInt((String) SubsetParameters.get(N_VALUE)); String componentFunction = "component(g, " + n + ")"; dbgLog.fine("componentFunction="+componentFunction); historyEntry.add(componentFunction); c.voidEval(componentFunction); } } // get the vertices and edges counts: String countCommand = "vcount(g)"; String countResponse = c.eval(countCommand).asString(); result.put(NUMBER_OF_VERTICES, countResponse); countCommand = "ecount(g)"; countResponse = c.eval(countCommand).asString(); result.put(NUMBER_OF_EDGES, countResponse); // save workspace as a replication data set String saveWS = "save(g, file='"+ RDataFileName +"')"; dbgLog.fine("save the workspace="+saveWS); c.voidEval(saveWS); result.put( SAVED_RWORK_SPACE, RDataFileName ); // we're done; let's add some potentially useful // information to the result and return: String RexecDate = c.eval("as.character(as.POSIXct(Sys.time()))").asString(); String RversionLine = "R.Version()$version.string"; String Rversion = c.eval(RversionLine).asString(); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); result.put("Rversion", Rversion); result.put("RexecDate", RexecDate); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); dbgLog.fine("result object (before closing the Rserve):\n"+result); c.close(); } catch (RserveException rse) { // RserveException (Rserve not running?) result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); result.put("RexecErrorMessage", rse.getMessage()); result.put("RexecErrorDescription", rse.getRequestErrorDescription()); return result; } catch (REXPMismatchException mme) { // REXP mismatch exception (what we got differs from what we expected) result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (IOException ie){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (Exception ex){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } return result; } /** ************************************************************* * Execute an R-based "ingest" of a GraphML file * * @param graphMLfileName; * @param cachedRDatafileName; * @return a Map that contains various information about results */ public Map<String, String> ingestGraphML (String graphMLfileName, String cachedRDatafileName) { Map<String, String> result = new HashMap<String, String>(); try { // Set up an Rserve connection dbgLog.fine("RSERVE_USER="+RSERVE_USER+"[default=rserve]"); dbgLog.fine("RSERVE_PWD="+RSERVE_PWD+"[default=rserve]"); dbgLog.fine("RSERVE_PORT="+RSERVE_PORT+"[default=6311]"); RConnection c = new RConnection(RSERVE_HOST, RSERVE_PORT); dbgLog.fine("hostname="+RSERVE_HOST); c.login(RSERVE_USER, RSERVE_PWD); dbgLog.fine(">" + c.eval("R.version$version.string").asString() + "<"); // send the graphML to the Rserve side InputStream inb = new BufferedInputStream(new FileInputStream(graphMLfileName)); int bufsize; byte[] bffr = new byte[1024]; RFileOutputStream os = c.createFile(GraphMLfileNameRemote); while ((bufsize = inb.read(bffr)) != -1) { os.write(bffr, 0, bufsize); } os.close(); inb.close(); historyEntry.add(librarySetup); c.voidEval(librarySetup); this.setupWorkingDirectories(c); // ingest itself: String ingestCommand = "ingest_graphml('" + GraphMLfileNameRemote + "')"; dbgLog.fine(ingestCommand); historyEntry.add(ingestCommand); c.voidEval(ingestCommand); int fileSize = getFileSize(c,RDataFileName); OutputStream outbr = new BufferedOutputStream(new FileOutputStream(new File(cachedRDatafileName))); RFileInputStream ris = c.openFile(RDataFileName); if (fileSize < 64*1024*1024){ bufsize = fileSize; } else { bufsize = 64*1024*1024; } byte[] obuf = new byte[bufsize]; while ( ris.read(obuf) != -1 ) { outbr.write(obuf, 0, bufsize); } ris.close(); outbr.close(); String RexecDate = c.eval("as.character(as.POSIXct(Sys.time()))").asString(); String RversionLine = "R.Version()$version.string"; String Rversion = c.eval(RversionLine).asString(); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); result.put("Rversion", Rversion); result.put("RexecDate", RexecDate); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); dbgLog.fine("result object (before closing the Rserve):\n"+result); c.close(); } catch (RserveException rse) { result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); result.put("RexecErrorMessage", rse.getMessage()); result.put("RexecErrorDescription", rse.getRequestErrorDescription()); return result; } catch (REXPMismatchException mme) { result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (FileNotFoundException fe){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); result.put("RexecErrorDescription", "File Not Found"); return result; } catch (IOException ie){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (Exception ex){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } return result; } // -- utilitiy methods /** * Returns the array of values that corresponds the order of * provided keys * * @param * @return */ public static String[] getValueSet(Map<String, String> mp, String[] keys) { List<String> tmpvl = new ArrayList<String>(); for (int i=0; i< keys.length; i++){ tmpvl.add(mp.get(keys[i])); } String[] tmpv = (String[])tmpvl.toArray(new String[tmpvl.size()]); return tmpv; } /** ************************************************************* * * * @param * @return */ public String joinNelementsPerLine(String[] vn, int divisor){ String vnl = null; if (vn.length < divisor){ vnl = StringUtils.join(vn, ", "); } else { StringBuilder sb = new StringBuilder(); int iter = vn.length / divisor; int lastN = vn.length % divisor; if (lastN != 0){ iter++; } int iterm = iter - 1; for (int i= 0; i<iter; i++){ int terminalN = divisor; if ((i == iterm ) && (lastN != 0)){ terminalN = lastN; } for (int j = 0; j< terminalN; j++){ if ( (divisor*i +j +1) == vn.length){ sb.append(vn[j + i*divisor]); } else { sb.append(vn[j + i*divisor] + ", "); } } sb.append("\n"); } vnl = sb.toString(); dbgLog.fine(vnl); } return vnl; } /** ************************************************************* * * * @param * @return */ public String joinNelementsPerLine(String[] vn, int divisor, String sp, boolean quote, String qm, String lnsp){ if (!(divisor >= 1)){ divisor = 1; } else if ( divisor > vn.length) { divisor = vn.length; } String sep = null; if (sp != null){ sep = sp; } else { sep = ", "; } String qmrk = null; if (quote){ if (qm == null){ qmrk = ","; } else { if (qm.equals("\"")){ qmrk = "\""; } else { qmrk = qm; } } } else { qmrk = ""; } String lineSep = null; if (lnsp == null){ lineSep = "\n"; } else { lineSep = lnsp; } String vnl = null; if (vn.length < divisor){ vnl = StringUtils.join(vn, sep); } else { StringBuilder sb = new StringBuilder(); int iter = vn.length / divisor; int lastN = vn.length % divisor; if (lastN != 0){ iter++; } int iterm = iter - 1; for (int i= 0; i<iter; i++){ int terminalN = divisor; if ((i == iterm ) && (lastN != 0)){ terminalN = lastN; } for (int j = 0; j< terminalN; j++){ if ( (divisor*i +j +1) == vn.length){ sb.append(qmrk + vn[j + i*divisor] + qmrk); } else { sb.append(qmrk + vn[j + i*divisor] + qmrk + sep); } } if (i < (iter-1)){ sb.append(lineSep); } } vnl = sb.toString(); dbgLog.fine("results:\n"+vnl); } return vnl; } /** ************************************************************* * * * @param * @return */ public int getFileSize(RConnection c, String targetFilename){ dbgLog.fine("targetFilename="+targetFilename); int fileSize = 0; try { String fileSizeLine = "round(file.info('"+targetFilename+"')$size)"; fileSize = c.eval(fileSizeLine).asInteger(); } catch (RserveException rse) { rse.printStackTrace(); } catch (REXPMismatchException mme) { mme.printStackTrace(); } return fileSize; } }
false
true
public Map<String, String> execute(DvnRJobRequest sro) { // set the return object Map<String, String> result = new HashMap<String, String>(); try { if ( sro != null ) { dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE)); } else { result.put("RexecError", "true"); result.put("RexecErrorDescription", "NULL R JOB OBJECT"); return result; } // Set up an Rserve connection dbgLog.fine("RSERVE_USER="+RSERVE_USER+"[default=rserve]"); dbgLog.fine("RSERVE_PWD="+RSERVE_PWD+"[default=rserve]"); dbgLog.fine("RSERVE_PORT="+RSERVE_PORT+"[default=6311]"); RConnection c = new RConnection(RSERVE_HOST, RSERVE_PORT); dbgLog.fine("hostname="+RSERVE_HOST); c.login(RSERVE_USER, RSERVE_PWD); dbgLog.fine(">" + c.eval("R.version$version.string").asString() + "<"); dbgLog.fine("wrkdir="+wrkdir); historyEntry.add(librarySetup); c.voidEval(librarySetup); String SavedRworkSpace = null; String CachedRworkSpace = sro.getCachedRworkSpace(); Map <String, Object> SubsetParameters = sro.getParametersForGraphSubset(); if ( SubsetParameters != null ) { SavedRworkSpace = (String) SubsetParameters.get(SAVED_RWORK_SPACE); } if ( SavedRworkSpace != null ) { RDataFileName = SavedRworkSpace; } else if ( CachedRworkSpace != null ) { // send data file to the Rserve side InputStream inb = new BufferedInputStream(new FileInputStream(CachedRworkSpace)); int bufsize; byte[] bffr = new byte[1024]; RFileOutputStream os = c.createFile(RDataFileName); while ((bufsize = inb.read(bffr)) != -1) { os.write(bffr, 0, bufsize); } os.close(); inb.close(); c.voidEval("load_and_clear('"+RDataFileName+"')"); result.put(SAVED_RWORK_SPACE, RDataFileName); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); c.close(); return result; } dbgLog.fine("RDataFile="+RDataFileName); historyEntry.add("load_and_clear('"+RDataFileName+"')"); c.voidEval("load_and_clear('"+RDataFileName+"')"); // check working directories setupWorkingDirectories(c); // subsetting String GraphSubsetType = (String) SubsetParameters.get(RSUBSETFUNCTION); if ( GraphSubsetType != null ) { if ( GraphSubsetType.equals(NTH_LARGEST) ) { int n = Integer.parseInt((String) SubsetParameters.get(N_VALUE)); String componentFunction = "component(g, " + n + ")"; dbgLog.fine("componentFunction="+componentFunction); historyEntry.add(componentFunction); c.voidEval(componentFunction); } else if ( GraphSubsetType.equals(MANUAL_QUERY_SUBSET) ) { String manualQueryType = (String) SubsetParameters.get(MANUAL_QUERY_TYPE); String manualQuery = (String) SubsetParameters.get(MANUAL_QUERY); String subsetCommand = null; if ( manualQueryType != null ) { if (manualQueryType.equals(EDGE_SUBSET)) { String dropDisconnected = (String) SubsetParameters.get(ELIMINATE_DISCONNECTED); if ( dropDisconnected != null ) { subsetCommand = "edge_subset(g, "+manualQuery+", "+dropDisconnected+")"; } else { subsetCommand = "edge_subset(g, "+manualQuery+", "+")"; } } else if (manualQueryType.equals(VERTEX_SUBSET)){ subsetCommand = "edge_subset(g, "+manualQuery+")"; } dbgLog.fine("manualQuerySubset="+subsetCommand); historyEntry.add(subsetCommand); c.voidEval(subsetCommand); } } else if ( GraphSubsetType.equals(NETWORK_MEASURE) ) { String networkMeasureType = (String) SubsetParameters.get(NETWORK_MEASURE_TYPE); String networkMeasureCommand = null; if ( networkMeasureType != null ) { if ( networkMeasureType.equals(NETWORK_MEASURE_DEGREE) ) { networkMeasureCommand = "add_degree"; } else if ( networkMeasureType.equals(NETWORK_MEASURE_RANK) ) { networkMeasureCommand = "add_rank"; } } } else if ( GraphSubsetType.equals(AUTOMATIC_QUERY) ) { int n = Integer.parseInt((String) SubsetParameters.get(N_VALUE)); String componentFunction = "component(g, " + n + ")"; dbgLog.fine("componentFunction="+componentFunction); historyEntry.add(componentFunction); c.voidEval(componentFunction); } } // get the vertices and edges counts: String countCommand = "vcount(g)"; String countResponse = c.eval(countCommand).asString(); result.put(NUMBER_OF_VERTICES, countResponse); countCommand = "ecount(g)"; countResponse = c.eval(countCommand).asString(); result.put(NUMBER_OF_EDGES, countResponse); // save workspace as a replication data set String saveWS = "save(g, file='"+ RDataFileName +"')"; dbgLog.fine("save the workspace="+saveWS); c.voidEval(saveWS); result.put( SAVED_RWORK_SPACE, RDataFileName ); // we're done; let's add some potentially useful // information to the result and return: String RexecDate = c.eval("as.character(as.POSIXct(Sys.time()))").asString(); String RversionLine = "R.Version()$version.string"; String Rversion = c.eval(RversionLine).asString(); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); result.put("Rversion", Rversion); result.put("RexecDate", RexecDate); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); dbgLog.fine("result object (before closing the Rserve):\n"+result); c.close(); } catch (RserveException rse) { // RserveException (Rserve not running?) result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); result.put("RexecErrorMessage", rse.getMessage()); result.put("RexecErrorDescription", rse.getRequestErrorDescription()); return result; } catch (REXPMismatchException mme) { // REXP mismatch exception (what we got differs from what we expected) result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (IOException ie){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (Exception ex){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } return result; }
public Map<String, String> execute(DvnRJobRequest sro) { // set the return object Map<String, String> result = new HashMap<String, String>(); try { if ( sro != null ) { dbgLog.fine("sro dump:\n"+ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE)); } else { result.put("RexecError", "true"); result.put("RexecErrorDescription", "NULL R JOB OBJECT"); return result; } // Set up an Rserve connection dbgLog.fine("RSERVE_USER="+RSERVE_USER+"[default=rserve]"); dbgLog.fine("RSERVE_PWD="+RSERVE_PWD+"[default=rserve]"); dbgLog.fine("RSERVE_PORT="+RSERVE_PORT+"[default=6311]"); RConnection c = new RConnection(RSERVE_HOST, RSERVE_PORT); dbgLog.fine("hostname="+RSERVE_HOST); c.login(RSERVE_USER, RSERVE_PWD); dbgLog.fine(">" + c.eval("R.version$version.string").asString() + "<"); dbgLog.fine("wrkdir="+wrkdir); historyEntry.add(librarySetup); c.voidEval(librarySetup); String SavedRworkSpace = null; String CachedRworkSpace = sro.getCachedRworkSpace(); Map <String, Object> SubsetParameters = sro.getParametersForGraphSubset(); if ( SubsetParameters != null ) { SavedRworkSpace = (String) SubsetParameters.get(SAVED_RWORK_SPACE); } if ( SavedRworkSpace != null ) { RDataFileName = SavedRworkSpace; } else if ( CachedRworkSpace != null ) { // send data file to the Rserve side InputStream inb = new BufferedInputStream(new FileInputStream(CachedRworkSpace)); int bufsize; byte[] bffr = new byte[1024]; RFileOutputStream os = c.createFile(RDataFileName); while ((bufsize = inb.read(bffr)) != -1) { os.write(bffr, 0, bufsize); } os.close(); inb.close(); c.voidEval("load_and_clear('"+RDataFileName+"')"); result.put(SAVED_RWORK_SPACE, RDataFileName); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); c.close(); return result; } dbgLog.fine("RDataFile="+RDataFileName); historyEntry.add("load_and_clear('"+RDataFileName+"')"); c.voidEval("load_and_clear('"+RDataFileName+"')"); // check working directories setupWorkingDirectories(c); // subsetting String GraphSubsetType = (String) SubsetParameters.get(RSUBSETFUNCTION); if ( GraphSubsetType != null ) { if ( GraphSubsetType.equals(NTH_LARGEST) ) { int n = Integer.parseInt((String) SubsetParameters.get(N_VALUE)); String componentFunction = "component(g, " + n + ")"; dbgLog.fine("componentFunction="+componentFunction); historyEntry.add(componentFunction); c.voidEval(componentFunction); } else if ( GraphSubsetType.equals(MANUAL_QUERY_SUBSET) ) { String manualQueryType = (String) SubsetParameters.get(MANUAL_QUERY_TYPE); String manualQuery = (String) SubsetParameters.get(MANUAL_QUERY); String subsetCommand = null; if ( manualQueryType != null ) { if (manualQueryType.equals(EDGE_SUBSET)) { String dropDisconnected = (String) SubsetParameters.get(ELIMINATE_DISCONNECTED); if ( dropDisconnected != null ) { subsetCommand = "edge_subset(g, '"+manualQuery+"', "+dropDisconnected+")"; } else { subsetCommand = "edge_subset(g, '"+manualQuery+"', "+")"; } } else if (manualQueryType.equals(VERTEX_SUBSET)){ subsetCommand = "vertex_subset(g, '"+manualQuery+"')"; } dbgLog.fine("manualQuerySubset="+subsetCommand); historyEntry.add(subsetCommand); c.voidEval(subsetCommand); } } else if ( GraphSubsetType.equals(NETWORK_MEASURE) ) { String networkMeasureType = (String) SubsetParameters.get(NETWORK_MEASURE_TYPE); String networkMeasureCommand = null; if ( networkMeasureType != null ) { if ( networkMeasureType.equals(NETWORK_MEASURE_DEGREE) ) { networkMeasureCommand = "add_degree"; } else if ( networkMeasureType.equals(NETWORK_MEASURE_RANK) ) { networkMeasureCommand = "add_rank"; } } } else if ( GraphSubsetType.equals(AUTOMATIC_QUERY) ) { int n = Integer.parseInt((String) SubsetParameters.get(N_VALUE)); String componentFunction = "component(g, " + n + ")"; dbgLog.fine("componentFunction="+componentFunction); historyEntry.add(componentFunction); c.voidEval(componentFunction); } } // get the vertices and edges counts: String countCommand = "vcount(g)"; String countResponse = c.eval(countCommand).asString(); result.put(NUMBER_OF_VERTICES, countResponse); countCommand = "ecount(g)"; countResponse = c.eval(countCommand).asString(); result.put(NUMBER_OF_EDGES, countResponse); // save workspace as a replication data set String saveWS = "save(g, file='"+ RDataFileName +"')"; dbgLog.fine("save the workspace="+saveWS); c.voidEval(saveWS); result.put( SAVED_RWORK_SPACE, RDataFileName ); // we're done; let's add some potentially useful // information to the result and return: String RexecDate = c.eval("as.character(as.POSIXct(Sys.time()))").asString(); String RversionLine = "R.Version()$version.string"; String Rversion = c.eval(RversionLine).asString(); result.put("dsbHost", RSERVE_HOST); result.put("dsbPort", DSB_HOST_PORT); result.put("IdSuffix", IdSuffix); result.put("Rversion", Rversion); result.put("RexecDate", RexecDate); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); dbgLog.fine("result object (before closing the Rserve):\n"+result); c.close(); } catch (RserveException rse) { // RserveException (Rserve not running?) result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); result.put("RexecErrorMessage", rse.getMessage()); result.put("RexecErrorDescription", rse.getRequestErrorDescription()); return result; } catch (REXPMismatchException mme) { // REXP mismatch exception (what we got differs from what we expected) result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (IOException ie){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } catch (Exception ex){ result.put("IdSuffix", IdSuffix); result.put("RCommandHistory", StringUtils.join(historyEntry,"\n")); result.put("RexecError", "true"); return result; } return result; }
diff --git a/src/org/shangjiyu/twidere/extension/translator/SettingsActivity.java b/src/org/shangjiyu/twidere/extension/translator/SettingsActivity.java index 2d6ceb8..ab21b0e 100644 --- a/src/org/shangjiyu/twidere/extension/translator/SettingsActivity.java +++ b/src/org/shangjiyu/twidere/extension/translator/SettingsActivity.java @@ -1,75 +1,75 @@ /******************************************************* * @Title: SettingsActivity.java * @Package org.shangjiyu.twidere.extension.translaetor * @Description: TODO(显示设置页面) * @author shangjiyu * @date 2013-10-10 下午1:55:28 * @version V1.0 ********************************************************/ package org.shangjiyu.twidere.extension.translator; import org.shangjiyu.twidere.extension.translator.R; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.preference.PreferenceActivity; import android.widget.Toast; /******************************************************** * @ClassName: SettingsActivity * @Description: TODO(设置页面) * @author shangjiyu * @date 2013-10-10 下午1:55:28 */ public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { private SharedPreferences sharedPreferences; @SuppressWarnings("deprecation") @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); addPreferencesFromResource(R.xml.settings); sharedPreferences.registerOnSharedPreferenceChangeListener(this); } /******************************************************** *Title: onSharedPreferenceChanged *Description: * @param sharedPreferences * @param key * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String) *********************************************************/ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO Auto-generated method stub if (sharedPreferences.getBoolean(getString(R.string.baidu_translate_api_checkbox), false)) { String baiduAPIKey = sharedPreferences.getString(getString(R.string.baidu_client_id_value), null); if ( baiduAPIKey != null && baiduAPIKey.length() == 24) { BDTranslate.BDTRANSLATEKEY_STRING = baiduAPIKey; }else { - Toast.makeText(SettingsActivity.this, "incorrec baidu app key!please reinpiut", Toast.LENGTH_LONG).show(); + Toast.makeText(SettingsActivity.this, "incorrect baidu app key!please reinpiut", Toast.LENGTH_SHORT).show(); } }else if (sharedPreferences.getBoolean(getString(R.string.microsoft_translate_api_checkbox), false)) { - String bingAPIkey = sharedPreferences.getString(getString(R.string.microsoft_client_secret_value), null); + String bingAPIkey = sharedPreferences.getString(getString(R.string.Bing_client_secret_value), null); if (bingAPIkey != null && bingAPIkey.length() == 44) { MSTranslate.CLIEND_SECRET_STRING = bingAPIkey; }else { - Toast.makeText(SettingsActivity.this, "incorrec Bing API Secret!please reinpiut", Toast.LENGTH_LONG).show(); + Toast.makeText(SettingsActivity.this, "incorrect Bing API Secret!please reinpiut", Toast.LENGTH_SHORT).show(); } } } }
false
true
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO Auto-generated method stub if (sharedPreferences.getBoolean(getString(R.string.baidu_translate_api_checkbox), false)) { String baiduAPIKey = sharedPreferences.getString(getString(R.string.baidu_client_id_value), null); if ( baiduAPIKey != null && baiduAPIKey.length() == 24) { BDTranslate.BDTRANSLATEKEY_STRING = baiduAPIKey; }else { Toast.makeText(SettingsActivity.this, "incorrec baidu app key!please reinpiut", Toast.LENGTH_LONG).show(); } }else if (sharedPreferences.getBoolean(getString(R.string.microsoft_translate_api_checkbox), false)) { String bingAPIkey = sharedPreferences.getString(getString(R.string.microsoft_client_secret_value), null); if (bingAPIkey != null && bingAPIkey.length() == 44) { MSTranslate.CLIEND_SECRET_STRING = bingAPIkey; }else { Toast.makeText(SettingsActivity.this, "incorrec Bing API Secret!please reinpiut", Toast.LENGTH_LONG).show(); } } }
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO Auto-generated method stub if (sharedPreferences.getBoolean(getString(R.string.baidu_translate_api_checkbox), false)) { String baiduAPIKey = sharedPreferences.getString(getString(R.string.baidu_client_id_value), null); if ( baiduAPIKey != null && baiduAPIKey.length() == 24) { BDTranslate.BDTRANSLATEKEY_STRING = baiduAPIKey; }else { Toast.makeText(SettingsActivity.this, "incorrect baidu app key!please reinpiut", Toast.LENGTH_SHORT).show(); } }else if (sharedPreferences.getBoolean(getString(R.string.microsoft_translate_api_checkbox), false)) { String bingAPIkey = sharedPreferences.getString(getString(R.string.Bing_client_secret_value), null); if (bingAPIkey != null && bingAPIkey.length() == 44) { MSTranslate.CLIEND_SECRET_STRING = bingAPIkey; }else { Toast.makeText(SettingsActivity.this, "incorrect Bing API Secret!please reinpiut", Toast.LENGTH_SHORT).show(); } } }
diff --git a/src/org/bennedum/transporter/Teleport.java b/src/org/bennedum/transporter/Teleport.java index 96557d3..db44857 100644 --- a/src/org/bennedum/transporter/Teleport.java +++ b/src/org/bennedum/transporter/Teleport.java @@ -1,797 +1,797 @@ /* * Copyright 2011 frdfsnlght <[email protected]>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bennedum.transporter; import com.iConomy.iConomy; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.StorageMinecart; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.util.Vector; /** * * @author frdfsnlght <[email protected]> */ public final class Teleport { private static final int DEFAULT_ARRIVAL_WINDOW = 20000; private static final Map<String,String> pins = new HashMap<String,String>(); private static final Set<Integer> gateLocks = new HashSet<Integer>(); private static final Map<String,PlayerArrival> arrivals = new HashMap<String,PlayerArrival>(); public static void removeGateLock(Entity entity) { synchronized (gateLocks) { gateLocks.remove(entity.getEntityId()); } } public static boolean isGateLocked(Entity entity) { synchronized (gateLocks) { return gateLocks.contains(entity.getEntityId()); } } public static void addGateLock(Entity entity) { synchronized (gateLocks) { gateLocks.add(entity.getEntityId()); } } public static void setPin(Player player, String pin) { synchronized (pins) { pins.put(player.getName(), pin); } } public static String getPin(Player player) { if (player == null) return null; return getPin(player.getName()); } public static String getPin(String playerName) { synchronized (pins) { return pins.get(playerName); } } public static boolean expectingArrival(Player player) { synchronized (arrivals) { return arrivals.containsKey(player.getName()); } } // called when an entity moves into a gate on our server public static Location send(Entity entity, LocalGate fromGate) throws TeleportException { addGateLock(entity); Gate toGate; try { toGate = fromGate.getDestinationGate(); } catch (GateException ge) { throw new TeleportException(ge.getMessage()); } toGate.attach(fromGate); if (toGate.isSameServer()) { return send(entity, fromGate, (LocalGate)toGate); } else { send(entity, fromGate, (RemoteGate)toGate); return null; } } // called when a player goes directly to a gate public static Location sendDirect(Player player, Gate toGate) throws TeleportException { if (toGate.isSameServer()) { return send(player, null, (LocalGate)toGate); } else { send(player, null, (RemoteGate)toGate); return null; } } // called when an entity is traveling between gates on our server // fromGate can be null if the player is being sent directly private static Location send(Entity entity, LocalGate fromGate, LocalGate toGate) throws TeleportException { Player player = null; String pin = null; Context ctx = null; if (entity instanceof Player) player = (Player)entity; else if (entity.getPassenger() instanceof Player) player = (Player)entity.getPassenger(); if (player != null) { pin = getPin(player); ctx = new Context(player); } if (player != null) { // check permissions if (fromGate != null) { try { ctx.requireAllPermissions("trp.use." + fromGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use this gate"); } } try { ctx.requireAllPermissions("trp.use." + toGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use the remote gate"); } // check pin if ((fromGate != null) && fromGate.getRequirePin()) { if (pin == null) throw new TeleportException("this gate requires a pin"); if (! fromGate.hasPin(pin)) throw new TeleportException("this gate rejected your pin"); } if (toGate.getRequirePin()) { if (pin == null) throw new TeleportException("remote gate requires a pin"); if ((! toGate.hasPin(pin)) && toGate.getRequireValidPin()) throw new TeleportException("remote gate rejected your pin"); } // check funds double travelCost; if (fromGate != null) { if (fromGate.isSameWorld(toGate)) travelCost = fromGate.getSendLocalCost() + toGate.getReceiveLocalCost(); else travelCost = fromGate.getSendWorldCost() + toGate.getReceiveWorldCost(); } else { if (toGate.isSameWorld(entity.getWorld())) travelCost = toGate.getReceiveLocalCost(); else travelCost = toGate.getReceiveWorldCost(); } try { ctx.requireFunds(travelCost); } catch (FundsException fe) { throw new TeleportException("gate use requires %s", iConomy.format(travelCost)); } } // check inventory if (! checkInventory(entity, toGate)) - throw new TeleportException("remote gate won't some inventory items"); + throw new TeleportException("remote gate won't allow some inventory items"); if ((fromGate != null) && Global.config.getBoolean("useGatePermissions", false)) { try { Permissions.requirePermissions(fromGate.getWorldName(), fromGate.getName(), true, "trp.send." + toGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("this gate is not permitted to send to the remote gate"); } try { Permissions.requirePermissions(toGate.getWorldName(), toGate.getName(), true, "trp.receive." + fromGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("the remote gate is not permitted to receive from this gate"); } } // do the teleport Location currentLoc = entity.getLocation(); Location newLocation = prepareSpawnLocation(currentLoc.getPitch(), currentLoc.getYaw(), (fromGate == null) ? null : fromGate.getDirection(), toGate); // this is necessary so minecarts don't sink into the ground // it also gives them a little push out of the gate if (! (entity instanceof Player)) newLocation.setY(newLocation.getY() + 0.5); Vector velocity = entity.getVelocity(); velocity.multiply(2); velocity.setY(0); entity.setVelocity(velocity); if (! entity.teleport(newLocation)) throw new TeleportException("teleport to '%s' failed", toGate.getFullName()); if (filterInventory(entity, toGate)) { if (player == null) Utils.info("some inventory items where filtered by the remote gate"); else ctx.sendLog("some inventory items where filtered by the remote gate"); } if (player == null) Utils.info("teleported entity '%d' to '%s'", entity.getEntityId(), toGate.getFullName()); else { ctx.sendLog(ChatColor.GOLD + "teleported to '%s'", toGate.getName(ctx)); // do damage for invalid pin if (toGate.getRequirePin() && (! toGate.hasPin(pin)) && (! toGate.getRequireValidPin()) && (toGate.getInvalidPinDamage() > 0)) { ctx.sendLog("invalid pin"); player.damage(toGate.getInvalidPinDamage()); } // deduct funds try { if (fromGate != null) { if (fromGate.isSameWorld(toGate)) { ctx.chargeFunds(fromGate.getSendLocalCost(), "debited $$ for on-world transmission"); ctx.chargeFunds(toGate.getReceiveLocalCost(), "debited $$ for on-world reception"); } else { ctx.chargeFunds(fromGate.getSendWorldCost(), "debited $$ for off-world transmission"); ctx.chargeFunds(toGate.getReceiveWorldCost(), "debited $$ for off-world reception"); } } else { if (toGate.isSameWorld(entity.getWorld())) ctx.chargeFunds(toGate.getReceiveLocalCost(), "debited $$ for on-world reception"); else ctx.chargeFunds(toGate.getReceiveWorldCost(), "debited $$ for off-world reception"); } } catch (FundsException fe) { ctx.warnLog("unable to deduct travel costs: %s", fe.getMessage()); } } return newLocation; } // called when an entity on our server is being sent to another server // fromGate can be null if the player is being sent directly private static void send(final Entity entity, final LocalGate fromGate, final RemoteGate toGate) throws TeleportException { final Player player; final String pin; final Context ctx; if (entity instanceof Player) player = (Player)entity; else if (entity.getPassenger() instanceof Player) player = (Player)entity.getPassenger(); else player = null; if (player == null) { pin = null; ctx = null; } else { pin = getPin(player); ctx = new Context(player); } if ((player != null) && (fromGate != null)) { // check permissions on our side try { ctx.requireAllPermissions("trp.use." + fromGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use this gate"); } // check pin if (fromGate.getRequirePin()) { if (pin == null) throw new TeleportException("this gate requires a pin"); if (! fromGate.hasPin(pin)) throw new TeleportException("this gate rejected your pin"); } // check funds try { ctx.requireFunds(fromGate.getSendServerCost()); } catch (FundsException fe) { throw new TeleportException("this gate requires %s", iConomy.format(fromGate.getSendWorldCost())); } } if ((fromGate != null) && Global.config.getBoolean("useGatePermissions", false)) try { Permissions.requirePermissions(fromGate.getWorldName(), fromGate.getName(), true, "trp.send." + toGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("this gate is not permitted to send to the remote gate"); } // check connection if (! toGate.getServer().isConnected()) throw new TeleportException("server '%s' is offline", toGate.getServer().getName()); if (player == null) Utils.info("teleporting entity '%d' to '%s'...", entity.getEntityId(), toGate.getFullName()); else Utils.info("teleporting player '%s' to '%s'...", player.getName(), toGate.getFullName()); // tell other side to check things // if we get a positive response, do our half of the teleport Utils.worker(new Runnable() { @Override public void run() { try { // this call will block until we get a response // if no exception is thrown, we can go ahead and send the entity on our side toGate.getServer().doExpectEntity(entity, fromGate, toGate); // remote side is ready to receive, so clean up here Utils.fire(new Runnable() { @Override public void run() { if (player != null) { ctx.send(ChatColor.GOLD + "teleporting to '%s'...", toGate.getName(ctx)); // charge funds if (fromGate != null) { try { ctx.chargeFunds(fromGate.getSendServerCost(), "debited $$ for off-server transmission"); } catch (FundsException fe) {} } String mcAddress = toGate.getServer().getMinecraftAddress(); if (mcAddress == null) { Utils.warning("minecraft address for '%s' is null?", toGate.getServer().getName()); return; } String[] addrParts = mcAddress.split("/"); if (addrParts.length == 1) { // this is a client based reconnect Utils.info("sending player '%s' to '%s' via client reconnect", player.getName(), addrParts[0]); player.kickPlayer("[" + Global.pluginName + " Client] please reconnect to: " + addrParts[0]); } else { // this is a proxy based reconnect Utils.info("sending player '%s' to '%s,%s' via proxy reconnect", player.getName(), addrParts[0], addrParts[1]); player.kickPlayer("[" + Global.pluginName + " Proxy] please reconnect to: " + addrParts[0] + "," + addrParts[1]); } } } }); } catch (final ServerException e) { Utils.fire(new Runnable() { @Override public void run() { if (player != null) ctx.warnLog("server '%s' complained: %s", toGate.getServer().getName(), e.getMessage()); else Utils.warning("server '%s' complained: %s", toGate.getServer().getName(), e.getMessage()); } }); } } }); } // called when another server is sending an entity our way, with or without a player // throw an exception, which will be returned to the sender, if we won't accept the entity // fromGateName and fromGateDirection can be null if the player is being sent directly public static void expect(final EntityState entityState, Server fromServer, String fromGateName, String toGateName, final BlockFace fromGateDirection) throws TeleportException { Gate gate; final RemoteGate fromGate; if (fromGateName != null) { gate = Global.gates.get(fromGateName); if (gate == null) throw new TeleportException("unknown gate '%s'", fromGateName); if (gate.isSameServer()) throw new TeleportException("fromGate must be a remote gate"); fromGate = (RemoteGate)gate; } else fromGate = null; gate = Global.gates.get(toGateName); if (gate == null) throw new TeleportException("unknown gate '%s'", toGateName); if (! gate.isSameServer()) throw new TeleportException("toGate must be a local gate"); final LocalGate toGate = (LocalGate)gate; // playerState will be null if no player is involved PlayerState playerState = entityState.getPlayerState(); if (playerState != null) { // check permissions on our side try { if (! Permissions.isAllowedToConnect(playerState.getName(), playerState.getIPAddress())) throw new TeleportException("player is not allowed to connect"); Permissions.requirePermissions(toGate.getWorldName(), playerState.getName(), true, "trp.use." + toGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use the remote gate"); } // check pin if (toGate.getRequirePin()) { String pin = playerState.getPin(); if (pin == null) throw new TeleportException("remote gate requires a pin"); if ((! toGate.hasPin(pin)) && toGate.getRequireValidPin()) throw new TeleportException("remote gate rejected your pin"); } // check funds try { Utils.deductFunds(playerState.getName(), toGate.getReceiveServerCost(), true); } catch (FundsException fe) { throw new TeleportException("gate use requires %s", iConomy.format(toGate.getReceiveServerCost())); } // check inventory if (! checkInventory(playerState, toGate)) throw new TeleportException("remote gate won't allow items in your inventory"); } else { // check inventory if (! checkInventory(entityState, toGate)) throw new TeleportException("remote gate won't allow items in inventory"); } if ((fromGate != null) && Global.config.getBoolean("useGatePermissions", false)) { try { Permissions.requirePermissions(toGate.getWorldName(), toGate.getName(), true, "trp.receive." + fromGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("the remote gate is not permitted to receive from this gate"); } } Utils.fire(new Runnable() { @Override public void run() { Utils.info("expecting '%s' from '%s'...", entityState.getName(), fromGate.getFullName()); } }); if (playerState == null) { // there's no player coming, so let the other side know and instantiate the entity now fromServer.doConfirmArrival(entityState, fromGateName, toGateName); Utils.fire(new Runnable() { @Override public void run() { Utils.info("sent confirmation of arrival of '%s' from '%s'...", entityState.getName(), fromGate.getFullName()); Location location = prepareSpawnLocation(entityState.getPitch(), entityState.getYaw(), fromGateDirection, toGate); Entity entity = entityState.restore(location, null); if (entity != null) { addGateLock(entity); if (filterInventory(entity, toGate)) Utils.info("some inventory items where filtered by the remote gate"); Utils.info("teleported '%s' to '%s'", entityState.getName(), toGate.getFullName()); } else Utils.warning("unable to teleport '%s' to '%s'", entityState.getName(), toGate.getFullName()); } }); } else { // save the info away and wait for the player to connect final PlayerArrival arrival = new PlayerArrival(entityState, fromServer.getName(), fromGateName, toGateName, fromGateDirection); synchronized (arrivals) { arrivals.put(playerState.getName(), arrival); } // set up a delayed task to cancel the arrival if they never arrive Utils.fireDelayed(new Runnable() { @Override public void run() { cancel(arrival); } }, Global.config.getInt("arrivalWindow", DEFAULT_ARRIVAL_WINDOW)); } } // called if an expected player doesn't join our server within the arrival window private static void cancel(PlayerArrival arrival) { synchronized (arrivals) { if (arrival.hasArrived()) return; arrivals.remove(arrival.getPlayerState().getName()); arrival.setCancelled(); } Utils.info("cancelled expected arrival of '%s' from '%s'", arrival.getPlayerState().getName(), arrival.getFromGateName()); try { Server fromServer = Global.servers.get(arrival.getFromServerName()); if (fromServer == null) throw new TeleportException("from server not found"); fromServer.doCancelArrival(arrival.getEntityState(), arrival.getFromGateName(), arrival.getToGateName()); } catch (TeleportException e) { Utils.warning("unable to notify other side of cancellation of arrival of '%s' from '%s': %s", arrival.getPlayerState().getName(), arrival.getFromGateName(), e.getMessage()); } } // called when the remote side cancels a player sent from our server public static void cancel(final EntityState entityState, final String fromGateName, final String toGateName) throws TeleportException { Utils.fire(new Runnable() { @Override public void run() { Utils.warning("received a cancellation of arrival of '%s' at '%s'", entityState.getName(), toGateName); } }); } // called when a player joins our server and we're expecting their arrival public static Location arrive(Player player) throws TeleportException { PlayerArrival arrival; synchronized (arrivals) { arrival = arrivals.remove(player.getName()); if (arrival == null) return null; arrival.setArrived(); } Utils.info("detected arrival of '%s' from '%s'", player.getName(), arrival.getFromGateName()); Gate gate = Global.gates.get(arrival.getToGateName()); if (gate == null) throw new TeleportException("unknown gate '%s'", arrival.getToGateName()); if (! gate.isSameServer()) throw new TeleportException("toGate must be a local gate"); LocalGate toGate = (LocalGate)gate; // don't check permissions, pin, or funds on our side since there's nothing we could // do about it now Context ctx = new Context(player); Location location = prepareSpawnLocation(arrival.getEntityState().getPitch(), arrival.getEntityState().getYaw(), arrival.getFromGateDirection(), toGate); Entity entity = arrival.getEntityState().restore(location, player); if (entity == null) throw new TeleportException("unable to restore entity"); addGateLock(player); if (! entity.teleport(location)) throw new TeleportException("teleport to '%s' failed", toGate.getName(ctx)); ctx.sendLog(ChatColor.GOLD + "teleported to '%s'", toGate.getName(ctx)); if (filterInventory(entity, toGate)) ctx.sendLog("some inventory items where filtered by the remote gate"); // do damage for invalid pin if (toGate.getRequirePin() && (! toGate.hasPin(arrival.getPlayerState().getPin())) && (! toGate.getRequireValidPin()) && (toGate.getInvalidPinDamage() > 0)) { ctx.sendLog("invalid pin"); player.damage(toGate.getInvalidPinDamage()); } // deduct funds try { ctx.chargeFunds(toGate.getReceiveServerCost(), "debited $$ for off-server reception"); } catch (FundsException fe) { ctx.warnLog("unable to deduct travel costs: %s", fe.getMessage()); } Server fromServer = Global.servers.get(arrival.getFromServerName()); if (fromServer != null) fromServer.doConfirmArrival(arrival.getEntityState(), arrival.getFromGateName(), arrival.getToGateName()); return location; } // called after an entity has successfully been received by a remote server public static void confirm(final EntityState entityState, final String fromGateName, final String toGateName) throws TeleportException { Utils.fire(new Runnable() { @Override public void run() { Utils.info("received confirmation of arrival of '%s' at '%s'", entityState.getName(), toGateName); // if the entity isn't a player, we have to destroy it on this side if ((! entityState.isPlayer()) && (fromGateName != null)) { LocalGate gate = Global.gates.getLocalGate(fromGateName); if (gate == null) return; for (Entity entity : gate.getWorld().getEntities()) if (entity.getEntityId() == entityState.getEntityId()) { // this needs to change if we decide the handle nested entities entity.remove(); break; } } } }); } public static void sendChat(Player player, String message) { Map<Server,Set<RemoteGate>> gates = new HashMap<Server,Set<RemoteGate>>(); Location loc = player.getLocation(); Gate destGate; Server destServer; for (LocalGate gate : Global.gates.getLocalGates()) { if (gate.isInChatProximity(loc) && gate.isOpen()) { try { destGate = gate.getDestinationGate(); if (! destGate.isSameServer()) { destServer = Global.servers.get(destGate.getServerName()); if (gates.get(destServer) == null) gates.put(destServer, new HashSet<RemoteGate>()); gates.get(destServer).add((RemoteGate)destGate); } } catch (GateException e) { } } } for (Server server : gates.keySet()) { server.doRelayChat(player, message, gates.get(server)); } } public static void receiveChat(String playerName, String displayName, String serverName, String message, List<String> toGates) { Future<Map<String,Location>> future = Utils.call(new Callable<Map<String,Location>>() { @Override public Map<String,Location> call() { Map<String,Location> players = new HashMap<String,Location>(); for (Player player : Global.plugin.getServer().getOnlinePlayers()) players.put(player.getName(), player.getLocation()); return players; } }); Map<String,Location> players = null; try { players = future.get(); } catch (InterruptedException e) { } catch (ExecutionException e) {} if (players == null) return; final Set<String> playersToReceive = new HashSet<String>(); for (String gateName : toGates) { Gate gate = Global.gates.get(gateName); if (gate == null) continue; if (! gate.isSameServer()) continue; for (String player : players.keySet()) if (((LocalGate)gate).isInChatProximity(players.get(player))) playersToReceive.add(player); } if (playersToReceive.isEmpty()) return; final String msg = String.format("<%s@%s> %s", displayName, serverName, message); Utils.fire(new Runnable() { @Override public void run() { for (String playerName : playersToReceive) { Player player = Global.plugin.getServer().getPlayer(playerName); if ((player != null) && (player.isOnline())) player.sendMessage(msg); } } }); } // fromGateDirection can be null if the player is being sent directly private static Location prepareSpawnLocation(float fromPitch, float fromYaw, BlockFace fromGateDirection, LocalGate toGate) { GateBlock block = toGate.getSpawnBlocks().randomBlock(); Location location = block.getLocation().clone(); location.setX(location.getX() + 0.5); location.setY(location.getY()); location.setZ(location.getZ() + 0.5); location.setPitch(fromPitch); if (fromGateDirection == null) fromGateDirection = toGate.getDirection(); location.setYaw(block.getDetail().getSpawn().calculateYaw(fromYaw, fromGateDirection, toGate.getDirection())); Utils.prepareChunk(location); return location; } // Beyond here be dragons... and inventory filtering private static boolean checkInventory(Entity entity, LocalGate toGate) { return checkInventory(EntityState.extractState(entity), toGate); } private static boolean checkInventory(EntityState entityState, LocalGate toGate) { if (! toGate.getRequireAllowedItems()) return true; while (entityState != null) { if (entityState instanceof VehicleState) { if (! checkInventory(((VehicleState)entityState).getInventory(), toGate)) return false; entityState = ((VehicleState)entityState).getPassengerState(); } else if (entityState instanceof PlayerState) { if (! checkInventory(((PlayerState)entityState).getInventory(), toGate)) return false; if (! checkInventory(((PlayerState)entityState).getArmor(), toGate)) return false; entityState = null; } } return true; } private static boolean checkInventory(ItemStack[] stacks, LocalGate toGate) { if (stacks == null) return true; for (int i = 0; i < stacks.length; i++) { ItemStack stack = stacks[i]; if (stack == null) continue; if (filterItemStack(stack, toGate) == null) return false; } return true; } private static boolean filterInventory(Entity entity, LocalGate toGate) { boolean filtered = false; while (entity != null) { if (entity instanceof StorageMinecart) { Inventory inventory = ((StorageMinecart)entity).getInventory(); if (filterInventory(inventory, toGate)) filtered = true; } else if (entity instanceof Player) { PlayerInventory inventory = ((Player)entity).getInventory(); if (filterInventory(inventory, toGate)) filtered = true; ItemStack[] armor = inventory.getArmorContents(); if (filterInventory(armor, toGate)) filtered = true; inventory.setArmorContents(armor); } entity = entity.getPassenger(); } return filtered; } private static boolean filterInventory(Inventory inventory, LocalGate toGate) { ItemStack[] contents = inventory.getContents(); boolean filtered = filterInventory(contents, toGate); inventory.setContents(contents); return filtered; } private static boolean filterInventory(ItemStack[] stacks, LocalGate toGate) { boolean filtered = false; for (int i = 0; i < stacks.length; i++) { ItemStack newStack = filterItemStack(stacks[i], toGate); if (newStack != stacks[i]) { stacks[i] = newStack; filtered = true; } } return filtered; } private static ItemStack filterItemStack(ItemStack stack, LocalGate toGate) { if (stack == null) return null; String item = encodeItemStack(stack); String newItem = toGate.getReplaceItem(item); if ((newItem != null) && (! newItem.equals("*"))) { stack = decodeItem(stack, newItem); item = newItem; } if (toGate.hasAllowedItems()) { if (toGate.hasAllowedItem(item)) return stack; return null; } if (toGate.hasBannedItem(item)) return null; return stack; } private static String encodeItemStack(ItemStack stack) { String item = stack.getType().toString(); if (stack.getDurability() > 0) item += ":" + stack.getDurability(); return item; } private static ItemStack decodeItem(ItemStack oldItem, String item) { String[] parts = item.split(":"); Material material = Material.valueOf(parts[0]); int amount = oldItem.getAmount(); short damage = oldItem.getDurability(); if (parts.length > 1) try { damage = Short.parseShort(parts[1]); } catch (NumberFormatException e) {} return new ItemStack(material, amount, damage); } }
true
true
private static Location send(Entity entity, LocalGate fromGate, LocalGate toGate) throws TeleportException { Player player = null; String pin = null; Context ctx = null; if (entity instanceof Player) player = (Player)entity; else if (entity.getPassenger() instanceof Player) player = (Player)entity.getPassenger(); if (player != null) { pin = getPin(player); ctx = new Context(player); } if (player != null) { // check permissions if (fromGate != null) { try { ctx.requireAllPermissions("trp.use." + fromGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use this gate"); } } try { ctx.requireAllPermissions("trp.use." + toGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use the remote gate"); } // check pin if ((fromGate != null) && fromGate.getRequirePin()) { if (pin == null) throw new TeleportException("this gate requires a pin"); if (! fromGate.hasPin(pin)) throw new TeleportException("this gate rejected your pin"); } if (toGate.getRequirePin()) { if (pin == null) throw new TeleportException("remote gate requires a pin"); if ((! toGate.hasPin(pin)) && toGate.getRequireValidPin()) throw new TeleportException("remote gate rejected your pin"); } // check funds double travelCost; if (fromGate != null) { if (fromGate.isSameWorld(toGate)) travelCost = fromGate.getSendLocalCost() + toGate.getReceiveLocalCost(); else travelCost = fromGate.getSendWorldCost() + toGate.getReceiveWorldCost(); } else { if (toGate.isSameWorld(entity.getWorld())) travelCost = toGate.getReceiveLocalCost(); else travelCost = toGate.getReceiveWorldCost(); } try { ctx.requireFunds(travelCost); } catch (FundsException fe) { throw new TeleportException("gate use requires %s", iConomy.format(travelCost)); } } // check inventory if (! checkInventory(entity, toGate)) throw new TeleportException("remote gate won't some inventory items"); if ((fromGate != null) && Global.config.getBoolean("useGatePermissions", false)) { try { Permissions.requirePermissions(fromGate.getWorldName(), fromGate.getName(), true, "trp.send." + toGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("this gate is not permitted to send to the remote gate"); } try { Permissions.requirePermissions(toGate.getWorldName(), toGate.getName(), true, "trp.receive." + fromGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("the remote gate is not permitted to receive from this gate"); } } // do the teleport Location currentLoc = entity.getLocation(); Location newLocation = prepareSpawnLocation(currentLoc.getPitch(), currentLoc.getYaw(), (fromGate == null) ? null : fromGate.getDirection(), toGate); // this is necessary so minecarts don't sink into the ground // it also gives them a little push out of the gate if (! (entity instanceof Player)) newLocation.setY(newLocation.getY() + 0.5); Vector velocity = entity.getVelocity(); velocity.multiply(2); velocity.setY(0); entity.setVelocity(velocity); if (! entity.teleport(newLocation)) throw new TeleportException("teleport to '%s' failed", toGate.getFullName()); if (filterInventory(entity, toGate)) { if (player == null) Utils.info("some inventory items where filtered by the remote gate"); else ctx.sendLog("some inventory items where filtered by the remote gate"); } if (player == null) Utils.info("teleported entity '%d' to '%s'", entity.getEntityId(), toGate.getFullName()); else { ctx.sendLog(ChatColor.GOLD + "teleported to '%s'", toGate.getName(ctx)); // do damage for invalid pin if (toGate.getRequirePin() && (! toGate.hasPin(pin)) && (! toGate.getRequireValidPin()) && (toGate.getInvalidPinDamage() > 0)) { ctx.sendLog("invalid pin"); player.damage(toGate.getInvalidPinDamage()); } // deduct funds try { if (fromGate != null) { if (fromGate.isSameWorld(toGate)) { ctx.chargeFunds(fromGate.getSendLocalCost(), "debited $$ for on-world transmission"); ctx.chargeFunds(toGate.getReceiveLocalCost(), "debited $$ for on-world reception"); } else { ctx.chargeFunds(fromGate.getSendWorldCost(), "debited $$ for off-world transmission"); ctx.chargeFunds(toGate.getReceiveWorldCost(), "debited $$ for off-world reception"); } } else { if (toGate.isSameWorld(entity.getWorld())) ctx.chargeFunds(toGate.getReceiveLocalCost(), "debited $$ for on-world reception"); else ctx.chargeFunds(toGate.getReceiveWorldCost(), "debited $$ for off-world reception"); } } catch (FundsException fe) { ctx.warnLog("unable to deduct travel costs: %s", fe.getMessage()); } } return newLocation; }
private static Location send(Entity entity, LocalGate fromGate, LocalGate toGate) throws TeleportException { Player player = null; String pin = null; Context ctx = null; if (entity instanceof Player) player = (Player)entity; else if (entity.getPassenger() instanceof Player) player = (Player)entity.getPassenger(); if (player != null) { pin = getPin(player); ctx = new Context(player); } if (player != null) { // check permissions if (fromGate != null) { try { ctx.requireAllPermissions("trp.use." + fromGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use this gate"); } } try { ctx.requireAllPermissions("trp.use." + toGate.getName()); } catch (PermissionsException pe) { throw new TeleportException("not permitted to use the remote gate"); } // check pin if ((fromGate != null) && fromGate.getRequirePin()) { if (pin == null) throw new TeleportException("this gate requires a pin"); if (! fromGate.hasPin(pin)) throw new TeleportException("this gate rejected your pin"); } if (toGate.getRequirePin()) { if (pin == null) throw new TeleportException("remote gate requires a pin"); if ((! toGate.hasPin(pin)) && toGate.getRequireValidPin()) throw new TeleportException("remote gate rejected your pin"); } // check funds double travelCost; if (fromGate != null) { if (fromGate.isSameWorld(toGate)) travelCost = fromGate.getSendLocalCost() + toGate.getReceiveLocalCost(); else travelCost = fromGate.getSendWorldCost() + toGate.getReceiveWorldCost(); } else { if (toGate.isSameWorld(entity.getWorld())) travelCost = toGate.getReceiveLocalCost(); else travelCost = toGate.getReceiveWorldCost(); } try { ctx.requireFunds(travelCost); } catch (FundsException fe) { throw new TeleportException("gate use requires %s", iConomy.format(travelCost)); } } // check inventory if (! checkInventory(entity, toGate)) throw new TeleportException("remote gate won't allow some inventory items"); if ((fromGate != null) && Global.config.getBoolean("useGatePermissions", false)) { try { Permissions.requirePermissions(fromGate.getWorldName(), fromGate.getName(), true, "trp.send." + toGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("this gate is not permitted to send to the remote gate"); } try { Permissions.requirePermissions(toGate.getWorldName(), toGate.getName(), true, "trp.receive." + fromGate.getGlobalName()); } catch (PermissionsException pe) { throw new TeleportException("the remote gate is not permitted to receive from this gate"); } } // do the teleport Location currentLoc = entity.getLocation(); Location newLocation = prepareSpawnLocation(currentLoc.getPitch(), currentLoc.getYaw(), (fromGate == null) ? null : fromGate.getDirection(), toGate); // this is necessary so minecarts don't sink into the ground // it also gives them a little push out of the gate if (! (entity instanceof Player)) newLocation.setY(newLocation.getY() + 0.5); Vector velocity = entity.getVelocity(); velocity.multiply(2); velocity.setY(0); entity.setVelocity(velocity); if (! entity.teleport(newLocation)) throw new TeleportException("teleport to '%s' failed", toGate.getFullName()); if (filterInventory(entity, toGate)) { if (player == null) Utils.info("some inventory items where filtered by the remote gate"); else ctx.sendLog("some inventory items where filtered by the remote gate"); } if (player == null) Utils.info("teleported entity '%d' to '%s'", entity.getEntityId(), toGate.getFullName()); else { ctx.sendLog(ChatColor.GOLD + "teleported to '%s'", toGate.getName(ctx)); // do damage for invalid pin if (toGate.getRequirePin() && (! toGate.hasPin(pin)) && (! toGate.getRequireValidPin()) && (toGate.getInvalidPinDamage() > 0)) { ctx.sendLog("invalid pin"); player.damage(toGate.getInvalidPinDamage()); } // deduct funds try { if (fromGate != null) { if (fromGate.isSameWorld(toGate)) { ctx.chargeFunds(fromGate.getSendLocalCost(), "debited $$ for on-world transmission"); ctx.chargeFunds(toGate.getReceiveLocalCost(), "debited $$ for on-world reception"); } else { ctx.chargeFunds(fromGate.getSendWorldCost(), "debited $$ for off-world transmission"); ctx.chargeFunds(toGate.getReceiveWorldCost(), "debited $$ for off-world reception"); } } else { if (toGate.isSameWorld(entity.getWorld())) ctx.chargeFunds(toGate.getReceiveLocalCost(), "debited $$ for on-world reception"); else ctx.chargeFunds(toGate.getReceiveWorldCost(), "debited $$ for off-world reception"); } } catch (FundsException fe) { ctx.warnLog("unable to deduct travel costs: %s", fe.getMessage()); } } return newLocation; }
diff --git a/src/net/amunak/bukkit/flywithfood/FlyWithFoodEventListener.java b/src/net/amunak/bukkit/flywithfood/FlyWithFoodEventListener.java index bd29a61..bddf2ab 100644 --- a/src/net/amunak/bukkit/flywithfood/FlyWithFoodEventListener.java +++ b/src/net/amunak/bukkit/flywithfood/FlyWithFoodEventListener.java @@ -1,144 +1,144 @@ package net.amunak.bukkit.flywithfood; /** * Copyright 2013 Jiří Barouš * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerToggleFlightEvent; class FlyWithFoodEventListener implements Listener { protected FlyWithFood plugin; private Log log; public FlyWithFoodEventListener(FlyWithFood p) { this.plugin = p; this.log = FlyWithFood.log; } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerJoin(PlayerJoinEvent e) { this.plugin.flyablePlayers.put(e.getPlayer(), new FlyablePlayerRecord()); this.plugin.checkFlyingCapability(e.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerChangedWorld(PlayerChangedWorldEvent e) { this.plugin.checkFlyingCapability(e.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerRespawn(PlayerRespawnEvent e) { this.plugin.checkFlyingCapability(e.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerGameModeChange(PlayerGameModeChangeEvent e) { this.plugin.checkFlyingCapability(e.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerWorldChange(PlayerChangedWorldEvent e) { this.plugin.checkFlyingCapability(e.getPlayer()); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerToggleFlight(PlayerToggleFlightEvent e) { this.plugin.checkFlyingCapability(e.getPlayer()); if (e.isFlying() && e.getPlayer().getGameMode().equals(GameMode.SURVIVAL)) { if (this.plugin.config.getBoolean("options.drainHunger.enable") && !e.getPlayer().hasPermission("fly.nohunger") && e.getPlayer().getFoodLevel() < this.plugin.hungerMin) { e.setCancelled(true); e.getPlayer().sendMessage(ChatColor.BLUE + "Your food level is under " + ChatColor.DARK_PURPLE + ((double) this.plugin.hungerMin / 2) + ChatColor.BLUE + ". You are too weak to fly."); } if (!e.getPlayer().getAllowFlight()) { e.setCancelled(true); } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onFoodLevelChange(FoodLevelChangeEvent e) { log.fine(e.getEntityType().toString() + " thrown foodlevelchange"); if (e.getEntity() instanceof Player) { this.plugin.foodLevelCheck((Player) e.getEntity(), e.getFoodLevel()); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) public void onPlayerItemConsume(PlayerItemConsumeEvent e) { log.fine("itemConsume fired"); Player p = e.getPlayer(); if (!e.isCancelled() && p.getGameMode().equals(GameMode.SURVIVAL) && this.plugin.config.getBoolean("options.limitFoodConsumption.enable") && p.isFlying() && !p.hasPermission("fly.eatanything") && this.plugin.listOfFood.contains(e.getItem().getType().toString())) { if (this.plugin.maxFoodEaten == 0) { p.sendMessage(ChatColor.BLUE + "Sorry, you cannot eat while flying."); e.setCancelled(true); } else { if (this.plugin.listOfForbiddenFood.contains(e.getItem().getType().toString())) { p.sendMessage(ChatColor.BLUE + "Sorry, you cannot consume this while flying."); e.setCancelled(true); } else if (this.plugin.maxFoodEaten > 0) { if (this.plugin.flyablePlayers.get(p).foodEaten < this.plugin.maxFoodEaten) { this.plugin.flyablePlayers.get(p).foodEaten += 1; p.sendMessage(ChatColor.BLUE + "You can eat " + ChatColor.DARK_PURPLE + (this.plugin.maxFoodEaten - this.plugin.flyablePlayers.get(p).foodEaten) + ChatColor.BLUE + " more food during this flight."); } else { p.sendMessage(ChatColor.BLUE + "You have already consumed " + ChatColor.DARK_PURPLE + this.plugin.maxFoodEaten - + ChatColor.BLUE + "piece" + (this.plugin.maxFoodEaten > 1 ? "s" : "") + + ChatColor.BLUE + " piece" + (this.plugin.maxFoodEaten > 1 ? "s" : "") + " of food during this flight. You can eat no more."); e.setCancelled(true); } } } } log.fine("itemConsume ended for " + p.getName() + " with cancelled: " + e.isCancelled()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerMove(PlayerMoveEvent e) { //Reset eaten food when grounded if (this.plugin.config.getBoolean("options.limitFoodConsumption.enable") && !e.getPlayer().isFlying() && e.getPlayer().isOnGround()) { this.plugin.flyablePlayers.get(e.getPlayer()).foodEaten = 0; } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent e) { this.plugin.flyablePlayers.remove(e.getPlayer()); } }
true
true
public void onPlayerItemConsume(PlayerItemConsumeEvent e) { log.fine("itemConsume fired"); Player p = e.getPlayer(); if (!e.isCancelled() && p.getGameMode().equals(GameMode.SURVIVAL) && this.plugin.config.getBoolean("options.limitFoodConsumption.enable") && p.isFlying() && !p.hasPermission("fly.eatanything") && this.plugin.listOfFood.contains(e.getItem().getType().toString())) { if (this.plugin.maxFoodEaten == 0) { p.sendMessage(ChatColor.BLUE + "Sorry, you cannot eat while flying."); e.setCancelled(true); } else { if (this.plugin.listOfForbiddenFood.contains(e.getItem().getType().toString())) { p.sendMessage(ChatColor.BLUE + "Sorry, you cannot consume this while flying."); e.setCancelled(true); } else if (this.plugin.maxFoodEaten > 0) { if (this.plugin.flyablePlayers.get(p).foodEaten < this.plugin.maxFoodEaten) { this.plugin.flyablePlayers.get(p).foodEaten += 1; p.sendMessage(ChatColor.BLUE + "You can eat " + ChatColor.DARK_PURPLE + (this.plugin.maxFoodEaten - this.plugin.flyablePlayers.get(p).foodEaten) + ChatColor.BLUE + " more food during this flight."); } else { p.sendMessage(ChatColor.BLUE + "You have already consumed " + ChatColor.DARK_PURPLE + this.plugin.maxFoodEaten + ChatColor.BLUE + "piece" + (this.plugin.maxFoodEaten > 1 ? "s" : "") + " of food during this flight. You can eat no more."); e.setCancelled(true); } } } } log.fine("itemConsume ended for " + p.getName() + " with cancelled: " + e.isCancelled()); }
public void onPlayerItemConsume(PlayerItemConsumeEvent e) { log.fine("itemConsume fired"); Player p = e.getPlayer(); if (!e.isCancelled() && p.getGameMode().equals(GameMode.SURVIVAL) && this.plugin.config.getBoolean("options.limitFoodConsumption.enable") && p.isFlying() && !p.hasPermission("fly.eatanything") && this.plugin.listOfFood.contains(e.getItem().getType().toString())) { if (this.plugin.maxFoodEaten == 0) { p.sendMessage(ChatColor.BLUE + "Sorry, you cannot eat while flying."); e.setCancelled(true); } else { if (this.plugin.listOfForbiddenFood.contains(e.getItem().getType().toString())) { p.sendMessage(ChatColor.BLUE + "Sorry, you cannot consume this while flying."); e.setCancelled(true); } else if (this.plugin.maxFoodEaten > 0) { if (this.plugin.flyablePlayers.get(p).foodEaten < this.plugin.maxFoodEaten) { this.plugin.flyablePlayers.get(p).foodEaten += 1; p.sendMessage(ChatColor.BLUE + "You can eat " + ChatColor.DARK_PURPLE + (this.plugin.maxFoodEaten - this.plugin.flyablePlayers.get(p).foodEaten) + ChatColor.BLUE + " more food during this flight."); } else { p.sendMessage(ChatColor.BLUE + "You have already consumed " + ChatColor.DARK_PURPLE + this.plugin.maxFoodEaten + ChatColor.BLUE + " piece" + (this.plugin.maxFoodEaten > 1 ? "s" : "") + " of food during this flight. You can eat no more."); e.setCancelled(true); } } } } log.fine("itemConsume ended for " + p.getName() + " with cancelled: " + e.isCancelled()); }
diff --git a/core/src/com/google/zxing/common/reedsolomon/GF256.java b/core/src/com/google/zxing/common/reedsolomon/GF256.java index f36caa75..5d7eb9b0 100644 --- a/core/src/com/google/zxing/common/reedsolomon/GF256.java +++ b/core/src/com/google/zxing/common/reedsolomon/GF256.java @@ -1,142 +1,142 @@ /* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.common.reedsolomon; /** * <p>This class contains utility methods for performing mathematical operations over * the Galois Field GF(256). Operations use a given primitive polynomial in calculations.</p> * * <p>Throughout this package, elements of GF(256) are represented as an <code>int</code> * for convenience and speed (but at the cost of memory). * Only the bottom 8 bits are really used.</p> * * @author [email protected] (Sean Owen) */ public final class GF256 { public static final GF256 QR_CODE_FIELD = new GF256(0x011D); // x^8 + x^4 + x^3 + x^2 + 1 public static final GF256 DATA_MATRIX_FIELD = new GF256(0x012D); // x^8 + x^5 + x^3 + x^2 + 1 private final int[] exp_table; private final int[] log_table; private final GF256Poly zero; private final GF256Poly one; /** * Create a representation of GF(256) using the given primitive polynomial. * * @param primitive irreducible polynomial whose coefficients are represented by * the bits of an int, where the least-significant bit represents the constant * coefficient */ private GF256(int primitive) { exp_table = new int[256]; log_table = new int[256]; int x = 1; for (int i = 0; i < 256; i++) { exp_table[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= 0x100) { x ^= primitive; } } for (int i = 0; i < 255; i++) { log_table[exp_table[i]] = i; } - // log[0] == 0 but this should never be used + // log_table[0] == 0 but this should never be used zero = new GF256Poly(this, new int[]{0}); one = new GF256Poly(this, new int[]{1}); } GF256Poly getZero() { return zero; } GF256Poly getOne() { return one; } /** * @return the monomial representing coefficient * x^degree */ GF256Poly buildMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return zero; } int[] coefficients = new int[degree + 1]; coefficients[0] = coefficient; return new GF256Poly(this, coefficients); } /** * Implements both addition and subtraction -- they are the same in GF(256). * * @return sum/difference of a and b */ static int addOrSubtract(int a, int b) { return a ^ b; } /** * @return 2 to the power of a in GF(256) */ int exp(int a) { return exp_table[a]; } /** * @return base 2 log of a in GF(256) */ int log(int a) { if (a == 0) { throw new IllegalArgumentException(); } return log_table[a]; } /** * @return multiplicative inverse of a */ int inverse(int a) { if (a == 0) { throw new ArithmeticException(); } return exp_table[255 - log_table[a]]; } /** * @param a * @param b * @return product of a and b in GF(256) */ int multiply(int a, int b) { if (a == 0 || b == 0) { return 0; } if (a == 1) { return b; } if (b == 1) { return a; } return exp_table[(log_table[a] + log_table[b]) % 255]; } }
true
true
private GF256(int primitive) { exp_table = new int[256]; log_table = new int[256]; int x = 1; for (int i = 0; i < 256; i++) { exp_table[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= 0x100) { x ^= primitive; } } for (int i = 0; i < 255; i++) { log_table[exp_table[i]] = i; } // log[0] == 0 but this should never be used zero = new GF256Poly(this, new int[]{0}); one = new GF256Poly(this, new int[]{1}); }
private GF256(int primitive) { exp_table = new int[256]; log_table = new int[256]; int x = 1; for (int i = 0; i < 256; i++) { exp_table[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= 0x100) { x ^= primitive; } } for (int i = 0; i < 255; i++) { log_table[exp_table[i]] = i; } // log_table[0] == 0 but this should never be used zero = new GF256Poly(this, new int[]{0}); one = new GF256Poly(this, new int[]{1}); }
diff --git a/src/edu/ames/frc/robot/MotorControl.java b/src/edu/ames/frc/robot/MotorControl.java index a53bbdd..73e7c2a 100644 --- a/src/edu/ames/frc/robot/MotorControl.java +++ b/src/edu/ames/frc/robot/MotorControl.java @@ -1,28 +1,28 @@ /* Currently managed by Tarun Sunkaraneni, and Ben Rose * This class manages all motor writing and managment. May need to deal with complex Gyro * input. */ package edu.ames.frc.robot; public class MotorControl { /* This converts the direction we want to go (from 0 to 1, relative to the robot's base) * and speed (from 0 to 1) directly to values for the three omni-wheeled motors. */ double[] convertHeadingToMotorCommands(double direction, double speed) { double[] motorvalue = new double[3]; /* so, we'll define the direction we want to go as "forward". There are * 3 different points where only two motors will need to run (if the direction * is parallel to a motor's axle). */ // 0 is what we define as the "front" motor - what we measure our heading angle from, // 1 is the motor one position clockwise from that, and // 2 is the motor one position counter-clockwise from 0. - motorvalue[0] = speed * (Math.sin(direction) / 3); - motorvalue[1] = speed * (Math.sin(direction - (2 * Math.PI / 3)) / 3); - motorvalue[2] = speed * (Math.sin(direction + (2 * Math.PI)) / 3); + motorvalue[0] = speed * Math.sin(direction); + motorvalue[1] = speed * Math.sin(direction - (2 * Math.PI / 3)); + motorvalue[2] = speed * Math.sin(direction + (2 * Math.PI)) / 3; return motorvalue; } }
true
true
double[] convertHeadingToMotorCommands(double direction, double speed) { double[] motorvalue = new double[3]; /* so, we'll define the direction we want to go as "forward". There are * 3 different points where only two motors will need to run (if the direction * is parallel to a motor's axle). */ // 0 is what we define as the "front" motor - what we measure our heading angle from, // 1 is the motor one position clockwise from that, and // 2 is the motor one position counter-clockwise from 0. motorvalue[0] = speed * (Math.sin(direction) / 3); motorvalue[1] = speed * (Math.sin(direction - (2 * Math.PI / 3)) / 3); motorvalue[2] = speed * (Math.sin(direction + (2 * Math.PI)) / 3); return motorvalue; }
double[] convertHeadingToMotorCommands(double direction, double speed) { double[] motorvalue = new double[3]; /* so, we'll define the direction we want to go as "forward". There are * 3 different points where only two motors will need to run (if the direction * is parallel to a motor's axle). */ // 0 is what we define as the "front" motor - what we measure our heading angle from, // 1 is the motor one position clockwise from that, and // 2 is the motor one position counter-clockwise from 0. motorvalue[0] = speed * Math.sin(direction); motorvalue[1] = speed * Math.sin(direction - (2 * Math.PI / 3)); motorvalue[2] = speed * Math.sin(direction + (2 * Math.PI)) / 3; return motorvalue; }
diff --git a/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/internal/builder/TestAll.java b/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/internal/builder/TestAll.java index 40ad5c88..0dadc886 100644 --- a/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/internal/builder/TestAll.java +++ b/editor/tools/plugins/com.google.dart.tools.core_test/src/com/google/dart/tools/core/internal/builder/TestAll.java @@ -1,28 +1,28 @@ /* * Copyright (c) 2011, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.dart.tools.core.internal.builder; import junit.framework.Test; import junit.framework.TestSuite; public class TestAll { public static Test suite() { TestSuite suite = new TestSuite("Tests in " + TestAll.class.getPackage().getName()); suite.addTestSuite(CachingArtifactProviderTest.class); // suite.addTestSuite(DartBuilderTest.class); suite.addTestSuite(LocalArtifactProviderTest.class); - suite.addTestSuite(RootArtifactProviderTest.class); +// suite.addTestSuite(RootArtifactProviderTest.class); return suite; } }
true
true
public static Test suite() { TestSuite suite = new TestSuite("Tests in " + TestAll.class.getPackage().getName()); suite.addTestSuite(CachingArtifactProviderTest.class); // suite.addTestSuite(DartBuilderTest.class); suite.addTestSuite(LocalArtifactProviderTest.class); suite.addTestSuite(RootArtifactProviderTest.class); return suite; }
public static Test suite() { TestSuite suite = new TestSuite("Tests in " + TestAll.class.getPackage().getName()); suite.addTestSuite(CachingArtifactProviderTest.class); // suite.addTestSuite(DartBuilderTest.class); suite.addTestSuite(LocalArtifactProviderTest.class); // suite.addTestSuite(RootArtifactProviderTest.class); return suite; }
diff --git a/src/pl/cougy/MonteCarlo/Test.java b/src/pl/cougy/MonteCarlo/Test.java index c4bd933..17c1f77 100644 --- a/src/pl/cougy/MonteCarlo/Test.java +++ b/src/pl/cougy/MonteCarlo/Test.java @@ -1,38 +1,39 @@ package pl.cougy.MonteCarlo; import java.util.ArrayList; import java.util.Scanner; public class Test { /** * @param args */ public static void main(String[] args) { @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); System.out.println("Please enter your expresion to be integrated with MonteCarlo method"); - System.out.println("you can use standard notation for example (x*x+y*y) :"); + System.out.println("you can use standard notation for example (a*a+b*b), remember to start " + + "naming your variables from a then b then c etc... :"); String expression = scanner.next(); System.out.println("How many variables have you entered : "); Integer numberOfVariables = scanner.nextInt(); ArrayList <Double> min = new ArrayList<>(); ArrayList <Double> max = new ArrayList<>(); for(int i=0; i < numberOfVariables.intValue();i++) { System.out.print("Please enter " + Integer.toString(i+1) + " interval [a"+ Integer.toString(i+1) +";b" + Integer.toString(i+1) + "]: "); min.add(scanner.nextDouble()); max.add(scanner.nextDouble()); } MonteCarlo test = new MonteCarlo(expression, 1000000, new Intervals(min,max)).generateValues(); System.out.println("Integral " + Double.toString(test.getIntegral())); System.out.println("Error " + Double.toString(test.getError())); } }
true
true
public static void main(String[] args) { @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); System.out.println("Please enter your expresion to be integrated with MonteCarlo method"); System.out.println("you can use standard notation for example (x*x+y*y) :"); String expression = scanner.next(); System.out.println("How many variables have you entered : "); Integer numberOfVariables = scanner.nextInt(); ArrayList <Double> min = new ArrayList<>(); ArrayList <Double> max = new ArrayList<>(); for(int i=0; i < numberOfVariables.intValue();i++) { System.out.print("Please enter " + Integer.toString(i+1) + " interval [a"+ Integer.toString(i+1) +";b" + Integer.toString(i+1) + "]: "); min.add(scanner.nextDouble()); max.add(scanner.nextDouble()); } MonteCarlo test = new MonteCarlo(expression, 1000000, new Intervals(min,max)).generateValues(); System.out.println("Integral " + Double.toString(test.getIntegral())); System.out.println("Error " + Double.toString(test.getError())); }
public static void main(String[] args) { @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); System.out.println("Please enter your expresion to be integrated with MonteCarlo method"); System.out.println("you can use standard notation for example (a*a+b*b), remember to start " + "naming your variables from a then b then c etc... :"); String expression = scanner.next(); System.out.println("How many variables have you entered : "); Integer numberOfVariables = scanner.nextInt(); ArrayList <Double> min = new ArrayList<>(); ArrayList <Double> max = new ArrayList<>(); for(int i=0; i < numberOfVariables.intValue();i++) { System.out.print("Please enter " + Integer.toString(i+1) + " interval [a"+ Integer.toString(i+1) +";b" + Integer.toString(i+1) + "]: "); min.add(scanner.nextDouble()); max.add(scanner.nextDouble()); } MonteCarlo test = new MonteCarlo(expression, 1000000, new Intervals(min,max)).generateValues(); System.out.println("Integral " + Double.toString(test.getIntegral())); System.out.println("Error " + Double.toString(test.getError())); }
diff --git a/src/main/java/org/eweb4j/component/dwz/menu/navmenu/SearchNavMenuAction.java b/src/main/java/org/eweb4j/component/dwz/menu/navmenu/SearchNavMenuAction.java index d8a4320..6a17582 100644 --- a/src/main/java/org/eweb4j/component/dwz/menu/navmenu/SearchNavMenuAction.java +++ b/src/main/java/org/eweb4j/component/dwz/menu/navmenu/SearchNavMenuAction.java @@ -1,37 +1,38 @@ package org.eweb4j.component.dwz.menu.navmenu; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.eweb4j.component.dwz.menu.MenuException; import org.eweb4j.mvc.action.annotation.Result; @Path("${NavMenuConstant.MODEL_NAME}") public class SearchNavMenuAction extends NavMenuBaseAction { @GET @POST @Path("/search") @Result("${NavMenuConstant.PAGING_ACTION_RESULT}") public String doSearchAndPaging(Map model) { try { model.put("listPage", service.getSearchResult(keyword, pageNum, numPerPage)); } catch (MenuException e) { + e.printStackTrace(); return dwz.getFailedJson(e.getMessage()).toString(); } return "success"; } @GET @POST @Path("/lookupSearch") @Result("${NavMenuConstant.LOOKUP_ACTION_RESULT}") public String doLookupSearch(Map model) { return this.doSearchAndPaging(model); } }
true
true
public String doSearchAndPaging(Map model) { try { model.put("listPage", service.getSearchResult(keyword, pageNum, numPerPage)); } catch (MenuException e) { return dwz.getFailedJson(e.getMessage()).toString(); } return "success"; }
public String doSearchAndPaging(Map model) { try { model.put("listPage", service.getSearchResult(keyword, pageNum, numPerPage)); } catch (MenuException e) { e.printStackTrace(); return dwz.getFailedJson(e.getMessage()).toString(); } return "success"; }
diff --git a/src/com/librelio/base/BaseActivity.java b/src/com/librelio/base/BaseActivity.java index bd0538f..a6dbd40 100644 --- a/src/com/librelio/base/BaseActivity.java +++ b/src/com/librelio/base/BaseActivity.java @@ -1,320 +1,322 @@ package com.librelio.base; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import java.util.Random; import org.netcook.android.tools.CrashCatcherActivity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Environment; import android.os.Handler; import android.util.Log; import com.librelio.LibrelioApplication; import com.librelio.lib.utils.BillingService.RequestPurchase; import com.librelio.lib.utils.BillingService.RestoreTransactions; import com.librelio.lib.utils.Consts.PurchaseState; import com.librelio.lib.utils.Consts.ResponseCode; import com.librelio.lib.utils.PurchaseObserver; import com.niveales.wind.R; public class BaseActivity extends CrashCatcherActivity implements IBaseContext { private static final String TAG = "BaseActivity"; public static final String BROADCAST_ACTION = "com.librelio.lib.service.broadcast"; public static final String TEST_INIT_COMPLETE = "TEST_INIT_COMPLETE"; protected static final int CONNECTION_ALERT = 1; protected static final int SERVER_ALERT = 2; protected static final int DOWNLOAD_ALERT = 3; protected static final int IO_EXEPTION = 4; private SharedPreferences sharedPreferences; /** * The receiver for stop progress in action bar */ protected BroadcastReceiver updateProgressStop = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setProgressBarIndeterminateVisibility(false); } }; /** * A {@link PurchaseObserver} is used to get callbacks when Android Market * sends messages to this application so that we can update the UI. */ public class LibrelioPurchaseObserver extends PurchaseObserver { public LibrelioPurchaseObserver(Handler handler) { super(BaseActivity.this, handler); } @Override public void onBillingSupported(boolean supported, String type) { /*if (Consts.DEBUG) { Log.i(TAG, "supported: " + supported); } if (type == null || type.equals(Consts.ITEM_TYPE_INAPP)) { if (supported) { restoreDatabase(); // mBuyButton.setEnabled(true); // mEditPayloadButton.setEnabled(true); } else { showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID); } } else if (!type.equals(Consts.ITEM_TYPE_SUBSCRIPTION)) { showDialog(DIALOG_SUBSCRIPTIONS_NOT_SUPPORTED_ID); }*/ } @Override public void onPurchaseStateChange(PurchaseState purchaseState, String itemId, int quantity, long purchaseTime, String developerPayload) { /*if (Consts.DEBUG) { Log.i(TAG, "onPurchaseStateChange() itemId: " + itemId + " " + purchaseState); } if (purchaseState == PurchaseState.PURCHASED) { mOwnedItems.add(itemId); // If this is a subscription, then enable the "Edit // Subscriptions" button. for (CatalogEntry e : CATALOG) { if (e.sku.equals(itemId) && e.managed.equals(Managed.SUBSCRIPTION)) { // TODO // update subscription MainMagazineActivity.this.onSubscribe(e.sku); } } } // mCatalogAdapter.setOwnedItems(mOwnedItems); cloud.setIssuePurchiseState(mOwnedItems); mOwnedItemsCursor.requery(); mIssueListGrid.invalidateViews();*/ } @Override public void onRequestPurchaseResponse(RequestPurchase request, ResponseCode responseCode) { /*if (Consts.DEBUG) { Log.d(TAG, request.mProductId + ": " + responseCode); } if (responseCode == ResponseCode.RESULT_OK) { if (Consts.DEBUG) { Log.i(TAG, "purchase was successfully sent to server"); } } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) { if (Consts.DEBUG) { Log.i(TAG, "user canceled purchase"); } } else { if (Consts.DEBUG) { Log.i(TAG, "purchase failed"); } }*/ } @Override public void onRestoreTransactionsResponse(RestoreTransactions request, ResponseCode responseCode) { /*if (responseCode == ResponseCode.RESULT_OK) { if (Consts.DEBUG) { Log.d(TAG, "completed RestoreTransactions request"); } // Update the shared preferences so that we don't perform // a RestoreTransactions again. SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(DB_INITIALIZED, true); edit.commit(); } else { if (Consts.DEBUG) { Log.d(TAG, "RestoreTransactions error: " + responseCode); } }*/ } } @Override public String getInternalPath() { return getDir("librelio", MODE_PRIVATE).getAbsolutePath() + "/"; } @Override public String getExternalPath() { return Environment.getExternalStorageDirectory() + "/librelio/"; } @Override public String getStoragePath(){ if (USE_INTERNAL_STORAGE) { return getInternalPath(); } else { return getExternalPath(); } } @Override public String getVideoTempPath() { //return getExternalPath() + ".f" + new Random().nextLong() + "-video.mp4"; return getExternalPath() + ".video.mp4"; } /** * Replaces the language and/or country of the device into the given string. * The pattern "%lang%" will be replaced by the device's language code and * the pattern "%region%" will be replaced with the device's country code. * * @param str * the string to replace the language/country within * @return a string containing the local language and region codes */ protected String replaceLanguageAndRegion(String str) { // Substitute language and or region if present in string if (str.contains("%lang%") || str.contains("%region%")) { Locale locale = Locale.getDefault(); str = str.replace("%lang%", locale.getLanguage().toLowerCase(Locale.getDefault())); str = str.replace("%region%", locale.getCountry().toLowerCase(Locale.getDefault())); } return str; } protected int getUpdatePeriod() { return 1800000; } @Override protected String getRecipient() { return "[email protected]"; } @Override protected Class<?> getStartActivityAfterCrached() { return BaseActivity.class; } @Override public boolean isOnline() { return LibrelioApplication.thereIsConnection(getBaseContext()); } @Override public SharedPreferences getPreferences() { if (null == sharedPreferences) { sharedPreferences = getSharedPreferences(LIBRELIO_SHARED_PREFERENCES, MODE_PRIVATE); } return sharedPreferences; } /** * Creates storage directories if necessary */ protected void initStorage(String... folders) { File f = new File(getStoragePath()); if (!f.exists()) { Log.d(TAG, getStoragePath() + " was create"); f.mkdirs(); } f = new File(getExternalPath()); if (!f.exists()) { Log.d(TAG, getExternalPath() + " was create"); f.mkdirs(); } if (null != folders && folders.length != 0) { for (String folder : folders) { File dir = new File(getStoragePath() + folder); if (!dir.exists()) { dir.mkdir(); } } } } /** * Copy files from android assets directory * * @param src * the source target * @param dst * the destination target */ protected int copyFromAssets(String src, String dst){ int count = -1; Log.d(TAG, "copyFromAssets " + src + " => " + dst); try { InputStream input = getAssets().open(src); OutputStream output = new FileOutputStream(dst); byte data[] = new byte[1024]; while ((count = input.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (IOException e) { Log.e(TAG, "copyFromAssets failed", e); } return count; } protected void enableRotation(boolean isEnable) { android.provider.Settings.System.putInt( getContentResolver(), android.provider.Settings.System.ACCELEROMETER_ROTATION, isEnable ? 1 : 0); } protected boolean hasTestMagazine() { return getResources().getBoolean(R.bool.enable_test_magazine); } protected void showAlertDialog(int id){ int msg_id = 0; final int fId = id; switch (id) { case CONNECTION_ALERT:{ msg_id = R.string.connection_failed; break; } case SERVER_ALERT:{ msg_id = R.string.server_error; break; } case DOWNLOAD_ALERT:{ msg_id = R.string.download_failed_please_check_your_connection; + break; } case IO_EXEPTION:{ msg_id = R.string.no_space_on_device; + break; } } String message = getResources().getString(msg_id); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(fId!=IO_EXEPTION){ finish(); } } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
false
true
protected void showAlertDialog(int id){ int msg_id = 0; final int fId = id; switch (id) { case CONNECTION_ALERT:{ msg_id = R.string.connection_failed; break; } case SERVER_ALERT:{ msg_id = R.string.server_error; break; } case DOWNLOAD_ALERT:{ msg_id = R.string.download_failed_please_check_your_connection; } case IO_EXEPTION:{ msg_id = R.string.no_space_on_device; } } String message = getResources().getString(msg_id); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(fId!=IO_EXEPTION){ finish(); } } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); }
protected void showAlertDialog(int id){ int msg_id = 0; final int fId = id; switch (id) { case CONNECTION_ALERT:{ msg_id = R.string.connection_failed; break; } case SERVER_ALERT:{ msg_id = R.string.server_error; break; } case DOWNLOAD_ALERT:{ msg_id = R.string.download_failed_please_check_your_connection; break; } case IO_EXEPTION:{ msg_id = R.string.no_space_on_device; break; } } String message = getResources().getString(msg_id); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(fId!=IO_EXEPTION){ finish(); } } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); }
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java index b224eeb1..fd826bdf 100644 --- a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java +++ b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java @@ -1,666 +1,666 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: Feb 17, 2008 */ package uk.me.parabola.mkgmap.osmstyle; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.imgfmt.app.CoordNode; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.general.AreaClipper; import uk.me.parabola.mkgmap.general.Clipper; import uk.me.parabola.mkgmap.general.LineAdder; import uk.me.parabola.mkgmap.general.LineClipper; import uk.me.parabola.mkgmap.general.MapCollector; import uk.me.parabola.mkgmap.general.MapElement; import uk.me.parabola.mkgmap.general.MapLine; import uk.me.parabola.mkgmap.general.MapPoint; import uk.me.parabola.mkgmap.general.MapRoad; import uk.me.parabola.mkgmap.general.MapShape; import uk.me.parabola.mkgmap.general.RoadNetwork; import uk.me.parabola.mkgmap.reader.osm.Element; import uk.me.parabola.mkgmap.reader.osm.GType; import uk.me.parabola.mkgmap.reader.osm.Node; import uk.me.parabola.mkgmap.reader.osm.OsmConverter; import uk.me.parabola.mkgmap.reader.osm.Relation; import uk.me.parabola.mkgmap.reader.osm.Rule; import uk.me.parabola.mkgmap.reader.osm.Style; import uk.me.parabola.mkgmap.reader.osm.Way; /** * Convert from OSM to the mkgmap intermediate format using a style. * A style is a collection of files that describe the mappings to be used * when converting. * * @author Steve Ratcliffe */ public class StyledConverter implements OsmConverter { private static final Logger log = Logger.getLogger(StyledConverter.class); private final String[] nameTagList; private final MapCollector collector; private Clipper clipper = Clipper.NULL_CLIPPER; private Area bbox = null; private Set<Coord> boundaryCoords = new HashSet<Coord>(); private int roadId; private final int MAX_NODES_IN_WAY = 16; private final double MIN_DISTANCE_BETWEEN_NODES = 5.5; // nodeIdMap maps a Coord into a nodeId private final Map<Coord, Integer> nodeIdMap = new HashMap<Coord, Integer>(); private int nextNodeId; private final Rule wayRules; private final Rule nodeRules; private final Rule relationRules; private LineAdder lineAdder = new LineAdder() { public void add(MapLine element) { if (element instanceof MapRoad) collector.addRoad((MapRoad) element); else collector.addLine(element); } }; public StyledConverter(Style style, MapCollector collector) { this.collector = collector; nameTagList = style.getNameTagList(); wayRules = style.getWayRules(); nodeRules = style.getNodeRules(); relationRules = style.getRelationRules(); LineAdder overlayAdder = style.getOverlays(lineAdder); if (overlayAdder != null) lineAdder = overlayAdder; } /** * This takes the way and works out what kind of map feature it is and makes * the relevant call to the mapper callback. * <p> * As a few examples we might want to check for the 'highway' tag, work out * if it is an area of a park etc. * * @param way The OSM way. */ public void convertWay(Way way) { if (way.getPoints().size() < 2) return; preConvertRules(way); GType foundType = wayRules.resolveType(way); if (foundType == null) return; postConvertRules(way, foundType); if (foundType.getFeatureKind() == GType.POLYLINE) { if(foundType.isRoad()) addRoad(way, foundType); else addLine(way, foundType); } else addShape(way, foundType); } /** * Takes a node (that has its own identity) and converts it from the OSM * type to the Garmin map type. * * @param node The node to convert. */ public void convertNode(Node node) { preConvertRules(node); GType foundType = nodeRules.resolveType(node); if (foundType == null) return; // If the node does not have a name, then set the name from this // type rule. log.debug("node name", node.getName()); if (node.getName() == null) { node.setName(foundType.getDefaultName()); log.debug("after set", node.getName()); } postConvertRules(node, foundType); addPoint(node, foundType); } /** * Rules to run before converting the element. */ private void preConvertRules(Element el) { if (nameTagList == null) return; for (String t : nameTagList) { String val = el.getTag(t); if (val != null) { el.addTag("name", val); break; } } } /** * Built in rules to run after converting the element. */ private void postConvertRules(Element el, GType type) { // Set the name from the 'name' tag or failing that from // the default_name. el.setName(el.getTag("name")); if (el.getName() == null) el.setName(type.getDefaultName()); } /** * Set the bounding box for this map. This should be set before any other * elements are converted if you want to use it. All elements that are added * are clipped to this box, new points are added as needed at the boundry. * * If a node or a way falls completely outside the boundry then it would be * ommited. This would not normally happen in the way this option is typically * used however. * * @param bbox The bounding area. */ public void setBoundingBox(Area bbox) { this.clipper = new AreaClipper(bbox); this.bbox = bbox; } /** * Run the rules for this relation. As this is not an end object, then * the only useful rules are action rules that set tags on the contained * ways or nodes. Every rule should probably start with 'type=".."'. * * @param relation The relation to convert. */ public void convertRelation(Relation relation) { // Relations never resolve to a GType and so we ignore the return // value. relationRules.resolveType(relation); } private void addLine(Way way, GType gt) { MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(way.getPoints()); if (way.isBoolTag("oneway")) line.setDirection(true); clipper.clipLine(line, lineAdder); } private void addShape(Way way, GType gt) { MapShape shape = new MapShape(); elementSetup(shape, gt, way); shape.setPoints(way.getPoints()); clipper.clipShape(shape, collector); } private void addPoint(Node node, GType gt) { if (!clipper.contains(node.getLocation())) return; MapPoint mp = new MapPoint(); elementSetup(mp, gt, node); mp.setLocation(node.getLocation()); collector.addPoint(mp); } private void elementSetup(MapElement ms, GType gt, Element element) { ms.setName(element.getName()); ms.setType(gt.getType()); ms.setMinResolution(gt.getMinResolution()); ms.setMaxResolution(gt.getMaxResolution()); } void addRoad(Way way, GType gt) { if("roundabout".equals(way.getTag("junction"))) { String frigFactorTag = way.getTag("mkgmap:frig_roundabout"); if(frigFactorTag != null) { // do special roundabout frigging to make gps // routing prompt use the correct exit number double frigFactor = 0.25; // default try { frigFactor = Double.parseDouble(frigFactorTag); } catch (NumberFormatException nfe) { // relax, tag was probably not a number anyway } frigRoundabout(way, frigFactor); } } // if there is a bounding box, clip the way with it List<Way> clippedWays = null; if(bbox != null) { List<List<Coord>> lineSegs = LineClipper.clip(bbox, way.getPoints()); boundaryCoords = new HashSet<Coord>(); if (lineSegs != null) { clippedWays = new ArrayList<Way>(); for (List<Coord> lco : lineSegs) { Way nWay = new Way(); nWay.setName(way.getName()); nWay.copyTags(way); for(Coord co : lco) { nWay.addPoint(co); if(co.getHighwayCount() == 0) { boundaryCoords.add(co); co.incHighwayCount(); } } clippedWays.add(nWay); } } } if(clippedWays != null) { for(Way cw : clippedWays) { addRoadAfterSplittingLoops(cw, gt); } } else { // no bounding box or way was not clipped addRoadAfterSplittingLoops(way, gt); } } void addRoadAfterSplittingLoops(Way way, GType gt) { // check if the way is a loop or intersects with itself boolean wayWasSplit = true; // aka rescan required while(wayWasSplit) { List<Coord> wayPoints = way.getPoints(); int numPointsInWay = wayPoints.size(); wayWasSplit = false; // assume way won't be split // check each point in the way to see if it is // the same point as a following point in the way for(int p1I = 0; !wayWasSplit && p1I < (numPointsInWay - 1); p1I++) { Coord p1 = wayPoints.get(p1I); for(int p2I = p1I + 1; !wayWasSplit && p2I < numPointsInWay; p2I++) { if(p1 == wayPoints.get(p2I)) { // way is a loop or intersects itself int splitI = p2I - 1; // split before second point if(splitI == p1I) { log.info("Way has zero length segment - " + wayPoints.get(splitI).toOSMURL()); wayPoints.remove(p2I); // next point to inspect has same index --p2I; // but number of points has reduced --numPointsInWay; } else { // split the way before the second point log.info("Split way at " + wayPoints.get(splitI).toDegreeString() + " - it has " + (numPointsInWay - splitI - 1 ) + " following segments."); Way loopTail = splitWayAt(way, splitI); // way before split has now been verified addRoadWithoutLoops(way, gt); // now repeat for the tail of the way way = loopTail; wayWasSplit = true; } } } } if(!wayWasSplit) { // no split required so make road from way addRoadWithoutLoops(way, gt); } } } void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); int highwayCount = p.getHighwayCount(); if(highwayCount > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeId = nextNodeId++; nodeIdMap.put(p, nodeId); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way // so split it here to avoid exceeding // the max nodes in way limit trailingWay = splitWayAt(way, i); // this will have truncated // the current Way's points so // the loop will now terminate log.info("Splitting way " + way.getName() + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(roadId++, line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); int speedIdx = -1; if(maxSpeed != null) speedIdx = getSpeedIdx(maxSpeed); road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType // for the purpose of testing for access restrictions highwayType = way.getTag("route"); } String[] vehicleClass = { "access", "bicycle", "foot", "hgv", "motorcar", "motorcycle", "psv", }; int[] accessSelector = { RoadNetwork.NO_MAX, RoadNetwork.NO_BIKE, RoadNetwork.NO_FOOT, RoadNetwork.NO_TRUCK, RoadNetwork.NO_CAR, RoadNetwork.NO_CAR, // motorcycle RoadNetwork.NO_BUS }; for(int i = 0; i < vehicleClass.length; ++i) { String access = way.getTag(vehicleClass[i]); if(access != null) access = access.toUpperCase(); if(access != null && (access.equals("PRIVATE") || access.equals("DESTINATION") || // FIXME - too strict access.equals("UNKNOWN") || access.equals("NO"))) { if(accessSelector[i] == RoadNetwork.NO_MAX) { // everything is denied access for(int j = 0; j < noAccess.length; ++j) noAccess[j] = true; } else { // just the specific vehicle // class is denied access noAccess[accessSelector[i]] = true; } log.info("No " + vehicleClass[i] + " allowed in " + highwayType + " " + way.getName()); } } if("footway".equals(highwayType)) { noAccess[RoadNetwork.EMERGENCY] = true; noAccess[RoadNetwork.DELIVERY] = true; noAccess[RoadNetwork.NO_CAR] = true; noAccess[RoadNetwork.NO_BUS] = true; noAccess[RoadNetwork.NO_TAXI] = true; if(!way.accessExplicitlyAllowed("bicycle")) noAccess[RoadNetwork.NO_BIKE] = true; noAccess[RoadNetwork.NO_TRUCK] = true; } else if("cycleway".equals(highwayType) || "bridleway".equals(highwayType)) { noAccess[RoadNetwork.EMERGENCY] = true; noAccess[RoadNetwork.DELIVERY] = true; noAccess[RoadNetwork.NO_CAR] = true; noAccess[RoadNetwork.NO_BUS] = true; noAccess[RoadNetwork.NO_TAXI] = true; noAccess[RoadNetwork.NO_TRUCK] = true; } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + way.getName() + "'s point #" + n + " at " + points.get(0).toDegreeString() + " is a boundary node"); } points.set(n, new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary)); } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } - clipper.clipLine(road, lineAdder); + lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); } // split a Way at the specified point and return the new Way // (the original Way is truncated) Way splitWayAt(Way way, int index) { Way trailingWay = new Way(); List<Coord> wayPoints = way.getPoints(); int numPointsInWay = wayPoints.size(); for(int i = index; i < numPointsInWay; ++i) trailingWay.addPoint(wayPoints.get(i)); // ensure split point becomes a node wayPoints.get(index).incHighwayCount(); // copy the way's name and tags to the new way trailingWay.setName(way.getName()); trailingWay.copyTags(way); // remove the points after the split from the original way // it's probably more efficient to remove from the end first for(int i = numPointsInWay - 1; i > index; --i) wayPoints.remove(i); return trailingWay; } // function to add points between adjacent nodes in a roundabout // to make gps use correct exit number in routing instructions void frigRoundabout(Way way, double frigFactor) { List<Coord> wayPoints = way.getPoints(); int origNumPoints = wayPoints.size(); if(origNumPoints < 3) { // forget it! return; } int[] highWayCounts = new int[origNumPoints]; int middleLat = 0; int middleLon = 0; highWayCounts[0] = wayPoints.get(0).getHighwayCount(); for(int i = 1; i < origNumPoints; ++i) { Coord p = wayPoints.get(i); middleLat += p.getLatitude(); middleLon += p.getLongitude(); highWayCounts[i] = p.getHighwayCount(); } middleLat /= origNumPoints - 1; middleLon /= origNumPoints - 1; Coord middleCoord = new Coord(middleLat, middleLon); // account for fact that roundabout joins itself --highWayCounts[0]; --highWayCounts[origNumPoints - 1]; for(int i = origNumPoints - 2; i >= 0; --i) { Coord p1 = wayPoints.get(i); Coord p2 = wayPoints.get(i + 1); if(highWayCounts[i] > 1 && highWayCounts[i + 1] > 1) { // both points will be nodes so insert // a new point between them that // (approximately) falls on the // roundabout's perimeter int newLat = (p1.getLatitude() + p2.getLatitude()) / 2; int newLon = (p1.getLongitude() + p2.getLongitude()) / 2; // new point has to be "outside" of // existing line joining p1 and p2 - // how far outside is determined by // the ratio of the distance between // p1 and p2 compared to the distance // of p1 from the "middle" of the // roundabout (aka, the approx radius // of the roundabout) - the higher the // value of frigFactor, the further out // the point will be double scale = 1 + frigFactor * p1.distance(p2) / p1.distance(middleCoord); newLat = (int)((newLat - middleLat) * scale) + middleLat; newLon = (int)((newLon - middleLon) * scale) + middleLon; Coord newPoint = new Coord(newLat, newLon); double d1 = p1.distance(newPoint); double d2 = p2.distance(newPoint); double maxDistance = 100; if(d1 >= MIN_DISTANCE_BETWEEN_NODES && d1 <= maxDistance && d2 >= MIN_DISTANCE_BETWEEN_NODES && d2 <= maxDistance) { newPoint.incHighwayCount(); wayPoints.add(i + 1, newPoint); } else if(false) { System.err.println("Not inserting point in roundabout after node " + i + " " + way.getName() + " @ " + middleCoord.toDegreeString() + " (d1 = " + p1.distance(newPoint) + " d2 = " + p2.distance(newPoint) + ")"); } } } } int getSpeedIdx(String tag) { double kmh = 0.0; double factor = 1.0; String speedTag = tag.toLowerCase().trim(); if(speedTag.matches(".*mph")) // Check if it is a limit in mph { speedTag = speedTag.replaceFirst("mph", ""); factor = 1.61; } else speedTag = speedTag.replaceFirst("kmh", ""); // get rid of kmh just in case try { kmh = Integer.parseInt(speedTag) * factor; } catch (Exception e) { return -1; } if(kmh > 110) return 7; if(kmh > 90) return 6; if(kmh > 80) return 5; if(kmh > 60) return 4; if(kmh > 40) return 3; if(kmh > 20) return 2; if(kmh > 10) return 1; else return 0; } }
true
true
void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); int highwayCount = p.getHighwayCount(); if(highwayCount > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeId = nextNodeId++; nodeIdMap.put(p, nodeId); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way // so split it here to avoid exceeding // the max nodes in way limit trailingWay = splitWayAt(way, i); // this will have truncated // the current Way's points so // the loop will now terminate log.info("Splitting way " + way.getName() + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(roadId++, line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); int speedIdx = -1; if(maxSpeed != null) speedIdx = getSpeedIdx(maxSpeed); road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType // for the purpose of testing for access restrictions highwayType = way.getTag("route"); } String[] vehicleClass = { "access", "bicycle", "foot", "hgv", "motorcar", "motorcycle", "psv", }; int[] accessSelector = { RoadNetwork.NO_MAX, RoadNetwork.NO_BIKE, RoadNetwork.NO_FOOT, RoadNetwork.NO_TRUCK, RoadNetwork.NO_CAR, RoadNetwork.NO_CAR, // motorcycle RoadNetwork.NO_BUS }; for(int i = 0; i < vehicleClass.length; ++i) { String access = way.getTag(vehicleClass[i]); if(access != null) access = access.toUpperCase(); if(access != null && (access.equals("PRIVATE") || access.equals("DESTINATION") || // FIXME - too strict access.equals("UNKNOWN") || access.equals("NO"))) { if(accessSelector[i] == RoadNetwork.NO_MAX) { // everything is denied access for(int j = 0; j < noAccess.length; ++j) noAccess[j] = true; } else { // just the specific vehicle // class is denied access noAccess[accessSelector[i]] = true; } log.info("No " + vehicleClass[i] + " allowed in " + highwayType + " " + way.getName()); } } if("footway".equals(highwayType)) { noAccess[RoadNetwork.EMERGENCY] = true; noAccess[RoadNetwork.DELIVERY] = true; noAccess[RoadNetwork.NO_CAR] = true; noAccess[RoadNetwork.NO_BUS] = true; noAccess[RoadNetwork.NO_TAXI] = true; if(!way.accessExplicitlyAllowed("bicycle")) noAccess[RoadNetwork.NO_BIKE] = true; noAccess[RoadNetwork.NO_TRUCK] = true; } else if("cycleway".equals(highwayType) || "bridleway".equals(highwayType)) { noAccess[RoadNetwork.EMERGENCY] = true; noAccess[RoadNetwork.DELIVERY] = true; noAccess[RoadNetwork.NO_CAR] = true; noAccess[RoadNetwork.NO_BUS] = true; noAccess[RoadNetwork.NO_TAXI] = true; noAccess[RoadNetwork.NO_TRUCK] = true; } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + way.getName() + "'s point #" + n + " at " + points.get(0).toDegreeString() + " is a boundary node"); } points.set(n, new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary)); } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } clipper.clipLine(road, lineAdder); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); }
void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); int highwayCount = p.getHighwayCount(); if(highwayCount > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeId = nextNodeId++; nodeIdMap.put(p, nodeId); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way // so split it here to avoid exceeding // the max nodes in way limit trailingWay = splitWayAt(way, i); // this will have truncated // the current Way's points so // the loop will now terminate log.info("Splitting way " + way.getName() + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(roadId++, line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); int speedIdx = -1; if(maxSpeed != null) speedIdx = getSpeedIdx(maxSpeed); road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType // for the purpose of testing for access restrictions highwayType = way.getTag("route"); } String[] vehicleClass = { "access", "bicycle", "foot", "hgv", "motorcar", "motorcycle", "psv", }; int[] accessSelector = { RoadNetwork.NO_MAX, RoadNetwork.NO_BIKE, RoadNetwork.NO_FOOT, RoadNetwork.NO_TRUCK, RoadNetwork.NO_CAR, RoadNetwork.NO_CAR, // motorcycle RoadNetwork.NO_BUS }; for(int i = 0; i < vehicleClass.length; ++i) { String access = way.getTag(vehicleClass[i]); if(access != null) access = access.toUpperCase(); if(access != null && (access.equals("PRIVATE") || access.equals("DESTINATION") || // FIXME - too strict access.equals("UNKNOWN") || access.equals("NO"))) { if(accessSelector[i] == RoadNetwork.NO_MAX) { // everything is denied access for(int j = 0; j < noAccess.length; ++j) noAccess[j] = true; } else { // just the specific vehicle // class is denied access noAccess[accessSelector[i]] = true; } log.info("No " + vehicleClass[i] + " allowed in " + highwayType + " " + way.getName()); } } if("footway".equals(highwayType)) { noAccess[RoadNetwork.EMERGENCY] = true; noAccess[RoadNetwork.DELIVERY] = true; noAccess[RoadNetwork.NO_CAR] = true; noAccess[RoadNetwork.NO_BUS] = true; noAccess[RoadNetwork.NO_TAXI] = true; if(!way.accessExplicitlyAllowed("bicycle")) noAccess[RoadNetwork.NO_BIKE] = true; noAccess[RoadNetwork.NO_TRUCK] = true; } else if("cycleway".equals(highwayType) || "bridleway".equals(highwayType)) { noAccess[RoadNetwork.EMERGENCY] = true; noAccess[RoadNetwork.DELIVERY] = true; noAccess[RoadNetwork.NO_CAR] = true; noAccess[RoadNetwork.NO_BUS] = true; noAccess[RoadNetwork.NO_TAXI] = true; noAccess[RoadNetwork.NO_TRUCK] = true; } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + way.getName() + "'s point #" + n + " at " + points.get(0).toDegreeString() + " is a boundary node"); } points.set(n, new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary)); } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); }
diff --git a/src/webrender/java/nextapp/echo2/webrender/output/HtmlDocument.java b/src/webrender/java/nextapp/echo2/webrender/output/HtmlDocument.java index 39397e5a..f338704f 100644 --- a/src/webrender/java/nextapp/echo2/webrender/output/HtmlDocument.java +++ b/src/webrender/java/nextapp/echo2/webrender/output/HtmlDocument.java @@ -1,136 +1,137 @@ /* * This file is part of the Echo Web Application Framework (hereinafter "Echo"). * Copyright (C) 2002-2005 NextApp, Inc. * * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. */ package nextapp.echo2.webrender.output; import nextapp.echo2.webrender.util.DomUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Text; /** * A simple wrapper around JAXP/W3C DOM APIs to generate and render an * XHTML 1.0 Transitional document. */ public class HtmlDocument extends XmlDocument { public static final String XHTML_1_0_TRANSITIONAL_PUBLIC_ID = "-//W3C//DTD XHTML 1.0 Transitional//EN"; public static final String XHTML_1_0_TRANSITIONAL_SYSTSEM_ID = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; public static final String XHTML_1_0_NAMESPACE_URI = "http://www.w3.org/1999/xhtml"; /** * Creates a new <code>HtmlDocument</code>. */ public HtmlDocument(String publicId, String systemId, String namespaceUri) { super("html", publicId, systemId, namespaceUri); Document document = getDocument(); Element htmlElement = document.getDocumentElement(); Element headElement = document.createElement("head"); Element titleElement = document.createElement("title"); + titleElement.appendChild(document.createTextNode(" ")); Element bodyElement = document.createElement("body"); htmlElement.appendChild(headElement); headElement.appendChild(titleElement); htmlElement.appendChild(bodyElement); } /** * Adds inline JavaScript code to the document. * * @param code the inline code */ public void addJavaScriptText(String code) { Document document = getDocument(); Element headElement = (Element) document.getElementsByTagName("head").item(0); Element scriptElement = document.createElement("script"); Text textNode = document.createTextNode(code); scriptElement.appendChild(textNode); scriptElement.setAttribute("type", "text/javascript"); headElement.appendChild(scriptElement); } /** * Adds a JavaScript include reference to the document. * * @param uri the URI of the JavaScript code */ public void addJavaScriptInclude(String uri) { Document document = getDocument(); Element headElement = (Element) document.getElementsByTagName("head").item(0); Element scriptElement = document.createElement("script"); Text textNode = document.createTextNode(" "); scriptElement.appendChild(textNode); scriptElement.setAttribute("type", "text/javascript"); scriptElement.setAttribute("src", uri); headElement.appendChild(scriptElement); } /** * Retrieves the BODY element of the document. * * @return the BODY element */ public Element getBodyElement() { return (Element) getDocument().getElementsByTagName("body").item(0); } /** * Retrieves the HEAD element of the document. * * @return the HEAD element */ public Element getHeadElement() { return (Element) getDocument().getElementsByTagName("head").item(0); } /** * Sets the value of the "generator" META element. * * @param value the value */ public void setGenarator(String value) { Element metaGeneratorElement = getDocument().createElement("meta"); metaGeneratorElement.setAttribute("name", "generator"); metaGeneratorElement.setAttribute("content", value); getHeadElement().appendChild(metaGeneratorElement); } /** * Convenience method to set the title of the document. * * @param value The new title value. */ public void setTitle(String value) { NodeList titles = getDocument().getElementsByTagName("title"); if (titles.getLength() == 1) { DomUtil.setElementText((Element) titles.item(0), value == null ? "" : value); } } }
true
true
public HtmlDocument(String publicId, String systemId, String namespaceUri) { super("html", publicId, systemId, namespaceUri); Document document = getDocument(); Element htmlElement = document.getDocumentElement(); Element headElement = document.createElement("head"); Element titleElement = document.createElement("title"); Element bodyElement = document.createElement("body"); htmlElement.appendChild(headElement); headElement.appendChild(titleElement); htmlElement.appendChild(bodyElement); }
public HtmlDocument(String publicId, String systemId, String namespaceUri) { super("html", publicId, systemId, namespaceUri); Document document = getDocument(); Element htmlElement = document.getDocumentElement(); Element headElement = document.createElement("head"); Element titleElement = document.createElement("title"); titleElement.appendChild(document.createTextNode(" ")); Element bodyElement = document.createElement("body"); htmlElement.appendChild(headElement); headElement.appendChild(titleElement); htmlElement.appendChild(bodyElement); }
diff --git a/user/test/com/google/gwt/dev/jjs/test/CoverageTest.java b/user/test/com/google/gwt/dev/jjs/test/CoverageTest.java index 8493a0d6f..daebfc7e4 100644 --- a/user/test/com/google/gwt/dev/jjs/test/CoverageTest.java +++ b/user/test/com/google/gwt/dev/jjs/test/CoverageTest.java @@ -1,956 +1,956 @@ /* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.dev.jjs.test; import com.google.gwt.junit.client.GWTTestCase; /** * This test is intended to exercise as many code paths and node types as * possible in the Java to JavaScript compiler. This test is not at all intended * to execute correctly. */ @SuppressWarnings("hiding") public class CoverageTest extends CoverageBase { /** * TODO: document me. */ public class Inner extends Super { public int x = 3; public final int y = 4; public Inner() { // ExplicitConstructorCall this(4); } public Inner(int i) { // ExplicitConstructorCall super(i); } public void foo() { final int z = this.y; new Inner() { { x = z; this.x = z; Inner.this.x = z; next = CoverageTest.this.next; next.foo(); CoverageTest.this.next.foo(); CoverageTest.this.x = z; CoverageTest.super.x = z; } public void foo() { x = z; this.x = z; Inner.this.x = z; next = CoverageTest.this.next; next.foo(); CoverageTest.this.next.foo(); CoverageTest.this.x = z; CoverageTest.super.x = z; } }; class NamedLocal extends Inner { @SuppressWarnings("unused") public void foo() { CoverageTest.this.getNext(); Inner.this.bar(); super.bar(); int x = z; } // JDT bug? This works in 5.0 but not in 1.4 // TODO: will javac compile it? class NamedLocalSub extends NamedLocal { @SuppressWarnings("unused") public void foo() { Inner.this.bar(); NamedLocal.this.foo(); super.foo(); int x = z; } } } testEmptyStatement(); new InnerSub().new InnerSubSub().fda(); new SecondMain().new FunkyInner(); /* * The statement below causes a javac bug in openJdk and sun's java 6. It * produces incorrect bytecode that fails with a java.lang.VerifyError -- * see Google's internal issue 1628473. This is likely to be an hindrance * if and when GWT attempts to read bytecode directly. */ // new NamedLocal().new NamedLocalSub().foo(); } public void bar() { } private void testAllocationExpression() { // AllocationExpression o = new Super(); assertEquals("3", o.toString()); o = new Super(42); assertEquals("42", o.toString()); } private void testAndAndExpression() { // AND_AND_Expression z = i == 1 && betterNotEval(); assertFalse(z); } private void testArrayAllocationExpression() { // ArrayAllocationExpression ia = new int[4]; assertEquals(4, ia.length); iaa = new int[4][3]; assertEquals(4, iaa.length); assertEquals(3, iaa[2].length); iaaa = new int[4][3][]; assertEquals(4, iaaa.length); assertEquals(3, iaaa[2].length); assertNull(iaaa[2][2]); } private void testArrayInitializer() { // ArrayInitializer ia = new int[] {i, j}; assertEquals(2, ia.length); assertEquals(j, ia[1]); iaa = new int[][] {{i, j}}; assertEquals(1, iaa.length); assertEquals(2, iaa[0].length); assertEquals(j, iaa[0][1]); iaa = new int[][] { {i, j}, ia}; assertEquals(2, iaa.length); assertEquals(2, iaa[0].length); assertEquals(j, iaa[0][1]); assertEquals(ia, iaa[1]); } private void testArrayReference() { // ArrayReference i = ia[0]; assertEquals(ia[0], i); ia[0] = i; } private void testAssertStatement() { // AssertStatement if (!CoverageTest.class.desiredAssertionStatus()) { return; } i = 1; try { assert i == 2; fail(); } catch (AssertionError e) { } try { assert i == 3 : true; fail(); } catch (AssertionError e) { assertEquals("true", e.getMessage()); } try { assert i == 3 : 'c'; fail(); } catch (AssertionError e) { assertEquals("c", e.getMessage()); } try { assert i == 3 : 1.1; fail(); } catch (AssertionError e) { assertEquals("1.1", e.getMessage()); } try { - assert i == 3 : 1.2f; + assert i == 3 : 1.5f; fail(); } catch (AssertionError e) { - assertEquals("1.2", e.getMessage()); + assertEquals("1.5", e.getMessage()); } try { assert i == 3 : 5; fail(); } catch (AssertionError e) { assertEquals("5", e.getMessage()); } try { assert i == 3 : 6L; fail(); } catch (AssertionError e) { assertEquals("6", e.getMessage()); } try { assert i == 3 : "foo"; fail(); } catch (AssertionError e) { assertEquals("foo", e.getMessage()); } try { assert i == 3 : new Object() { @Override public String toString() { return "bar"; } }; fail(); } catch (AssertionError e) { assertEquals("bar", e.getMessage()); } } private void testAssignment() { // Assignment i = j; assertEquals(j, i); } private void testBinaryExpression() { // BinaryExpression i = 4; i = i + j; assertEquals(6, i); i = i - j; assertEquals(4, i); i = i * j; assertEquals(8, i); i = i / j; assertEquals(4, i); i = i % j; assertEquals(0, i); i = 7; i = i & j; assertEquals(2, i); i = 0; i = i | j; assertEquals(2, i); i = 7; i = i ^ j; assertEquals(5, i); i = i << j; assertEquals(20, i); i = i >> j; assertEquals(5, i); i = i >>> j; assertEquals(1, i); } private void testBreakContinueLabelStatement() { // BreakStatement, ContinueStatement z = true; i = 0; x = 0; outer : while (z) { ++x; inner : while (z) { ++i; if (i == 1) { continue; } if (i == 2) { continue inner; } if (i == 3) { continue outer; } if (i == 4) { break; } if (i == 5) { break inner; } if (i == 6) { break outer; } } } assertEquals(6, i); assertEquals(4, x); } private void testCaseSwitchStatement() { // CaseStatement, SwitchStatement i = 6; switch (j) { case 1: ++i; // fallthrough case 2: i += 2; // fallthrough case 3: i += 3; // fallthrough case 4: i += 4; // fallthrough default: i += 0; } assertEquals(15, i); } @SuppressWarnings("cast") private void testCastExpression() { // CastExpression o = (Super) o; } private void testCharLiteral() { // CharLiteral i = 'c'; assertEquals("c", String.valueOf((char) i)); } private void testClassLiteralAccess() { // ClassLiteralAccess o = Super.class; String str = o.toString(); // Class metadata could be disabled if (!str.startsWith("class Class$")) { assertEquals("class com.google.gwt.dev.jjs.test.CoverageTest$Super", str); } } private void testCompoundAssignment() { // CompoundAssignment i = 4; i += j; assertEquals(6, i); i -= j; assertEquals(4, i); i *= j; assertEquals(8, i); i /= j; assertEquals(4, i); i %= j; assertEquals(0, i); i = 7; i &= j; assertEquals(2, i); i = 0; i |= j; assertEquals(2, i); i = 7; i ^= j; assertEquals(5, i); i <<= j; assertEquals(20, i); i >>= j; assertEquals(5, i); i >>>= j; assertEquals(1, i); } private void testConditionalExpression() { // ConditionalExpression z = false; i = z ? 7 : j; assertEquals(j, i); } private void testDoStatement() { // DoStatement i = 3; z = false; do { i += j; } while (z); assertEquals(5, i); } private void testEmptyStatement() { // EmptyStatement ; } private void testEqualExpression() { // EqualExpression i = 3; assertFalse(i == j); assertTrue(i != j); assertFalse(i < j); assertFalse(i <= j); assertTrue(i > j); assertTrue(i >= j); } private void testForeachStatement() { for (int q : ia) { i = q; } } private void testForStatement() { // ForStatement i = 0; for (int q = 0, v = 4; q < v; ++q) { i += q; } assertEquals(6, i); for (i = 0; i < 4; ++i) { } assertEquals(4, i); } private void testIfStatement() { // IfStatement z = false; if (z) { fail(); } if (z) { fail(); } else { assertFalse(z); } if (!z) { assertFalse(z); } else { fail(); } } private void testInstanceOfExpression() { // InstanceOfExpression Object o = CoverageTest.this; assertTrue(o instanceof CoverageBase); } private void testLiterals() { // DoubleLiteral d = 3.141592653589793; assertEquals(3, (int) d); // FalseLiteral assertFalse(false); // FloatLiteral f = 3.1415927f; assertEquals(3, (int) f); // IntLiteral i = 4; // IntLiteralMinValue i = -2147483648; // LongLiteral l = 4L; // LongLiteralMinValue l = -9223372036854775808L; // NullLiteral o = null; // StringLiteral s = "f'oo\b\t\n\f\r\"\\"; assertEquals(s, "f" + '\'' + 'o' + 'o' + '\b' + '\t' + '\n' + '\f' + '\r' + '"' + '\\'); // TrueLiteral assertTrue(true); } private void testOrOrExpression() { // OR_OR_Expression i = 1; assertTrue(i == 1 || betterNotEval()); } private void testPostfixExpression() { // PostfixExpression assertEquals(1, i++); assertEquals(2, i--); } private void testPrefixExpression() { // PrefixExpression assertEquals(2, ++i); assertEquals(1, --i); } private void testQualifiedAllocationExpression() { // QualifiedAllocationExpression o = new Inner(); o = CoverageTest.this.new Inner(); o = new CoverageTest().new Inner(); } private void testQualifiedNameReference() { // QualifiedNameReference CoverageTest m = new CoverageTest(); ia = new int[2]; assertEquals("1", 2, ia.length); assertEquals("2", 2, m.j); assertEquals("3", 4, m.y); assertEquals("4", 2, new CoverageTest().j); assertEquals("5", 4, new CoverageTest().y); assertEquals("6", 2, m.next.j); assertEquals("7", 4, m.next.y); assertEquals("8", 2, new CoverageTest().next.j); assertEquals("9", 4, new CoverageTest().next.y); assertEquals("A", 2, m.getNext().j); assertEquals("B", 4, m.getNext().y); assertEquals("C", 2, new CoverageTest().getNext().j); assertEquals("D", 4, new CoverageTest().getNext().y); } private void testReferenceCalls() { // MessageSend, QualifiedSuperReference, QualifiedThisReference, // SuperReference, ThisReference Inner other = new Inner(); foo(); this.foo(); other.foo(); CoverageTest.this.foo(); super.foo(); Inner.super.foo(); CoverageTest.super.foo(); sfoo(); this.sfoo(); CoverageTest.sfoo(); Inner.sfoo(); Super.sfoo(); other.sfoo(); CoverageTest.this.sfoo(); super.sfoo(); Inner.super.sfoo(); CoverageTest.super.sfoo(); } private Inner testReferences() { // FieldReference, QualifiedSuperReference, QualifiedThisReference, // SuperReference, ThisReference Inner other = new Inner(); i = 3; i = i + j + x + y; assertEquals(12, i); i = this.i + this.j + this.x + this.y; assertEquals(21, i); i = CoverageTest.i + CoverageTest.j; assertEquals(8, i); i = Inner.i + Inner.j; assertEquals(10, i); i = Super.i + Super.j; assertEquals(12, i); i = other.i + other.j + other.x + other.y; assertEquals(21, i); i = Inner.this.i + Inner.this.j + Inner.this.x + Inner.this.y; assertEquals(30, i); i = CoverageTest.this.i + CoverageTest.this.j + CoverageTest.this.x + CoverageTest.this.y; assertEquals(15, i); i = super.i + super.j + super.x + super.y; assertEquals(25, i); i = Inner.super.i + Inner.super.j + Inner.super.x + Inner.super.y; assertEquals(35, i); i = CoverageTest.super.i + CoverageTest.super.j + CoverageTest.super.x + CoverageTest.super.y; assertEquals(10, i); return other; } private void testReturnStatement() { // ReturnStatement assertEquals("foo", doReturnFoo()); if (true) { return; } fail(); } private void testSynchronizedStatement() { // SynchronizedStatement synchronized (inner) { inner.i = i; } } private void testTryCatchFinallyThrowStatement() { // ThrowStatement, TryStatement try { i = 3; if (true) { throw new Exception(); } fail(); } catch (Exception e) { } finally { i = 7; } assertEquals(7, i); try { try { i = 3; } catch (Throwable t) { fail(); } } catch (Throwable t) { fail(); } finally { i = 7; } assertEquals(7, i); } private void testUnaryExpression() { // UnaryExpression i = 4; assertEquals(-4, -i); assertEquals(-5, ~i); z = true; assertFalse(!z); } private void testWhileStatement() { // WhileStatement z = false; while (z) { fail(); } } } /** * TODO: document me. */ public static class Super { public static int i = 2; public static final int j = 2; // Initializer static { Super.i = 1; } // Initializer static { Super.i = 3; } protected static void sfoo() { } public int x = 2; public final int y = 4; // Initializer { x = 1; } // Initializer { x = 3; } public Super() { } public Super(int i) { x = i; } public void foo() { } public String toString() { return String.valueOf(x); } } private static class InnerSub extends Inner { private class InnerSubSub extends InnerSub { { asdfasdfasdf = InnerSub.this.asdfasdfasdf; InnerSub.this.asdfasdfasdf = asdfasdfasdf; asdfasdfasdf = super.asdfasdfasdf; super.asdfasdfasdf = asdfasdfasdf; } void fda() { asdfasdfasdf = InnerSub.this.asdfasdfasdf; InnerSub.this.asdfasdfasdf = asdfasdfasdf; asdfasdfasdf = super.asdfasdfasdf; super.asdfasdfasdf = asdfasdfasdf; } } private int asdfasdfasdf = 3; InnerSub() { new CoverageTest().super(); } } private static class SecondMain { private class FunkyInner extends Inner { FunkyInner() { new CoverageTest().super(); } } } public static double d; public static float f; public static int i = 1 + 2 + 3; public static int[] ia; public static int[][] iaa; public static int[][][] iaaa; public static final int j = 2; public static long l; public static Object o; public static String s = "foo"; public static CoverageTest singleton; public static boolean z; public static boolean betterNotEval() { fail(); return false; } protected static void sfoo() { } private static String doReturnFoo() { if (true) { return "foo"; } fail(); return "bar"; } public final Inner inner = new Inner(); public CoverageTest next; public int x = 3; public final int y = 4; public CoverageTest() { if (singleton == null) { singleton = this; } next = this; } public void foo() { } public String getModuleName() { return "com.google.gwt.dev.jjs.CompilerSuite"; } public CoverageTest getNext() { return next; } public void testAllocationExpression() { inner.testAllocationExpression(); } public void testAndAndExpression() { inner.testAndAndExpression(); } public void testArrayAllocationExpression() { inner.testArrayAllocationExpression(); } public void testArrayInitializer() { inner.testArrayInitializer(); } public void testArrayReference() { inner.testArrayReference(); } public void testAssertStatement() { inner.testAssertStatement(); } public void testAssignment() { inner.testAssignment(); } public void testBinaryExpression() { inner.testBinaryExpression(); } public void testBreakContinueLabelStatement() { inner.testBreakContinueLabelStatement(); } public void testCaseSwitchStatement() { inner.testCaseSwitchStatement(); } public void testCastExpression() { inner.testCastExpression(); } public void testCharLiteral() { inner.testCharLiteral(); } public void testClassLiteralAccess() { inner.testClassLiteralAccess(); } public void testCompoundAssignment() { inner.testCompoundAssignment(); } public void testConditionalExpression() { inner.testConditionalExpression(); } public void testDoStatement() { inner.testDoStatement(); } public void testEmptyStatement() { inner.testEmptyStatement(); } public void testEqualExpression() { inner.testEqualExpression(); } public void testForeachStatement() { inner.testForeachStatement(); } public void testForStatement() { inner.testForStatement(); } public void testIfStatement() { inner.testIfStatement(); } public void testInstanceOfExpression() { inner.testInstanceOfExpression(); } public void testLiterals() { inner.testLiterals(); } public void testOrOrExpression() { inner.testOrOrExpression(); } public void testPostfixExpression() { inner.testPostfixExpression(); } public void testPrefixExpression() { inner.testPrefixExpression(); } public void testQualifiedAllocationExpression() { inner.testQualifiedAllocationExpression(); } public void testQualifiedNameReference() { inner.testQualifiedNameReference(); } public void testReferenceCalls() { inner.testReferenceCalls(); } public void testReferences() { inner.testReferences(); } public void testReturnStatement() { inner.testReturnStatement(); } public void testSynchronizedStatement() { inner.testSynchronizedStatement(); } public void testTryCatchFinallyThrowStatement() { inner.testTryCatchFinallyThrowStatement(); } public void testUnaryExpression() { inner.testUnaryExpression(); } public void testWhileStatement() { inner.testWhileStatement(); } } abstract class CoverageBase extends GWTTestCase { public static int i = 1; public static final int j = 2; protected static void sfoo() { } public int x = 3; public final int y = 4; public void foo() { } }
false
true
private void testAssertStatement() { // AssertStatement if (!CoverageTest.class.desiredAssertionStatus()) { return; } i = 1; try { assert i == 2; fail(); } catch (AssertionError e) { } try { assert i == 3 : true; fail(); } catch (AssertionError e) { assertEquals("true", e.getMessage()); } try { assert i == 3 : 'c'; fail(); } catch (AssertionError e) { assertEquals("c", e.getMessage()); } try { assert i == 3 : 1.1; fail(); } catch (AssertionError e) { assertEquals("1.1", e.getMessage()); } try { assert i == 3 : 1.2f; fail(); } catch (AssertionError e) { assertEquals("1.2", e.getMessage()); } try { assert i == 3 : 5; fail(); } catch (AssertionError e) { assertEquals("5", e.getMessage()); } try { assert i == 3 : 6L; fail(); } catch (AssertionError e) { assertEquals("6", e.getMessage()); } try { assert i == 3 : "foo"; fail(); } catch (AssertionError e) { assertEquals("foo", e.getMessage()); } try { assert i == 3 : new Object() { @Override public String toString() { return "bar"; } }; fail(); } catch (AssertionError e) { assertEquals("bar", e.getMessage()); } }
private void testAssertStatement() { // AssertStatement if (!CoverageTest.class.desiredAssertionStatus()) { return; } i = 1; try { assert i == 2; fail(); } catch (AssertionError e) { } try { assert i == 3 : true; fail(); } catch (AssertionError e) { assertEquals("true", e.getMessage()); } try { assert i == 3 : 'c'; fail(); } catch (AssertionError e) { assertEquals("c", e.getMessage()); } try { assert i == 3 : 1.1; fail(); } catch (AssertionError e) { assertEquals("1.1", e.getMessage()); } try { assert i == 3 : 1.5f; fail(); } catch (AssertionError e) { assertEquals("1.5", e.getMessage()); } try { assert i == 3 : 5; fail(); } catch (AssertionError e) { assertEquals("5", e.getMessage()); } try { assert i == 3 : 6L; fail(); } catch (AssertionError e) { assertEquals("6", e.getMessage()); } try { assert i == 3 : "foo"; fail(); } catch (AssertionError e) { assertEquals("foo", e.getMessage()); } try { assert i == 3 : new Object() { @Override public String toString() { return "bar"; } }; fail(); } catch (AssertionError e) { assertEquals("bar", e.getMessage()); } }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/gitiles/MenuFilter.java b/src/main/java/com/googlesource/gerrit/plugins/gitiles/MenuFilter.java index df5438e..aeeec93 100644 --- a/src/main/java/com/googlesource/gerrit/plugins/gitiles/MenuFilter.java +++ b/src/main/java/com/googlesource/gerrit/plugins/gitiles/MenuFilter.java @@ -1,72 +1,72 @@ // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.gitiles; import com.google.common.collect.Lists; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gitiles.BaseServlet; import com.google.gitiles.GitilesUrls; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.IOException; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; class MenuFilter implements Filter { private final Provider<CurrentUser> userProvider; private final GitilesUrls urls; @Inject MenuFilter(Provider<CurrentUser> userProvider, GitilesUrls urls) { this.userProvider = userProvider; this.urls = urls; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; CurrentUser user = userProvider.get(); List<Object> entries = Lists.newArrayListWithCapacity(2); if (user instanceof IdentifiedUser) { entries .add(BaseServlet.menuEntry(((IdentifiedUser) user).getName(), null)); entries.add(BaseServlet.menuEntry("Sign Out", urls.getBaseGerritUrl(req) - + "logout/")); + + "logout")); } else { entries.add(BaseServlet.menuEntry("Sign In", urls.getBaseGerritUrl(req) - + "login/")); + + "login")); } BaseServlet.putSoyData(req, "menuEntries", entries); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
false
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; CurrentUser user = userProvider.get(); List<Object> entries = Lists.newArrayListWithCapacity(2); if (user instanceof IdentifiedUser) { entries .add(BaseServlet.menuEntry(((IdentifiedUser) user).getName(), null)); entries.add(BaseServlet.menuEntry("Sign Out", urls.getBaseGerritUrl(req) + "logout/")); } else { entries.add(BaseServlet.menuEntry("Sign In", urls.getBaseGerritUrl(req) + "login/")); } BaseServlet.putSoyData(req, "menuEntries", entries); chain.doFilter(request, response); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; CurrentUser user = userProvider.get(); List<Object> entries = Lists.newArrayListWithCapacity(2); if (user instanceof IdentifiedUser) { entries .add(BaseServlet.menuEntry(((IdentifiedUser) user).getName(), null)); entries.add(BaseServlet.menuEntry("Sign Out", urls.getBaseGerritUrl(req) + "logout")); } else { entries.add(BaseServlet.menuEntry("Sign In", urls.getBaseGerritUrl(req) + "login")); } BaseServlet.putSoyData(req, "menuEntries", entries); chain.doFilter(request, response); }
diff --git a/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java b/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java index d5604e89..28936efb 100644 --- a/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java +++ b/do_jdbc/src/main/java/data_objects/drivers/AbstractDriverDefinition.java @@ -1,536 +1,535 @@ package data_objects.drivers; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.Map; import java.util.Properties; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.jruby.Ruby; import org.jruby.RubyBigDecimal; import org.jruby.RubyBignum; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyFloat; import org.jruby.RubyHash; import org.jruby.RubyNumeric; import org.jruby.RubyObjectAdapter; import org.jruby.RubyProc; import org.jruby.RubyRegexp; import org.jruby.RubyString; import org.jruby.RubyTime; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.marshal.UnmarshalStream; import org.jruby.util.ByteList; import data_objects.RubyType; import java.lang.UnsupportedOperationException; /** * * @author alexbcoles * @author mkristian */ public abstract class AbstractDriverDefinition implements DriverDefinition { // assuming that API is thread safe protected static final RubyObjectAdapter API = JavaEmbedUtils .newObjectAdapter(); protected final static DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); private final String scheme; private final String jdbcScheme; private final String moduleName; protected AbstractDriverDefinition(String scheme, String moduleName) { this(scheme, scheme, moduleName); } protected AbstractDriverDefinition(String scheme, String jdbcScheme, String moduleName) { this.scheme = scheme; this.jdbcScheme = jdbcScheme; this.moduleName = moduleName; } public String getModuleName() { return this.moduleName; } public String getErrorName() { return this.moduleName + "Error"; } @SuppressWarnings("unchecked") public URI parseConnectionURI(IRubyObject connection_uri) throws URISyntaxException, UnsupportedEncodingException { URI uri; if ("DataObjects::URI".equals(connection_uri.getType().getName())) { String query; StringBuffer userInfo = new StringBuffer(); verifyScheme(stringOrNull(API.callMethod(connection_uri, "scheme"))); String user = stringOrNull(API.callMethod(connection_uri, "user")); String password = stringOrNull(API.callMethod(connection_uri, "password")); String host = stringOrNull(API.callMethod(connection_uri, "host")); int port = intOrMinusOne(API.callMethod(connection_uri, "port")); String path = stringOrNull(API.callMethod(connection_uri, "path")); IRubyObject query_values = API.callMethod(connection_uri, "query"); String fragment = stringOrNull(API.callMethod(connection_uri, "fragment")); if (user != null && !"".equals(user)) { userInfo.append(user); if (password != null && !"".equals(password)) { userInfo.append(":").append(password); } } if (query_values.isNil()) { query = null; } else if (query_values instanceof RubyHash) { query = mapToQueryString(query_values.convertToHash()); } else { query = API.callMethod(query_values, "to_s").asJavaString(); } if (host != null && !"".equals(host)) { // a client/server database (e.g. MySQL, PostgreSQL, MS // SQLServer) uri = new URI(this.jdbcScheme, userInfo.toString(), host, port, path, query, fragment); } else { // an embedded / file-based database (e.g. SQLite3, Derby // (embedded mode), HSQLDB - use opaque uri uri = new URI(this.jdbcScheme, path, fragment); } } else { // If connection_uri comes in as a string, we just pass it // through uri = new URI(connection_uri.asJavaString()); } return uri; } protected void verifyScheme(String scheme) { if (!this.scheme.equals(scheme)) { throw new RuntimeException("scheme mismatch, expected: " + this.scheme + " but got: " + scheme); } } /** * Convert a map of key/values to a URI query string * * @param map * @return * @throws java.io.UnsupportedEncodingException */ private String mapToQueryString(Map<Object, Object> map) throws UnsupportedEncodingException { StringBuffer querySb = new StringBuffer(); for (Map.Entry<Object, Object> pairs: map.entrySet()){ String key = (pairs.getKey() != null) ? pairs.getKey().toString() : ""; String value = (pairs.getValue() != null) ? pairs.getValue() .toString() : ""; querySb.append(java.net.URLEncoder.encode(key, "UTF-8")) .append("="); querySb.append(java.net.URLEncoder.encode(value, "UTF-8")); } return querySb.toString(); } public RaiseException newDriverError(Ruby runtime, String message) { RubyClass driverError = runtime.getClass(getErrorName()); return new RaiseException(runtime, driverError, message, true); } public RaiseException newDriverError(Ruby runtime, SQLException exception) { return newDriverError(runtime, exception, null); } public RaiseException newDriverError(Ruby runtime, SQLException exception, java.sql.Statement statement) { RubyClass driverError = runtime.getClass(getErrorName()); int code = exception.getErrorCode(); StringBuffer sb = new StringBuffer("("); // Append the Vendor Code, if there is one // TODO: parse vendor exception codes // TODO: replace 'vendor' with vendor name if (code > 0) sb.append("vendor_errno=").append(code).append(", "); sb.append("sql_state=").append(exception.getSQLState()).append(") "); sb.append(exception.getLocalizedMessage()); if (statement != null) sb.append("\nQuery: ").append(statementToString(statement)); return new RaiseException(runtime, driverError, sb.toString(), true); } public RubyObjectAdapter getObjectAdapter() { return API; } public RubyType jdbcTypeToRubyType(int type, int precision, int scale) { return RubyType.jdbcTypeToRubyType(type, scale); } public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: // to get NULL values we need to use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, new DateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See // http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html try { dt = rs.getTimestamp(col); } catch (SQLException sqle) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, new DateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Time ts = rs.getTime(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.getObject(), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: ps.setLong(idx, ((RubyBignum) arg).getLongValue()); break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(Connection connection, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } - @Override public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String statementToString(Statement s) { return s.toString(); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; // } }
true
true
public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: // to get NULL values we need to use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, new DateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See // http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html try { dt = rs.getTimestamp(col); } catch (SQLException sqle) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, new DateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Time ts = rs.getTime(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.getObject(), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: ps.setLong(idx, ((RubyBignum) arg).getLongValue()); break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(Connection connection, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } @Override public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String statementToString(Statement s) { return s.toString(); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; // } }
public final IRubyObject getTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { // TODO assert to needs to be turned on with the java call // better throw something assert (type != null); // this method does not expect a null Ruby Type if (rs == null) {// || rs.wasNull()) { return runtime.getNil(); } return doGetTypecastResultSetValue(runtime, rs, col, type); } protected IRubyObject doGetTypecastResultSetValue(Ruby runtime, ResultSet rs, int col, RubyType type) throws SQLException, IOException { //System.out.println(rs.getMetaData().getColumnTypeName(col) + " = " + type.toString()); switch (type) { case FIXNUM: case INTEGER: case BIGNUM: // to get NULL values we need to use getBigDecimal BigDecimal bdi = rs.getBigDecimal(col); if (bdi == null) { return runtime.getNil(); } // will return either Fixnum or Bignum return RubyBignum.bignorm(runtime, bdi.toBigInteger()); case FLOAT: // TODO: why getDouble is not used here? BigDecimal bdf = rs.getBigDecimal(col); if (bdf == null) { return runtime.getNil(); } return new RubyFloat(runtime, bdf.doubleValue()); case BIG_DECIMAL: BigDecimal bd = rs.getBigDecimal(col); if (bd == null) { return runtime.getNil(); } return new RubyBigDecimal(runtime, bd); case DATE: java.sql.Date date = rs.getDate(col); if (date == null) { return runtime.getNil(); } return prepareRubyDateFromSqlDate(runtime, new DateTime(date)); case DATE_TIME: java.sql.Timestamp dt = null; // DateTimes with all-zero components throw a SQLException with // SQLState S1009 in MySQL Connector/J 3.1+ // See // http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html try { dt = rs.getTimestamp(col); } catch (SQLException sqle) { } if (dt == null) { return runtime.getNil(); } return prepareRubyDateTimeFromSqlTimestamp(runtime, new DateTime(dt)); case TIME: switch (rs.getMetaData().getColumnType(col)) { case Types.TIME: java.sql.Time tm = rs.getTime(col); if (tm == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(tm)); case Types.TIMESTAMP: java.sql.Time ts = rs.getTime(col); if (ts == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlTime(runtime, new DateTime(ts)); case Types.DATE: java.sql.Date da = rs.getDate(col); if (da == null) { return runtime.getNil(); } return prepareRubyTimeFromSqlDate(runtime, da); default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } case TRUE_CLASS: // getBoolean delivers False in case the underlying data is null if (rs.getString(col) == null){ return runtime.getNil(); } return runtime.newBoolean(rs.getBoolean(col)); case BYTE_ARRAY: InputStream binaryStream = rs.getBinaryStream(col); ByteList bytes = new ByteList(2048); try { byte[] buf = new byte[2048]; for (int n = binaryStream.read(buf); n != -1; n = binaryStream .read(buf)) { bytes.append(buf, 0, n); } } finally { binaryStream.close(); } return API.callMethod(runtime.fastGetModule("Extlib").fastGetClass( "ByteArray"), "new", runtime.newString(bytes)); case CLASS: String classNameStr = rs.getString(col); if (classNameStr == null) { return runtime.getNil(); } RubyString class_name_str = RubyString.newUnicodeString(runtime, rs .getString(col)); class_name_str.setTaint(true); return API.callMethod(runtime.getObject(), "full_const_get", class_name_str); case OBJECT: InputStream asciiStream = rs.getAsciiStream(col); IRubyObject obj = runtime.getNil(); try { UnmarshalStream ums = new UnmarshalStream(runtime, asciiStream, RubyProc.NEVER); obj = ums.unmarshalObject(); } catch (IOException ioe) { // TODO: log this } return obj; case NIL: return runtime.getNil(); case STRING: default: String str = rs.getString(col); if (str == null) { return runtime.getNil(); } RubyString return_str = RubyString.newUnicodeString(runtime, str); return_str.setTaint(true); return return_str; } } public void setPreparedStatementParam(PreparedStatement ps, IRubyObject arg, int idx) throws SQLException { switch (RubyType.getRubyType(arg.getType().getName())) { case FIXNUM: ps.setInt(idx, Integer.parseInt(arg.toString())); break; case BIGNUM: ps.setLong(idx, ((RubyBignum) arg).getLongValue()); break; case FLOAT: ps.setDouble(idx, RubyNumeric.num2dbl(arg)); break; case BIG_DECIMAL: ps.setBigDecimal(idx, ((RubyBigDecimal) arg).getValue()); break; case NIL: ps.setNull(idx, ps.getParameterMetaData().getParameterType(idx)); break; case TRUE_CLASS: case FALSE_CLASS: ps.setBoolean(idx, arg.toString().equals("true")); break; case STRING: ps.setString(idx, arg.toString()); break; case CLASS: ps.setString(idx, arg.toString()); break; case BYTE_ARRAY: ps.setBytes(idx, ((RubyString) arg).getBytes()); break; // TODO: add support for ps.setBlob(); case DATE: ps.setDate(idx, java.sql.Date.valueOf(arg.toString())); break; case TIME: DateTime dateTime = ((RubyTime) arg).getDateTime(); Timestamp ts = new Timestamp(dateTime.getMillis()); ps.setTimestamp(idx, ts, dateTime.toGregorianCalendar()); break; case DATE_TIME: String datetime = arg.toString().replace('T', ' '); ps.setTimestamp(idx, Timestamp.valueOf(datetime .replaceFirst("[-+]..:..$", ""))); break; case REGEXP: ps.setString(idx, ((RubyRegexp) arg).source().toString()); break; // default case handling is simplified // TODO: if something is not working because of that then should be added to specs default: int jdbcType = ps.getParameterMetaData().getParameterType(idx); ps.setObject(idx, arg.toString(), jdbcType); } } public boolean registerPreparedStatementReturnParam(String sqlText, PreparedStatement ps, int idx) throws SQLException { return false; } public long getPreparedStatementReturnParam(PreparedStatement ps) throws SQLException { return 0; } public String prepareSqlTextForPs(String sqlText, IRubyObject[] args) { return sqlText; } public abstract boolean supportsJdbcGeneratedKeys(); public abstract boolean supportsJdbcScrollableResultSets(); public boolean supportsConnectionEncodings() { return false; } public boolean supportsConnectionPrepareStatementMethodWithGKFlag() { return true; } public ResultSet getGeneratedKeys(Connection connection) { return null; } public Properties getDefaultConnectionProperties() { return new Properties(); } public void afterConnectionCallback(Connection connection, Map<String, String> query) throws SQLException { // do nothing } public void setEncodingProperty(Properties props, String encodingName) { // do nothing } public Connection getConnectionWithEncoding(Ruby runtime, IRubyObject connection, String url, Properties props) throws SQLException { throw new UnsupportedOperationException("This method only returns a method" + " for drivers that support specifiying an encoding."); } public String quoteString(String str) { StringBuffer quotedValue = new StringBuffer(str.length() + 2); quotedValue.append("\'"); quotedValue.append(str.replaceAll("'", "''")); quotedValue.append("\'"); return quotedValue.toString(); } public String statementToString(Statement s) { return s.toString(); } protected static IRubyObject prepareRubyDateTimeFromSqlTimestamp( Ruby runtime, DateTime stamp) { if (stamp.getMillis() == 0) { return runtime.getNil(); } int zoneOffset = stamp.getZone().getOffset(stamp.getMillis()) / 3600000; RubyClass klazz = runtime.fastGetClass("DateTime"); IRubyObject rbOffset = runtime.fastGetClass("Rational").callMethod( runtime.getCurrentContext(), "new", new IRubyObject[] { runtime.newFixnum(zoneOffset), runtime.newFixnum(24) }); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(stamp.getYear()), runtime.newFixnum(stamp.getMonthOfYear()), runtime.newFixnum(stamp.getDayOfMonth()), runtime.newFixnum(stamp.getHourOfDay()), runtime.newFixnum(stamp.getMinuteOfHour()), runtime.newFixnum(stamp.getSecondOfMinute()), rbOffset }); } protected static IRubyObject prepareRubyTimeFromSqlTime(Ruby runtime, DateTime time) { if (time.getMillis() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, time); return rbTime; } protected static IRubyObject prepareRubyTimeFromSqlDate(Ruby runtime, Date date) { if (date.getTime() + 3600000 == 0) { return runtime.getNil(); } RubyTime rbTime = RubyTime.newTime(runtime, date.getTime()); return rbTime; } public static IRubyObject prepareRubyDateFromSqlDate(Ruby runtime, DateTime date) { if (date.getMillis() == 0) { return runtime.getNil(); } RubyClass klazz = runtime.fastGetClass("Date"); return klazz.callMethod(runtime.getCurrentContext(), "civil", new IRubyObject[] { runtime.newFixnum(date.getYear()), runtime.newFixnum(date.getMonthOfYear()), runtime.newFixnum(date.getDayOfMonth()) }); } private static String stringOrNull(IRubyObject obj) { return (!obj.isNil()) ? obj.asJavaString() : null; } private static int intOrMinusOne(IRubyObject obj) { return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : -1; } // private static Integer integerOrNull(IRubyObject obj) { // return (!obj.isNil()) ? RubyFixnum.fix2int(obj) : null; // } }
diff --git a/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java b/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java index 4ff18ae..0836637 100644 --- a/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java +++ b/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java @@ -1,298 +1,298 @@ /* ** This file is part of Filius, a network construction and simulation software. ** ** Originally created at the University of Siegen, Institute "Didactics of ** Informatics and E-Learning" by a students' project group: ** members (2006-2007): ** André Asschoff, Johannes Bade, Carsten Dittich, Thomas Gerding, ** Nadja Haßler, Ernst Johannes Klebert, Michell Weyer ** supervisors: ** Stefan Freischlad (maintainer until 2009), Peer Stechert ** Project is maintained since 2010 by Christian Eibl <[email protected]> ** and Stefan Freischlad ** Filius is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 2 of the License, or ** (at your option) version 3. ** ** Filius is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied ** warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ** PURPOSE. See the GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Filius. If not, see <http://www.gnu.org/licenses/>. */ package filius.gui.anwendungssicht; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.util.Observable; import java.util.StringTokenizer; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.event.InternalFrameEvent; import filius.Main; import filius.software.lokal.Terminal; import filius.software.system.Dateisystem; /** * Applikationsfenster fuer ein Terminal * * @author Johannes Bade & Thomas Gerding * */ public class GUIApplicationTerminalWindow extends GUIApplicationWindow { /** * */ private static final long serialVersionUID = 1L; private JTextArea terminalField; private JPanel backPanel; private JTextField inputField; private JLabel inputLabel; private JScrollPane tpPane; private boolean jobRunning; private String enteredCommand; private String[] enteredParameters; private boolean multipleObserverEvents; public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName){ super(desktop, appName); this.setMaximizable(false); this.setResizable(false); jobRunning = false; multipleObserverEvents = false; terminalField = new JTextArea(""); terminalField.setEditable(false); terminalField.setCaretColor(new Color(222,222,222)); terminalField.setForeground(new Color(222,222,222)); terminalField.setBackground(new Color(0,0,0)); terminalField.setFont(new Font("Courier New",Font.PLAIN,11)); terminalField.setFocusable(false); terminalField.setBorder(null); tpPane = new JScrollPane(terminalField); // make textfield scrollable tpPane.setBorder(null); tpPane.setBackground(new Color(0,0,0)); tpPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // do not show vert. scrollbar tpPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // do not show hor. scrollbar inputField = new JTextField(""); inputField.setEditable(true); inputField.setBackground(new Color(0,0,0)); inputField.setForeground(new Color(222,222,222)); inputField.setCaretColor(new Color(222,222,222)); inputField.setBorder(null); inputField.setFont(new Font("Courier New",Font.PLAIN,11)); inputField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { if(!(inputField.getText().isEmpty() || inputField.getText().replaceAll(" ", "").isEmpty())) { // only process non-empty input //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event started"); terminalField.append("\n"+inputLabel.getText()+inputField.getText()+"\n"); StringTokenizer tk = new StringTokenizer(inputField.getText(), " "); /* Erstes Token enthaelt den Befehl*/ enteredCommand = tk.nextToken(); /* restliche Tokens werden in String Array geschrieben. * Array wird sicherheitshalber mit mindestens 3 leeren Strings gefüllt! */ enteredParameters = new String[3+tk.countTokens()]; for (int i =0; i< 3+tk.countTokens(); i++) { enteredParameters[i] = new String(); } int iti = 0; while (tk.hasMoreTokens()) { enteredParameters[iti] =tk.nextToken(); iti++; } if (enteredCommand.equals("exit")) { doDefaultCloseAction(); } else if (enteredCommand.equals("reset")) { terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); } else { inputLabel.setVisible(false); jobRunning = true; ((Terminal) holeAnwendung()).terminalEingabeAuswerten(enteredCommand,enteredParameters); } } else { terminalField.append("\n"); } //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event finished"); inputField.setText(""); } - if (e.getKey() == 67 && e.getModifiers() == 2) { + if (e.getKeyCode() == 67 && e.getModifiers() == 2) { System.out.println("INTERRUPT"); ((Terminal) holeAnwendung()).setInterrupt(true); } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); inputLabel = new JLabel(">"); inputLabel.setBackground(new Color(0,0,0)); inputLabel.setForeground(new Color(222,222,222)); inputLabel.setFont(new Font("Courier New",Font.PLAIN,11)); Box terminalBox = Box.createHorizontalBox(); terminalBox.setBackground(new Color(0,0,0)); terminalBox.add(tpPane); // terminalField embedded in ScrollPane terminalBox.setBorder(BorderFactory.createEmptyBorder(5,5,1,5)); Box inputBox = Box.createHorizontalBox(); inputBox.setBackground(new Color(0,0,0)); inputBox.add(inputLabel); inputBox.add(Box.createHorizontalStrut(1)); inputBox.add(inputField); inputBox.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); backPanel = new JPanel(new BorderLayout()); backPanel.setBackground(new Color(0,0,0)); backPanel.add(terminalBox, BorderLayout.CENTER); backPanel.add(inputBox, BorderLayout.SOUTH); this.getContentPane().add(backPanel); terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); try { Thread.sleep(100); } catch (InterruptedException e) {} this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); pack(); inputField.requestFocus(); this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); } public void setMultipleObserverEvents(boolean flag) { } public void windowActivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void internalFrameActivated(InternalFrameEvent e) { } public void internalFrameClosed(InternalFrameEvent e) { } public void internalFrameClosing(InternalFrameEvent e) { } public void internalFrameDeactivated(InternalFrameEvent e) { } public void internalFrameDeiconified(InternalFrameEvent e) { } public void internalFrameIconified(InternalFrameEvent e) { } public void internalFrameOpened(InternalFrameEvent e) { } public void update(Observable arg0, Object arg1) { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (GUIApplicationTerminalWindow), update("+arg0+","+arg1+")"); if (arg1 == null) return; if (jobRunning) { //Main.debug.println("DEBUG: terminalField.height="+terminalField.getHeight()+", tpPane.height="+tpPane.getHeight()); if (arg1 instanceof Boolean) { multipleObserverEvents=((Boolean) arg1).booleanValue(); } else { // expect String this.terminalField.append(arg1.toString()); //this.terminalField.updateUI(); try { // mini delay to let the terminalField reliably update its new height Thread.sleep(200); } catch (InterruptedException e) {} this.tpPane.repaint(); this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); if(!multipleObserverEvents) { // is this observer call expected to be the last one for the current command, i.e., multipleOverserverEvents=false? this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); this.inputLabel.setVisible(true); jobRunning=false; } } } } }
true
true
public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName){ super(desktop, appName); this.setMaximizable(false); this.setResizable(false); jobRunning = false; multipleObserverEvents = false; terminalField = new JTextArea(""); terminalField.setEditable(false); terminalField.setCaretColor(new Color(222,222,222)); terminalField.setForeground(new Color(222,222,222)); terminalField.setBackground(new Color(0,0,0)); terminalField.setFont(new Font("Courier New",Font.PLAIN,11)); terminalField.setFocusable(false); terminalField.setBorder(null); tpPane = new JScrollPane(terminalField); // make textfield scrollable tpPane.setBorder(null); tpPane.setBackground(new Color(0,0,0)); tpPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // do not show vert. scrollbar tpPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // do not show hor. scrollbar inputField = new JTextField(""); inputField.setEditable(true); inputField.setBackground(new Color(0,0,0)); inputField.setForeground(new Color(222,222,222)); inputField.setCaretColor(new Color(222,222,222)); inputField.setBorder(null); inputField.setFont(new Font("Courier New",Font.PLAIN,11)); inputField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { if(!(inputField.getText().isEmpty() || inputField.getText().replaceAll(" ", "").isEmpty())) { // only process non-empty input //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event started"); terminalField.append("\n"+inputLabel.getText()+inputField.getText()+"\n"); StringTokenizer tk = new StringTokenizer(inputField.getText(), " "); /* Erstes Token enthaelt den Befehl*/ enteredCommand = tk.nextToken(); /* restliche Tokens werden in String Array geschrieben. * Array wird sicherheitshalber mit mindestens 3 leeren Strings gefüllt! */ enteredParameters = new String[3+tk.countTokens()]; for (int i =0; i< 3+tk.countTokens(); i++) { enteredParameters[i] = new String(); } int iti = 0; while (tk.hasMoreTokens()) { enteredParameters[iti] =tk.nextToken(); iti++; } if (enteredCommand.equals("exit")) { doDefaultCloseAction(); } else if (enteredCommand.equals("reset")) { terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); } else { inputLabel.setVisible(false); jobRunning = true; ((Terminal) holeAnwendung()).terminalEingabeAuswerten(enteredCommand,enteredParameters); } } else { terminalField.append("\n"); } //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event finished"); inputField.setText(""); } if (e.getKey() == 67 && e.getModifiers() == 2) { System.out.println("INTERRUPT"); ((Terminal) holeAnwendung()).setInterrupt(true); } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); inputLabel = new JLabel(">"); inputLabel.setBackground(new Color(0,0,0)); inputLabel.setForeground(new Color(222,222,222)); inputLabel.setFont(new Font("Courier New",Font.PLAIN,11)); Box terminalBox = Box.createHorizontalBox(); terminalBox.setBackground(new Color(0,0,0)); terminalBox.add(tpPane); // terminalField embedded in ScrollPane terminalBox.setBorder(BorderFactory.createEmptyBorder(5,5,1,5)); Box inputBox = Box.createHorizontalBox(); inputBox.setBackground(new Color(0,0,0)); inputBox.add(inputLabel); inputBox.add(Box.createHorizontalStrut(1)); inputBox.add(inputField); inputBox.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); backPanel = new JPanel(new BorderLayout()); backPanel.setBackground(new Color(0,0,0)); backPanel.add(terminalBox, BorderLayout.CENTER); backPanel.add(inputBox, BorderLayout.SOUTH); this.getContentPane().add(backPanel); terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); try { Thread.sleep(100); } catch (InterruptedException e) {} this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); pack(); inputField.requestFocus(); this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); }
public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName){ super(desktop, appName); this.setMaximizable(false); this.setResizable(false); jobRunning = false; multipleObserverEvents = false; terminalField = new JTextArea(""); terminalField.setEditable(false); terminalField.setCaretColor(new Color(222,222,222)); terminalField.setForeground(new Color(222,222,222)); terminalField.setBackground(new Color(0,0,0)); terminalField.setFont(new Font("Courier New",Font.PLAIN,11)); terminalField.setFocusable(false); terminalField.setBorder(null); tpPane = new JScrollPane(terminalField); // make textfield scrollable tpPane.setBorder(null); tpPane.setBackground(new Color(0,0,0)); tpPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // do not show vert. scrollbar tpPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // do not show hor. scrollbar inputField = new JTextField(""); inputField.setEditable(true); inputField.setBackground(new Color(0,0,0)); inputField.setForeground(new Color(222,222,222)); inputField.setCaretColor(new Color(222,222,222)); inputField.setBorder(null); inputField.setFont(new Font("Courier New",Font.PLAIN,11)); inputField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { if(!(inputField.getText().isEmpty() || inputField.getText().replaceAll(" ", "").isEmpty())) { // only process non-empty input //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event started"); terminalField.append("\n"+inputLabel.getText()+inputField.getText()+"\n"); StringTokenizer tk = new StringTokenizer(inputField.getText(), " "); /* Erstes Token enthaelt den Befehl*/ enteredCommand = tk.nextToken(); /* restliche Tokens werden in String Array geschrieben. * Array wird sicherheitshalber mit mindestens 3 leeren Strings gefüllt! */ enteredParameters = new String[3+tk.countTokens()]; for (int i =0; i< 3+tk.countTokens(); i++) { enteredParameters[i] = new String(); } int iti = 0; while (tk.hasMoreTokens()) { enteredParameters[iti] =tk.nextToken(); iti++; } if (enteredCommand.equals("exit")) { doDefaultCloseAction(); } else if (enteredCommand.equals("reset")) { terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); } else { inputLabel.setVisible(false); jobRunning = true; ((Terminal) holeAnwendung()).terminalEingabeAuswerten(enteredCommand,enteredParameters); } } else { terminalField.append("\n"); } //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event finished"); inputField.setText(""); } if (e.getKeyCode() == 67 && e.getModifiers() == 2) { System.out.println("INTERRUPT"); ((Terminal) holeAnwendung()).setInterrupt(true); } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); inputLabel = new JLabel(">"); inputLabel.setBackground(new Color(0,0,0)); inputLabel.setForeground(new Color(222,222,222)); inputLabel.setFont(new Font("Courier New",Font.PLAIN,11)); Box terminalBox = Box.createHorizontalBox(); terminalBox.setBackground(new Color(0,0,0)); terminalBox.add(tpPane); // terminalField embedded in ScrollPane terminalBox.setBorder(BorderFactory.createEmptyBorder(5,5,1,5)); Box inputBox = Box.createHorizontalBox(); inputBox.setBackground(new Color(0,0,0)); inputBox.add(inputLabel); inputBox.add(Box.createHorizontalStrut(1)); inputBox.add(inputField); inputBox.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); backPanel = new JPanel(new BorderLayout()); backPanel.setBackground(new Color(0,0,0)); backPanel.add(terminalBox, BorderLayout.CENTER); backPanel.add(inputBox, BorderLayout.SOUTH); this.getContentPane().add(backPanel); terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); try { Thread.sleep(100); } catch (InterruptedException e) {} this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); pack(); inputField.requestFocus(); this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); }
diff --git a/src/galileo/client/StoreNOAA.java b/src/galileo/client/StoreNOAA.java index 33d0982..c29f10f 100644 --- a/src/galileo/client/StoreNOAA.java +++ b/src/galileo/client/StoreNOAA.java @@ -1,126 +1,125 @@ /* Copyright (c) 2013, Colorado State University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package galileo.client; import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.Random; import galileo.comm.Disconnection; import galileo.comm.QueryRequest; import galileo.comm.QueryResponse; import galileo.comm.StorageRequest; import galileo.dataset.Block; import galileo.dataset.BlockMetadata; import galileo.dataset.Device; import galileo.dataset.DeviceSet; import galileo.dataset.FileBlock; import galileo.dataset.Metadata; import galileo.dataset.SpatialProperties; import galileo.dataset.TemporalProperties; import galileo.dataset.feature.Feature; import galileo.dataset.feature.FeatureSet; import galileo.event.EventContainer; import galileo.event.EventType; import galileo.net.ClientMessageRouter; import galileo.net.GalileoMessage; import galileo.net.MessageListener; import galileo.net.NetworkDestination; import galileo.query.Query; import galileo.samples.ConvertNetCDF; import galileo.serialization.Serializer; import galileo.util.FileNames; import galileo.util.GeoHash; import galileo.util.Pair; import galileo.util.ProgressBar; public class StoreNOAA { private ClientMessageRouter messageRouter; private EventPublisher publisher; public StoreNOAA() throws IOException { messageRouter = new ClientMessageRouter(); publisher = new EventPublisher(messageRouter); } public NetworkDestination connect(String hostname, int port) throws UnknownHostException, IOException { return messageRouter.connectTo(hostname, port); } public void disconnect() { messageRouter.shutdown(); } public void store(NetworkDestination destination, Block block) throws Exception { StorageRequest store = new StorageRequest(block); publisher.publish(destination, store); } public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: galileo.client.TextClient " + "<server-hostname> <server-port> <directory-name>"); return; } String serverHostName = args[0]; int serverPort = Integer.parseInt(args[1]); StoreNOAA client = new StoreNOAA(); File dir = new File(args[2]); - System.out.println(args[2]); NetworkDestination server = client.connect(serverHostName, serverPort); for (File f : dir.listFiles()) { Pair<String, String> nameParts = FileNames.splitExtension(f); String ext = nameParts.b; if (ext.equals("grb") || ext.equals("bz2") || ext.equals("gz")) { if(!f.getName().endsWith("_000.grb.bz2")) continue; System.out.println("Parsing: "+ f.getName()); Map<String, Metadata> metas = ConvertNetCDF.readFile(f.getAbsolutePath()); System.out.println("Storing: "+ f.getName()); int cntr = 0; ProgressBar pb = new ProgressBar(metas.size(), f.getName()); for (Map.Entry<String, Metadata> entry : metas.entrySet()) { pb.setVal(cntr++); client.store(server, ConvertNetCDF.createBlock("", entry.getValue())); } pb.finish(); } } System.out.println("Completed Directory"); } }
true
true
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: galileo.client.TextClient " + "<server-hostname> <server-port> <directory-name>"); return; } String serverHostName = args[0]; int serverPort = Integer.parseInt(args[1]); StoreNOAA client = new StoreNOAA(); File dir = new File(args[2]); System.out.println(args[2]); NetworkDestination server = client.connect(serverHostName, serverPort); for (File f : dir.listFiles()) { Pair<String, String> nameParts = FileNames.splitExtension(f); String ext = nameParts.b; if (ext.equals("grb") || ext.equals("bz2") || ext.equals("gz")) { if(!f.getName().endsWith("_000.grb.bz2")) continue; System.out.println("Parsing: "+ f.getName()); Map<String, Metadata> metas = ConvertNetCDF.readFile(f.getAbsolutePath()); System.out.println("Storing: "+ f.getName()); int cntr = 0; ProgressBar pb = new ProgressBar(metas.size(), f.getName()); for (Map.Entry<String, Metadata> entry : metas.entrySet()) { pb.setVal(cntr++); client.store(server, ConvertNetCDF.createBlock("", entry.getValue())); } pb.finish(); } } System.out.println("Completed Directory"); }
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Usage: galileo.client.TextClient " + "<server-hostname> <server-port> <directory-name>"); return; } String serverHostName = args[0]; int serverPort = Integer.parseInt(args[1]); StoreNOAA client = new StoreNOAA(); File dir = new File(args[2]); NetworkDestination server = client.connect(serverHostName, serverPort); for (File f : dir.listFiles()) { Pair<String, String> nameParts = FileNames.splitExtension(f); String ext = nameParts.b; if (ext.equals("grb") || ext.equals("bz2") || ext.equals("gz")) { if(!f.getName().endsWith("_000.grb.bz2")) continue; System.out.println("Parsing: "+ f.getName()); Map<String, Metadata> metas = ConvertNetCDF.readFile(f.getAbsolutePath()); System.out.println("Storing: "+ f.getName()); int cntr = 0; ProgressBar pb = new ProgressBar(metas.size(), f.getName()); for (Map.Entry<String, Metadata> entry : metas.entrySet()) { pb.setVal(cntr++); client.store(server, ConvertNetCDF.createBlock("", entry.getValue())); } pb.finish(); } } System.out.println("Completed Directory"); }
diff --git a/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/wizards/NewObjectClassWizard.java b/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/wizards/NewObjectClassWizard.java index ba095826c..8fd439575 100644 --- a/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/wizards/NewObjectClassWizard.java +++ b/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/wizards/NewObjectClassWizard.java @@ -1,112 +1,112 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.apacheds.schemaeditor.view.wizards; import org.apache.directory.studio.apacheds.schemaeditor.Activator; import org.apache.directory.studio.apacheds.schemaeditor.model.ObjectClassImpl; import org.apache.directory.studio.apacheds.schemaeditor.model.Schema; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; /** * This class represents the wizard to create a new ObjectClass. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class NewObjectClassWizard extends Wizard implements INewWizard { public static final String ID = Activator.PLUGIN_ID + ".wizards.NewObjectClassWizard"; /** The selected schema */ private Schema selectedSchema; // The pages of the wizards private NewObjectClassGeneralPageWizardPage generalPage; private NewObjectClassContentWizardPage contentPage; private NewObjectClassMandatoryAttributesPage mandatoryAttributesPage; private NewObjectClassOptionalAttributesPage optionalAttributesPage; /* (non-Javadoc) * @see org.eclipse.jface.wizard.Wizard#addPages() */ public void addPages() { // Creating pages generalPage = new NewObjectClassGeneralPageWizardPage(); generalPage.setSelectedSchema( selectedSchema ); contentPage = new NewObjectClassContentWizardPage(); mandatoryAttributesPage = new NewObjectClassMandatoryAttributesPage(); optionalAttributesPage = new NewObjectClassOptionalAttributesPage(); // Adding pages addPage( generalPage ); addPage( contentPage ); addPage( mandatoryAttributesPage ); addPage( optionalAttributesPage ); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.Wizard#performFinish() */ public boolean performFinish() { ObjectClassImpl newOC = new ObjectClassImpl( generalPage.getOidValue() ); newOC.setSchema( generalPage.getSchemaValue() ); newOC.setNames( generalPage.getAliasesValue() ); newOC.setDescription( generalPage.getDescriptionValue() ); newOC.setSuperClassesNames( contentPage.getSuperiorsNameValue() ); newOC.setType( contentPage.getClassTypeValue() ); newOC.setObsolete( contentPage.getObsoleteValue() ); newOC.setMustNamesList( mandatoryAttributesPage.getMandatoryAttributeTypesNames() ); - newOC.setMustNamesList( optionalAttributesPage.getOptionalAttributeTypesNames() ); + newOC.setMayNamesList( optionalAttributesPage.getOptionalAttributeTypesNames() ); Activator.getDefault().getSchemaHandler().addObjectClass( newOC ); return true; } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection) */ public void init( IWorkbench workbench, IStructuredSelection selection ) { // Nothing to do. } /** * Sets the selected schema. * * @param schema * the selected schema */ public void setSelectedSchema( Schema schema ) { selectedSchema = schema; } }
true
true
public boolean performFinish() { ObjectClassImpl newOC = new ObjectClassImpl( generalPage.getOidValue() ); newOC.setSchema( generalPage.getSchemaValue() ); newOC.setNames( generalPage.getAliasesValue() ); newOC.setDescription( generalPage.getDescriptionValue() ); newOC.setSuperClassesNames( contentPage.getSuperiorsNameValue() ); newOC.setType( contentPage.getClassTypeValue() ); newOC.setObsolete( contentPage.getObsoleteValue() ); newOC.setMustNamesList( mandatoryAttributesPage.getMandatoryAttributeTypesNames() ); newOC.setMustNamesList( optionalAttributesPage.getOptionalAttributeTypesNames() ); Activator.getDefault().getSchemaHandler().addObjectClass( newOC ); return true; }
public boolean performFinish() { ObjectClassImpl newOC = new ObjectClassImpl( generalPage.getOidValue() ); newOC.setSchema( generalPage.getSchemaValue() ); newOC.setNames( generalPage.getAliasesValue() ); newOC.setDescription( generalPage.getDescriptionValue() ); newOC.setSuperClassesNames( contentPage.getSuperiorsNameValue() ); newOC.setType( contentPage.getClassTypeValue() ); newOC.setObsolete( contentPage.getObsoleteValue() ); newOC.setMustNamesList( mandatoryAttributesPage.getMandatoryAttributeTypesNames() ); newOC.setMayNamesList( optionalAttributesPage.getOptionalAttributeTypesNames() ); Activator.getDefault().getSchemaHandler().addObjectClass( newOC ); return true; }
diff --git a/src/main/java/mmo/Chat/MMOChat.java b/src/main/java/mmo/Chat/MMOChat.java index 9777495..eb69921 100644 --- a/src/main/java/mmo/Chat/MMOChat.java +++ b/src/main/java/mmo/Chat/MMOChat.java @@ -1,170 +1,171 @@ /* * This file is part of mmoMinecraft (https://github.com/mmoMinecraftDev). * * mmoMinecraft is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package mmo.Chat; import java.util.ArrayList; import java.util.List; import mmo.Core.MMO; import mmo.Core.MMOPlugin; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.util.config.Configuration; public class MMOChat extends MMOPlugin { @Override public void onEnable() { super.onEnable(); MMO.mmoChat = true; getDatabase().find(ChatDB.class);//.findRowCount(); mmoPlayerListener mpl = new mmoPlayerListener(); pm.registerEvent(Type.PLAYER_CHAT, mpl, Priority.Normal, this); pm.registerEvent(Type.PLAYER_COMMAND_PREPROCESS, mpl, Priority.Normal, this); pm.registerEvent(Type.CUSTOM_EVENT, new Channels(), Priority.Normal, this); Chat.plugin = this; Chat.cfg = cfg; Chat.load(); } @Override public void loadConfiguration(Configuration cfg) { cfg.getString("default_channel", "Chat"); - if (cfg.getKeys("channel").isEmpty()) { + List<String> keys = cfg.getKeys("channel"); + if (keys == null || keys.isEmpty()) { cfg.getBoolean("channel.Chat.enabled", true); cfg.getBoolean("channel.Chat.command", true); cfg.getBoolean("channel.Chat.log", true); cfg.getString("channel.Chat.filters", "Server"); cfg.getBoolean("channel.Shout.enabled", true); cfg.getBoolean("channel.Shout.command", true); cfg.getBoolean("channel.Shout.log", true); cfg.getString("channel.Shout.filters", "World"); cfg.getBoolean("channel.Yell.enabled", true); cfg.getBoolean("channel.Yell.command", true); cfg.getBoolean("channel.Yell.log", true); cfg.getString("channel.Yell.filters", "Yell"); cfg.getBoolean("channel.Say.enabled", true); cfg.getBoolean("channel.Say.command", true); cfg.getBoolean("channel.Say.log", true); cfg.getString("channel.Say.filters", "Say"); cfg.getBoolean("channel.Tell.enabled", true); cfg.getBoolean("channel.Tell.command", true); cfg.getBoolean("channel.Tell.log", false); cfg.getString("channel.Tell.filters", "Tell"); cfg.getBoolean("channel.Reply.enabled", true); cfg.getBoolean("channel.Reply.command", true); cfg.getBoolean("channel.Reply.log", false); cfg.getString("channel.Reply.filters", "Reply"); cfg.getBoolean("channel.Party.enabled", false); cfg.getBoolean("channel.Party.command", false); cfg.getBoolean("channel.Party.log", false); cfg.getString("channel.Party.filters", "Party"); } for (String channel : cfg.getKeys("channel")) { // Add all channels, even disabled ones - check is dynamic Chat.addChannel(channel); } } @Override public void onDisable() { // mmo.autoUpdate(); MMO.mmoChat = false; super.onDisable(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) { return false; } Player player = (Player) sender; if (command.getName().equalsIgnoreCase("channel")) { String channel; if (args.length > 0 && (channel = Chat.findChannel(args[0])) != null) { if (args.length > 1) { if (args[1].equalsIgnoreCase("hide")) { Chat.hideChannel(player, channel); return true; } else if (args[1].equalsIgnoreCase("show")) { Chat.hideChannel(player, channel); return true; } } else { if (Chat.setChannel(player, channel)) { sendMessage(player, "Channel changed to %s", Chat.getChannel(player)); } else { sendMessage(player, "Unknown channel"); } return true; } } } return false; } @Override public List<Class<?>> getDatabaseClasses() { List<Class<?>> list = new ArrayList<Class<?>>(); list.add(ChatDB.class); return list; } public class mmoPlayerListener extends PlayerListener { @Override public void onPlayerChat(PlayerChatEvent event) { if (Chat.doChat(null, event.getPlayer(), event.getMessage())) { event.setCancelled(true); } } @Override public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String message = event.getMessage(); String channel = MMO.firstWord(message); if (channel != null && !channel.isEmpty()) { channel = channel.substring(1); if ("me".equalsIgnoreCase(channel) && Chat.doChat(null, event.getPlayer(), message)) { event.setCancelled(true); } else if ((channel = Chat.findChannel(channel)) != null && cfg.getBoolean("channel." + channel + ".command", true) && Chat.doChat(channel, event.getPlayer(), MMO.removeFirstWord(message))) { event.setCancelled(true); } } } } }
true
true
public void loadConfiguration(Configuration cfg) { cfg.getString("default_channel", "Chat"); if (cfg.getKeys("channel").isEmpty()) { cfg.getBoolean("channel.Chat.enabled", true); cfg.getBoolean("channel.Chat.command", true); cfg.getBoolean("channel.Chat.log", true); cfg.getString("channel.Chat.filters", "Server"); cfg.getBoolean("channel.Shout.enabled", true); cfg.getBoolean("channel.Shout.command", true); cfg.getBoolean("channel.Shout.log", true); cfg.getString("channel.Shout.filters", "World"); cfg.getBoolean("channel.Yell.enabled", true); cfg.getBoolean("channel.Yell.command", true); cfg.getBoolean("channel.Yell.log", true); cfg.getString("channel.Yell.filters", "Yell"); cfg.getBoolean("channel.Say.enabled", true); cfg.getBoolean("channel.Say.command", true); cfg.getBoolean("channel.Say.log", true); cfg.getString("channel.Say.filters", "Say"); cfg.getBoolean("channel.Tell.enabled", true); cfg.getBoolean("channel.Tell.command", true); cfg.getBoolean("channel.Tell.log", false); cfg.getString("channel.Tell.filters", "Tell"); cfg.getBoolean("channel.Reply.enabled", true); cfg.getBoolean("channel.Reply.command", true); cfg.getBoolean("channel.Reply.log", false); cfg.getString("channel.Reply.filters", "Reply"); cfg.getBoolean("channel.Party.enabled", false); cfg.getBoolean("channel.Party.command", false); cfg.getBoolean("channel.Party.log", false); cfg.getString("channel.Party.filters", "Party"); } for (String channel : cfg.getKeys("channel")) { // Add all channels, even disabled ones - check is dynamic Chat.addChannel(channel); } }
public void loadConfiguration(Configuration cfg) { cfg.getString("default_channel", "Chat"); List<String> keys = cfg.getKeys("channel"); if (keys == null || keys.isEmpty()) { cfg.getBoolean("channel.Chat.enabled", true); cfg.getBoolean("channel.Chat.command", true); cfg.getBoolean("channel.Chat.log", true); cfg.getString("channel.Chat.filters", "Server"); cfg.getBoolean("channel.Shout.enabled", true); cfg.getBoolean("channel.Shout.command", true); cfg.getBoolean("channel.Shout.log", true); cfg.getString("channel.Shout.filters", "World"); cfg.getBoolean("channel.Yell.enabled", true); cfg.getBoolean("channel.Yell.command", true); cfg.getBoolean("channel.Yell.log", true); cfg.getString("channel.Yell.filters", "Yell"); cfg.getBoolean("channel.Say.enabled", true); cfg.getBoolean("channel.Say.command", true); cfg.getBoolean("channel.Say.log", true); cfg.getString("channel.Say.filters", "Say"); cfg.getBoolean("channel.Tell.enabled", true); cfg.getBoolean("channel.Tell.command", true); cfg.getBoolean("channel.Tell.log", false); cfg.getString("channel.Tell.filters", "Tell"); cfg.getBoolean("channel.Reply.enabled", true); cfg.getBoolean("channel.Reply.command", true); cfg.getBoolean("channel.Reply.log", false); cfg.getString("channel.Reply.filters", "Reply"); cfg.getBoolean("channel.Party.enabled", false); cfg.getBoolean("channel.Party.command", false); cfg.getBoolean("channel.Party.log", false); cfg.getString("channel.Party.filters", "Party"); } for (String channel : cfg.getKeys("channel")) { // Add all channels, even disabled ones - check is dynamic Chat.addChannel(channel); } }
diff --git a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java index 2492f6cb..e8309910 100644 --- a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java +++ b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/linking/EMLinkingService.java @@ -1,424 +1,424 @@ package org.osate.xtext.aadl2.errormodel.linking; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.xtext.linking.impl.IllegalNodeException; import org.eclipse.xtext.nodemodel.INode; import org.osate.aadl2.Aadl2Package; import org.osate.aadl2.AadlPackage; import org.osate.aadl2.AnnexLibrary; import org.osate.aadl2.Classifier; import org.osate.aadl2.ComponentClassifier; import org.osate.aadl2.ContainedNamedElement; import org.osate.aadl2.ContainmentPathElement; import org.osate.aadl2.DirectionType; import org.osate.aadl2.Element; import org.osate.aadl2.Feature; import org.osate.aadl2.FeatureGroup; import org.osate.aadl2.FeatureGroupType; import org.osate.aadl2.NamedElement; import org.osate.aadl2.PackageSection; import org.osate.aadl2.Subcomponent; import org.osate.aadl2.modelsupport.util.AadlUtil; import org.osate.aadl2.util.Aadl2Util; import org.osate.xtext.aadl2.errormodel.errorModel.ConditionElement; import org.osate.xtext.aadl2.errormodel.errorModel.ConditionExpression; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateMachine; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorTransition; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorDetection; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelLibrary; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelPackage; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorTypes; import org.osate.xtext.aadl2.errormodel.errorModel.FeatureorPPReference; import org.osate.xtext.aadl2.errormodel.errorModel.RecoverEvent; import org.osate.xtext.aadl2.errormodel.errorModel.SubcomponentElement; import org.osate.xtext.aadl2.errormodel.errorModel.TypeMappingSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeTransformationSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeUseContext; import org.osate.xtext.aadl2.errormodel.util.EMV2Util; import org.osate.xtext.aadl2.properties.linking.PropertiesLinkingService; import org.osate.xtext.aadl2.properties.util.EMFIndexRetrieval; public class EMLinkingService extends PropertiesLinkingService { public EMLinkingService(){ super(); } /** * find the closest subcomponent classifier before the element at idx. * @param list * @param idx * @return */ private ComponentClassifier getLastComponentClassifier(EList<ContainmentPathElement> list, int idx){ idx = idx -1; while (idx >= 0){ NamedElement el = list.get(idx).getNamedElement(); if (el instanceof Subcomponent){ return((Subcomponent)el).getAllClassifier(); } idx = idx -1; } return null; } @Override public List<EObject> getLinkedObjects(EObject context, EReference reference, INode node) throws IllegalNodeException { final EClass requiredType = reference.getEReferenceType(); EObject searchResult = null; if (requiredType == null) return Collections.<EObject> emptyList(); Element cxt = (Element) context; final String name = getCrossRefNodeAsString(node); if (Aadl2Package.eINSTANCE.getNamedElement() == requiredType) { // containment path element if (context instanceof ContainmentPathElement) { ContainedNamedElement path = (ContainedNamedElement) context.eContainer(); EList<ContainmentPathElement> list = path .getContainmentPathElements(); int idx = list.indexOf(context); Element cxtElement = (Element)context; FeatureGroupType cxtFGT = null; String epFGPrefix = ""; if (idx > 0) { // use the last component on the path as context for lookup of error model elements ComponentClassifier cxtPathComp = getLastComponentClassifier(list,idx); if (cxtPathComp != null) cxtElement = cxtPathComp; // deal with feature groups and features as identifiers of error propagations NamedElement ne = list.get(idx - 1).getNamedElement(); if (ne instanceof FeatureGroup) { FeatureGroup fg = (FeatureGroup) ne; cxtFGT = fg.getAllFeatureGroupType(); epFGPrefix = fg.getName()+"."; if (idx > 1){ // there is an idx - 2 int cnt = idx -2; NamedElement prevne = list.get(cnt).getNamedElement(); while (cnt >= 0){ if ( prevne instanceof FeatureGroup){ epFGPrefix = epFGPrefix+((FeatureGroup)prevne).getName()+"."; } else if (prevne instanceof ErrorPropagation){ epFGPrefix = epFGPrefix +EMV2Util.getPrintName((ErrorPropagation)prevne)+"."; break; } else { break; } cnt = cnt -1; } } } else if (ne instanceof ErrorPropagation){ // we resolved previous entry to an error propagation // It may represent the context of the feature, e.g., when both the fg and the feature have an error propagation EList<FeatureorPPReference> flist = ((ErrorPropagation)ne).getFeatureorPPRefs(); if (!flist.isEmpty()){ FeatureorPPReference fop = flist.get(flist.size()-1); if (fop instanceof FeatureGroup){ cxtFGT = ((FeatureGroup) fop).getAllFeatureGroupType(); } } epFGPrefix = EMV2Util.getPrintName((ErrorPropagation)ne)+"."; } } // find annex subclause as context for error model identifier lookup if (!Aadl2Util.isNull(cxtElement)){ - searchResult = findErrorType(cxtElement, name); - if (searchResult != null) return Collections.singletonList(searchResult); - searchResult = findTypeSet(cxtElement, name); - if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, epFGPrefix+name,DirectionType.OUT); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, epFGPrefix+name,DirectionType.IN); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findPropagationPoint(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorFlow(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorEvent(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorState(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorTransition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorDetection(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findOutgoingPropagationCondition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); if (cxtFGT != null){ // if previous element was feature group, look up next feature group in its type // we do not want to return features as they should get resolved to an error propagation NamedElement finding = cxtFGT.findNamedElement(name); if (finding instanceof FeatureGroup) searchResult = finding; } if (cxtElement instanceof Classifier) { // look up subcomponent in classifier of previous subcomponent, or feature group // we do not want to return features as they should get resolved to an error propagation NamedElement finding = ((Classifier)cxtElement).findNamedElement(name); if (finding instanceof Subcomponent || finding instanceof FeatureGroup) searchResult = finding; } if (searchResult != null) return Collections.singletonList(searchResult); + searchResult = findErrorType(cxtElement, name); + if (searchResult != null) return Collections.singletonList(searchResult); + searchResult = findTypeSet(cxtElement, name); + if (searchResult != null) return Collections.singletonList(searchResult); } } else if (context instanceof RecoverEvent){ Classifier ns = AadlUtil.getContainingClassifier(context); searchResult = ns.findNamedElement(name); } else if (context instanceof FeatureorPPReference){ ErrorPropagation ep = (ErrorPropagation) context.eContainer(); EList<FeatureorPPReference> frefs = ep.getFeatureorPPRefs(); int idx = frefs.indexOf(context); Classifier cl=null; if (idx > 0){ FeatureorPPReference enclosingfg = frefs.get(idx-1); NamedElement fg = enclosingfg.getFeatureorPP(); if (fg instanceof FeatureGroup){ cl = ((FeatureGroup)fg).getFeatureGroupType(); } } else { cl = AadlUtil.getContainingClassifier(context); } if (cl != null){ NamedElement ne = cl.findNamedElement(name); if (ne instanceof Feature){ searchResult = ne; } else { // find propagation point searchResult = EMV2Util.findPropagationPoint(cl,name); } } } } else if (ErrorModelPackage.eINSTANCE.getErrorType() == requiredType) { searchResult = findErrorType(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getTypeSet() == requiredType) { searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorTypes() == requiredType) { searchResult = findErrorType(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getPropagationPoint() == requiredType) { // find propagation point Classifier cl = AadlUtil.getContainingClassifier(context); searchResult = EMV2Util.findPropagationPoint(cl,name); } else if (ErrorModelPackage.eINSTANCE.getErrorModelLibrary() == requiredType) { // first look it up in global index EObject gobj = getIndexedObject(context, reference, name); if (gobj != null ){ if( gobj.eClass() == requiredType){ return Collections.singletonList(gobj); } else { System.out.println("Global lookup of type did not match "+name); } } searchResult = findErrorModelLibrary(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateOrTypeSet() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorPropagation() == requiredType) { if (reference.getName().equalsIgnoreCase("outgoing")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.OUT); } else if (reference.getName().equalsIgnoreCase("incoming")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); } else { searchResult = EMV2Util.findErrorPropagation(cxt, name,null); } } else if (ErrorModelPackage.eINSTANCE.getTypeMappingSet() == requiredType) { searchResult = findTypeMappingSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getTypeTransformationSet() == requiredType) { searchResult = findTypeTransformationSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateMachine() == requiredType) { searchResult = findErrorBehaviorStateMachine(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorState() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState((Element)context, name); } else if (ErrorModelPackage.eINSTANCE.getEventOrPropagation() == requiredType) { searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); if (searchResult == null ){ if (context instanceof ConditionExpression && (EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorDetection || EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorBehaviorTransition)){ // find it only for transitions searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } } } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorEvent() == requiredType) { searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorTransition() == requiredType) { searchResult = EMV2Util.findErrorBehaviorTransition(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorFlow() == requiredType) { searchResult = EMV2Util.findErrorFlow(cxt.getContainingClassifier(), name); } else if (Aadl2Package.eINSTANCE.getSubcomponent()==requiredType) { // } else if (Aadl2Package.eINSTANCE.getSubcomponent().isSuperTypeOf(requiredType)) { if (context instanceof SubcomponentElement){ ConditionElement ce = (ConditionElement)context.eContainer(); EList<SubcomponentElement> sublist = ce.getSubcomponents(); int idx = sublist.indexOf(context); Classifier ns = AadlUtil.getContainingClassifier(context); if (idx > 0) { SubcomponentElement se = sublist.get(idx-1); Subcomponent subcomponent = se.getSubcomponent(); ns = subcomponent.getAllClassifier(); } EObject res = ns.findNamedElement(name); if (res instanceof Subcomponent) { searchResult = res; } } } if (searchResult != null) { return Collections.singletonList(searchResult); } return Collections.<EObject> emptyList(); } /** * find the error model library. The String name refers to the package and the default EML name is added ("emv2") * @param context context of search to identify package and EML * @param name * @return */ public ErrorModelLibrary findErrorModelLibrary(EObject context, String name){ ErrorModelLibrary eml = (ErrorModelLibrary) EMFIndexRetrieval.getEObjectOfType(context, ErrorModelPackage.eINSTANCE.getErrorModelLibrary(), name+"::"+"emv2"); if (eml != null) return eml; AadlPackage ap = findAadlPackageReference(name, AadlUtil.getContainingPackageSection(context)); if (ap == null) return null; PackageSection ps = ap.getOwnedPublicSection(); EList<AnnexLibrary>all=ps.getOwnedAnnexLibraries(); for (AnnexLibrary al : all){ if (al instanceof ErrorModelLibrary){ return (ErrorModelLibrary)al; } } return null; } public TypeMappingSet findTypeMappingSet(EObject context, String name){ ErrorModelLibrary eml = findErrorModelLibrary(context, EMV2Util.getPackageName(name)); if (eml != null){ EList<TypeMappingSet> tmsl= eml.getMappings(); for (TypeMappingSet tms : tmsl){ if (EMV2Util.getItemNameWithoutQualification(name).equalsIgnoreCase(tms.getName())) return tms; } } return null; } public TypeTransformationSet findTypeTransformationSet(EObject context, String name){ ErrorModelLibrary eml = findErrorModelLibrary(context, EMV2Util.getPackageName(name)); if (eml != null){ EList<TypeTransformationSet> tmsl= eml.getTransformations(); for (TypeTransformationSet tms : tmsl){ if (EMV2Util.getItemNameWithoutQualification(name).equalsIgnoreCase(tms.getName())) return tms; } } return null; } public ErrorBehaviorStateMachine findErrorBehaviorStateMachine(EObject context, String name){ ErrorModelLibrary eml = findErrorModelLibrary(context, EMV2Util.getPackageName(name)); if (eml != null){ EList<ErrorBehaviorStateMachine> ebsml= eml.getBehaviors(); for (ErrorBehaviorStateMachine ebsm : ebsml){ if (EMV2Util.getItemNameWithoutQualification(name).equalsIgnoreCase(ebsm.getName())) return ebsm; } } return null; } public ErrorType findErrorType(Element context, String typeName){ return (ErrorType)findEMLNamedTypeElement(context, typeName, ErrorModelPackage.eINSTANCE.getErrorType()); } public TypeSet findTypeSet(Element context, String typeName){ return (TypeSet)findEMLNamedTypeElement(context, typeName, ErrorModelPackage.eINSTANCE.getTypeSet()); } /** * find an error type or type set * The context is either an errormodel element, or a classifier as context of a containment path. * @param context * @param qualTypeName * @param eclass * @return */ public EObject findEMLNamedTypeElement(Element context, String qualTypeName, EClass eclass){ String packName = EMV2Util.getPackageName(qualTypeName); String typeName = EMV2Util.getItemNameWithoutQualification(qualTypeName); if (packName != null){ // qualified reference; look there only ErrorModelLibrary eml = findErrorModelLibrary(context, packName); // PHF: change to findNamedElementInThisEML if we do not make inherited names externally visible return findEMLNamedTypeElement(eml, typeName, eclass); } ErrorModelLibrary owneml = EMV2Util.getContainingErrorModelLibrary(context); TypeUseContext tuns = EMV2Util.getContainingTypeUseContext(context); List<ErrorModelLibrary> otheremls = null;; if (tuns == null && context instanceof Classifier){ otheremls = EMV2Util.getErrorModelSubclauseWithUseTypes((Classifier)context); } else if (tuns != null) { // we are in a transformation set, mapping set etc. otheremls = EMV2Util.getUseTypes(tuns); } else if (owneml != null){ // lookup in own EML if we are inside an ErrorModelLibrary EObject res = findNamedTypeElementInThisEML(owneml, typeName, eclass); if (res != null) return res; otheremls = owneml.getExtends(); } if (otheremls != null){ for (ErrorModelLibrary etll: otheremls){ // PHF: change to findNamedElementInThisEML if we do not make inherited names externally visible EObject res = findEMLNamedTypeElement(etll, typeName, eclass); if (res != null) { return res; } } } return null; } public EObject findNamedTypeElementInThisEML(ErrorModelLibrary eml, String typeName, EClass eclass){ if (eml == null) return null; if (eclass == ErrorModelPackage.eINSTANCE.getErrorType()){ EList<ErrorType> elt = eml.getTypes(); for (ErrorType ets : elt){ if (typeName.equalsIgnoreCase(ets.getName())) return ets; } } else { EList<TypeSet> elt = eml.getTypesets(); for (TypeSet ets : elt){ if (typeName.equalsIgnoreCase(ets.getName())) return ets; } } return null; } }
false
true
public List<EObject> getLinkedObjects(EObject context, EReference reference, INode node) throws IllegalNodeException { final EClass requiredType = reference.getEReferenceType(); EObject searchResult = null; if (requiredType == null) return Collections.<EObject> emptyList(); Element cxt = (Element) context; final String name = getCrossRefNodeAsString(node); if (Aadl2Package.eINSTANCE.getNamedElement() == requiredType) { // containment path element if (context instanceof ContainmentPathElement) { ContainedNamedElement path = (ContainedNamedElement) context.eContainer(); EList<ContainmentPathElement> list = path .getContainmentPathElements(); int idx = list.indexOf(context); Element cxtElement = (Element)context; FeatureGroupType cxtFGT = null; String epFGPrefix = ""; if (idx > 0) { // use the last component on the path as context for lookup of error model elements ComponentClassifier cxtPathComp = getLastComponentClassifier(list,idx); if (cxtPathComp != null) cxtElement = cxtPathComp; // deal with feature groups and features as identifiers of error propagations NamedElement ne = list.get(idx - 1).getNamedElement(); if (ne instanceof FeatureGroup) { FeatureGroup fg = (FeatureGroup) ne; cxtFGT = fg.getAllFeatureGroupType(); epFGPrefix = fg.getName()+"."; if (idx > 1){ // there is an idx - 2 int cnt = idx -2; NamedElement prevne = list.get(cnt).getNamedElement(); while (cnt >= 0){ if ( prevne instanceof FeatureGroup){ epFGPrefix = epFGPrefix+((FeatureGroup)prevne).getName()+"."; } else if (prevne instanceof ErrorPropagation){ epFGPrefix = epFGPrefix +EMV2Util.getPrintName((ErrorPropagation)prevne)+"."; break; } else { break; } cnt = cnt -1; } } } else if (ne instanceof ErrorPropagation){ // we resolved previous entry to an error propagation // It may represent the context of the feature, e.g., when both the fg and the feature have an error propagation EList<FeatureorPPReference> flist = ((ErrorPropagation)ne).getFeatureorPPRefs(); if (!flist.isEmpty()){ FeatureorPPReference fop = flist.get(flist.size()-1); if (fop instanceof FeatureGroup){ cxtFGT = ((FeatureGroup) fop).getAllFeatureGroupType(); } } epFGPrefix = EMV2Util.getPrintName((ErrorPropagation)ne)+"."; } } // find annex subclause as context for error model identifier lookup if (!Aadl2Util.isNull(cxtElement)){ searchResult = findErrorType(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = findTypeSet(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, epFGPrefix+name,DirectionType.OUT); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, epFGPrefix+name,DirectionType.IN); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findPropagationPoint(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorFlow(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorEvent(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorState(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorTransition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorDetection(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findOutgoingPropagationCondition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); if (cxtFGT != null){ // if previous element was feature group, look up next feature group in its type // we do not want to return features as they should get resolved to an error propagation NamedElement finding = cxtFGT.findNamedElement(name); if (finding instanceof FeatureGroup) searchResult = finding; } if (cxtElement instanceof Classifier) { // look up subcomponent in classifier of previous subcomponent, or feature group // we do not want to return features as they should get resolved to an error propagation NamedElement finding = ((Classifier)cxtElement).findNamedElement(name); if (finding instanceof Subcomponent || finding instanceof FeatureGroup) searchResult = finding; } if (searchResult != null) return Collections.singletonList(searchResult); } } else if (context instanceof RecoverEvent){ Classifier ns = AadlUtil.getContainingClassifier(context); searchResult = ns.findNamedElement(name); } else if (context instanceof FeatureorPPReference){ ErrorPropagation ep = (ErrorPropagation) context.eContainer(); EList<FeatureorPPReference> frefs = ep.getFeatureorPPRefs(); int idx = frefs.indexOf(context); Classifier cl=null; if (idx > 0){ FeatureorPPReference enclosingfg = frefs.get(idx-1); NamedElement fg = enclosingfg.getFeatureorPP(); if (fg instanceof FeatureGroup){ cl = ((FeatureGroup)fg).getFeatureGroupType(); } } else { cl = AadlUtil.getContainingClassifier(context); } if (cl != null){ NamedElement ne = cl.findNamedElement(name); if (ne instanceof Feature){ searchResult = ne; } else { // find propagation point searchResult = EMV2Util.findPropagationPoint(cl,name); } } } } else if (ErrorModelPackage.eINSTANCE.getErrorType() == requiredType) { searchResult = findErrorType(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getTypeSet() == requiredType) { searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorTypes() == requiredType) { searchResult = findErrorType(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getPropagationPoint() == requiredType) { // find propagation point Classifier cl = AadlUtil.getContainingClassifier(context); searchResult = EMV2Util.findPropagationPoint(cl,name); } else if (ErrorModelPackage.eINSTANCE.getErrorModelLibrary() == requiredType) { // first look it up in global index EObject gobj = getIndexedObject(context, reference, name); if (gobj != null ){ if( gobj.eClass() == requiredType){ return Collections.singletonList(gobj); } else { System.out.println("Global lookup of type did not match "+name); } } searchResult = findErrorModelLibrary(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateOrTypeSet() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorPropagation() == requiredType) { if (reference.getName().equalsIgnoreCase("outgoing")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.OUT); } else if (reference.getName().equalsIgnoreCase("incoming")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); } else { searchResult = EMV2Util.findErrorPropagation(cxt, name,null); } } else if (ErrorModelPackage.eINSTANCE.getTypeMappingSet() == requiredType) { searchResult = findTypeMappingSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getTypeTransformationSet() == requiredType) { searchResult = findTypeTransformationSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateMachine() == requiredType) { searchResult = findErrorBehaviorStateMachine(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorState() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState((Element)context, name); } else if (ErrorModelPackage.eINSTANCE.getEventOrPropagation() == requiredType) { searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); if (searchResult == null ){ if (context instanceof ConditionExpression && (EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorDetection || EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorBehaviorTransition)){ // find it only for transitions searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } } } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorEvent() == requiredType) { searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorTransition() == requiredType) { searchResult = EMV2Util.findErrorBehaviorTransition(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorFlow() == requiredType) { searchResult = EMV2Util.findErrorFlow(cxt.getContainingClassifier(), name); } else if (Aadl2Package.eINSTANCE.getSubcomponent()==requiredType) { // } else if (Aadl2Package.eINSTANCE.getSubcomponent().isSuperTypeOf(requiredType)) { if (context instanceof SubcomponentElement){ ConditionElement ce = (ConditionElement)context.eContainer(); EList<SubcomponentElement> sublist = ce.getSubcomponents(); int idx = sublist.indexOf(context); Classifier ns = AadlUtil.getContainingClassifier(context); if (idx > 0) { SubcomponentElement se = sublist.get(idx-1); Subcomponent subcomponent = se.getSubcomponent(); ns = subcomponent.getAllClassifier(); } EObject res = ns.findNamedElement(name); if (res instanceof Subcomponent) { searchResult = res; } } } if (searchResult != null) { return Collections.singletonList(searchResult); } return Collections.<EObject> emptyList(); }
public List<EObject> getLinkedObjects(EObject context, EReference reference, INode node) throws IllegalNodeException { final EClass requiredType = reference.getEReferenceType(); EObject searchResult = null; if (requiredType == null) return Collections.<EObject> emptyList(); Element cxt = (Element) context; final String name = getCrossRefNodeAsString(node); if (Aadl2Package.eINSTANCE.getNamedElement() == requiredType) { // containment path element if (context instanceof ContainmentPathElement) { ContainedNamedElement path = (ContainedNamedElement) context.eContainer(); EList<ContainmentPathElement> list = path .getContainmentPathElements(); int idx = list.indexOf(context); Element cxtElement = (Element)context; FeatureGroupType cxtFGT = null; String epFGPrefix = ""; if (idx > 0) { // use the last component on the path as context for lookup of error model elements ComponentClassifier cxtPathComp = getLastComponentClassifier(list,idx); if (cxtPathComp != null) cxtElement = cxtPathComp; // deal with feature groups and features as identifiers of error propagations NamedElement ne = list.get(idx - 1).getNamedElement(); if (ne instanceof FeatureGroup) { FeatureGroup fg = (FeatureGroup) ne; cxtFGT = fg.getAllFeatureGroupType(); epFGPrefix = fg.getName()+"."; if (idx > 1){ // there is an idx - 2 int cnt = idx -2; NamedElement prevne = list.get(cnt).getNamedElement(); while (cnt >= 0){ if ( prevne instanceof FeatureGroup){ epFGPrefix = epFGPrefix+((FeatureGroup)prevne).getName()+"."; } else if (prevne instanceof ErrorPropagation){ epFGPrefix = epFGPrefix +EMV2Util.getPrintName((ErrorPropagation)prevne)+"."; break; } else { break; } cnt = cnt -1; } } } else if (ne instanceof ErrorPropagation){ // we resolved previous entry to an error propagation // It may represent the context of the feature, e.g., when both the fg and the feature have an error propagation EList<FeatureorPPReference> flist = ((ErrorPropagation)ne).getFeatureorPPRefs(); if (!flist.isEmpty()){ FeatureorPPReference fop = flist.get(flist.size()-1); if (fop instanceof FeatureGroup){ cxtFGT = ((FeatureGroup) fop).getAllFeatureGroupType(); } } epFGPrefix = EMV2Util.getPrintName((ErrorPropagation)ne)+"."; } } // find annex subclause as context for error model identifier lookup if (!Aadl2Util.isNull(cxtElement)){ searchResult = EMV2Util.findErrorPropagation(cxtElement, epFGPrefix+name,DirectionType.OUT); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorPropagation(cxtElement, epFGPrefix+name,DirectionType.IN); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findPropagationPoint(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorFlow(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorEvent(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorState(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorBehaviorTransition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findErrorDetection(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = EMV2Util.findOutgoingPropagationCondition(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); if (cxtFGT != null){ // if previous element was feature group, look up next feature group in its type // we do not want to return features as they should get resolved to an error propagation NamedElement finding = cxtFGT.findNamedElement(name); if (finding instanceof FeatureGroup) searchResult = finding; } if (cxtElement instanceof Classifier) { // look up subcomponent in classifier of previous subcomponent, or feature group // we do not want to return features as they should get resolved to an error propagation NamedElement finding = ((Classifier)cxtElement).findNamedElement(name); if (finding instanceof Subcomponent || finding instanceof FeatureGroup) searchResult = finding; } if (searchResult != null) return Collections.singletonList(searchResult); searchResult = findErrorType(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); searchResult = findTypeSet(cxtElement, name); if (searchResult != null) return Collections.singletonList(searchResult); } } else if (context instanceof RecoverEvent){ Classifier ns = AadlUtil.getContainingClassifier(context); searchResult = ns.findNamedElement(name); } else if (context instanceof FeatureorPPReference){ ErrorPropagation ep = (ErrorPropagation) context.eContainer(); EList<FeatureorPPReference> frefs = ep.getFeatureorPPRefs(); int idx = frefs.indexOf(context); Classifier cl=null; if (idx > 0){ FeatureorPPReference enclosingfg = frefs.get(idx-1); NamedElement fg = enclosingfg.getFeatureorPP(); if (fg instanceof FeatureGroup){ cl = ((FeatureGroup)fg).getFeatureGroupType(); } } else { cl = AadlUtil.getContainingClassifier(context); } if (cl != null){ NamedElement ne = cl.findNamedElement(name); if (ne instanceof Feature){ searchResult = ne; } else { // find propagation point searchResult = EMV2Util.findPropagationPoint(cl,name); } } } } else if (ErrorModelPackage.eINSTANCE.getErrorType() == requiredType) { searchResult = findErrorType(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getTypeSet() == requiredType) { searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorTypes() == requiredType) { searchResult = findErrorType(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getPropagationPoint() == requiredType) { // find propagation point Classifier cl = AadlUtil.getContainingClassifier(context); searchResult = EMV2Util.findPropagationPoint(cl,name); } else if (ErrorModelPackage.eINSTANCE.getErrorModelLibrary() == requiredType) { // first look it up in global index EObject gobj = getIndexedObject(context, reference, name); if (gobj != null ){ if( gobj.eClass() == requiredType){ return Collections.singletonList(gobj); } else { System.out.println("Global lookup of type did not match "+name); } } searchResult = findErrorModelLibrary(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateOrTypeSet() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState(cxt, name); if (searchResult == null) searchResult = findTypeSet(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorPropagation() == requiredType) { if (reference.getName().equalsIgnoreCase("outgoing")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.OUT); } else if (reference.getName().equalsIgnoreCase("incoming")){ searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); } else { searchResult = EMV2Util.findErrorPropagation(cxt, name,null); } } else if (ErrorModelPackage.eINSTANCE.getTypeMappingSet() == requiredType) { searchResult = findTypeMappingSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getTypeTransformationSet() == requiredType) { searchResult = findTypeTransformationSet(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorStateMachine() == requiredType) { searchResult = findErrorBehaviorStateMachine(context, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorState() == requiredType) { searchResult = EMV2Util.findErrorBehaviorState((Element)context, name); } else if (ErrorModelPackage.eINSTANCE.getEventOrPropagation() == requiredType) { searchResult = EMV2Util.findErrorPropagation(cxt, name,DirectionType.IN); if (searchResult == null ){ if (context instanceof ConditionExpression && (EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorDetection || EMV2Util.getConditionExpressionContext((ConditionExpression)context) instanceof ErrorBehaviorTransition)){ // find it only for transitions searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } } } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorEvent() == requiredType) { searchResult = EMV2Util.findErrorBehaviorEvent(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorBehaviorTransition() == requiredType) { searchResult = EMV2Util.findErrorBehaviorTransition(cxt, name); } else if (ErrorModelPackage.eINSTANCE.getErrorFlow() == requiredType) { searchResult = EMV2Util.findErrorFlow(cxt.getContainingClassifier(), name); } else if (Aadl2Package.eINSTANCE.getSubcomponent()==requiredType) { // } else if (Aadl2Package.eINSTANCE.getSubcomponent().isSuperTypeOf(requiredType)) { if (context instanceof SubcomponentElement){ ConditionElement ce = (ConditionElement)context.eContainer(); EList<SubcomponentElement> sublist = ce.getSubcomponents(); int idx = sublist.indexOf(context); Classifier ns = AadlUtil.getContainingClassifier(context); if (idx > 0) { SubcomponentElement se = sublist.get(idx-1); Subcomponent subcomponent = se.getSubcomponent(); ns = subcomponent.getAllClassifier(); } EObject res = ns.findNamedElement(name); if (res instanceof Subcomponent) { searchResult = res; } } } if (searchResult != null) { return Collections.singletonList(searchResult); } return Collections.<EObject> emptyList(); }
diff --git a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnDiffViewer.java b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnDiffViewer.java index d2d847637..0636d1a10 100644 --- a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnDiffViewer.java +++ b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnDiffViewer.java @@ -1,153 +1,153 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.DefaultSVNDiffGenerator; import org.tmatesoft.svn.core.wc.ISVNDiffGenerator; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNRevision; import sonia.scm.util.AssertUtil; import sonia.scm.util.Util; //~--- JDK imports ------------------------------------------------------------ import java.io.File; import java.io.IOException; import java.io.OutputStream; /** * * @author Sebastian Sdorra */ public class SvnDiffViewer implements DiffViewer { /** the logger for SvnDiffViewer */ private static final Logger logger = LoggerFactory.getLogger(SvnDiffViewer.class); //~--- constructors --------------------------------------------------------- /** * Constructs ... * * * @param directory */ public SvnDiffViewer(File directory) { this.directory = directory; } /** * Constructs ... * * * @param handler * @param repository */ public SvnDiffViewer(SvnRepositoryHandler handler, Repository repository) { this(handler.getDirectory(repository)); } //~--- get methods ---------------------------------------------------------- /** * Method description * * * @param revision * @param path * @param output * * @throws IOException * @throws RepositoryException */ @Override public void getDiff(String revision, String path, OutputStream output) throws IOException, RepositoryException { AssertUtil.assertIsNotEmpty(revision); AssertUtil.assertIsNotNull(output); try { SVNURL svnurl = SVNURL.fromFile(directory); if (Util.isNotEmpty(path)) { svnurl = svnurl.appendPath(path, true); } SVNClientManager clientManager = SVNClientManager.newInstance(); SVNDiffClient diffClient = clientManager.getDiffClient(); ISVNDiffGenerator diffGenerator = diffClient.getDiffGenerator(); if (diffGenerator == null) { diffGenerator = new DefaultSVNDiffGenerator(); } diffGenerator.setDiffAdded(true); diffGenerator.setDiffDeleted(true); diffClient.setDiffGenerator(diffGenerator); long currentRev = Long.parseLong(revision); diffClient.doDiff(svnurl, SVNRevision.HEAD, - SVNRevision.create(currentRev), - SVNRevision.create(currentRev - 1), SVNDepth.INFINITY, + SVNRevision.create(currentRev - 1), + SVNRevision.create(currentRev), SVNDepth.INFINITY, false, output); } catch (Exception ex) { logger.error("could not create blame view", ex); } } //~--- fields --------------------------------------------------------------- /** Field description */ private File directory; }
true
true
public void getDiff(String revision, String path, OutputStream output) throws IOException, RepositoryException { AssertUtil.assertIsNotEmpty(revision); AssertUtil.assertIsNotNull(output); try { SVNURL svnurl = SVNURL.fromFile(directory); if (Util.isNotEmpty(path)) { svnurl = svnurl.appendPath(path, true); } SVNClientManager clientManager = SVNClientManager.newInstance(); SVNDiffClient diffClient = clientManager.getDiffClient(); ISVNDiffGenerator diffGenerator = diffClient.getDiffGenerator(); if (diffGenerator == null) { diffGenerator = new DefaultSVNDiffGenerator(); } diffGenerator.setDiffAdded(true); diffGenerator.setDiffDeleted(true); diffClient.setDiffGenerator(diffGenerator); long currentRev = Long.parseLong(revision); diffClient.doDiff(svnurl, SVNRevision.HEAD, SVNRevision.create(currentRev), SVNRevision.create(currentRev - 1), SVNDepth.INFINITY, false, output); } catch (Exception ex) { logger.error("could not create blame view", ex); } }
public void getDiff(String revision, String path, OutputStream output) throws IOException, RepositoryException { AssertUtil.assertIsNotEmpty(revision); AssertUtil.assertIsNotNull(output); try { SVNURL svnurl = SVNURL.fromFile(directory); if (Util.isNotEmpty(path)) { svnurl = svnurl.appendPath(path, true); } SVNClientManager clientManager = SVNClientManager.newInstance(); SVNDiffClient diffClient = clientManager.getDiffClient(); ISVNDiffGenerator diffGenerator = diffClient.getDiffGenerator(); if (diffGenerator == null) { diffGenerator = new DefaultSVNDiffGenerator(); } diffGenerator.setDiffAdded(true); diffGenerator.setDiffDeleted(true); diffClient.setDiffGenerator(diffGenerator); long currentRev = Long.parseLong(revision); diffClient.doDiff(svnurl, SVNRevision.HEAD, SVNRevision.create(currentRev - 1), SVNRevision.create(currentRev), SVNDepth.INFINITY, false, output); } catch (Exception ex) { logger.error("could not create blame view", ex); } }
diff --git a/ChallengeSheet.java b/ChallengeSheet.java index 7610c11..51297c3 100644 --- a/ChallengeSheet.java +++ b/ChallengeSheet.java @@ -1,93 +1,93 @@ import java.util.*; import java.nio.file.*; import java.nio.charset.*; public class ChallengeSheet { public static void makeSheet() { Difficulty[] ds = { Difficulty.getEasyDifficulty(), Difficulty.getMediumDifficulty(), Difficulty.getHardDifficulty() }; Challenge[] cs = new Challenge[3]; { int found = 0; while (found != 3) { Challenge c = new Challenge(ds[found]); ArrayList<Operator> operators = c.getChallenge(); boolean fail = false; // Throw away bad Challenges that use the same operator twice in a row for (int i = 2; i < operators.size(); i++) { if (operators.get(i).getClass().equals(operators.get(i-1).getClass())) { fail = true; } } if (!fail) { cs[found++] = c; } } } int[] solutions = { cs[0].getSolution(), cs[1].getSolution(), cs[2].getSolution() }; // Open Files List<String> head = null; List<String> tail = null; List<String> chHead = null; List<String> chTail = null; try { Path headP = FileSystems.getDefault().getPath("tex", "head.tex"); Path tailP = FileSystems.getDefault().getPath("tex", "tail.tex"); Path chHeadP = FileSystems.getDefault().getPath("tex", "challengeBefore.tex"); Path chTailP = FileSystems.getDefault().getPath("tex", "challengeAfter.tex"); Charset charset = Charset.defaultCharset(); head = Files.readAllLines(headP, charset); tail = Files.readAllLines(tailP, charset); chHead = Files.readAllLines(chHeadP, charset); chTail = Files.readAllLines(chTailP, charset); } catch (Exception e) { e.printStackTrace(); } // Print Document for (String s : head) { System.out.println(s); } for (Challenge c : cs) { for (String s : chHead) { System.out.println(s); } for (Operator o : c.getChallenge()) { System.out.print(o.toTexString()); System.out.print(" & "); } System.out.println("\\textcolor{white}{?} \\\\"); for (String s : chTail) { System.out.println(s); } } System.out.println("\\begin{turn}{180}"); System.out.format("Lösungen: %d, %d, %d\n", solutions[0], solutions[1], solutions[2]); - System.out.println("\\end{turn}{180}"); + System.out.println("\\end{turn}"); for (String s : tail) { System.out.println(s); } } }
true
true
public static void makeSheet() { Difficulty[] ds = { Difficulty.getEasyDifficulty(), Difficulty.getMediumDifficulty(), Difficulty.getHardDifficulty() }; Challenge[] cs = new Challenge[3]; { int found = 0; while (found != 3) { Challenge c = new Challenge(ds[found]); ArrayList<Operator> operators = c.getChallenge(); boolean fail = false; // Throw away bad Challenges that use the same operator twice in a row for (int i = 2; i < operators.size(); i++) { if (operators.get(i).getClass().equals(operators.get(i-1).getClass())) { fail = true; } } if (!fail) { cs[found++] = c; } } } int[] solutions = { cs[0].getSolution(), cs[1].getSolution(), cs[2].getSolution() }; // Open Files List<String> head = null; List<String> tail = null; List<String> chHead = null; List<String> chTail = null; try { Path headP = FileSystems.getDefault().getPath("tex", "head.tex"); Path tailP = FileSystems.getDefault().getPath("tex", "tail.tex"); Path chHeadP = FileSystems.getDefault().getPath("tex", "challengeBefore.tex"); Path chTailP = FileSystems.getDefault().getPath("tex", "challengeAfter.tex"); Charset charset = Charset.defaultCharset(); head = Files.readAllLines(headP, charset); tail = Files.readAllLines(tailP, charset); chHead = Files.readAllLines(chHeadP, charset); chTail = Files.readAllLines(chTailP, charset); } catch (Exception e) { e.printStackTrace(); } // Print Document for (String s : head) { System.out.println(s); } for (Challenge c : cs) { for (String s : chHead) { System.out.println(s); } for (Operator o : c.getChallenge()) { System.out.print(o.toTexString()); System.out.print(" & "); } System.out.println("\\textcolor{white}{?} \\\\"); for (String s : chTail) { System.out.println(s); } } System.out.println("\\begin{turn}{180}"); System.out.format("Lösungen: %d, %d, %d\n", solutions[0], solutions[1], solutions[2]); System.out.println("\\end{turn}{180}"); for (String s : tail) { System.out.println(s); } }
public static void makeSheet() { Difficulty[] ds = { Difficulty.getEasyDifficulty(), Difficulty.getMediumDifficulty(), Difficulty.getHardDifficulty() }; Challenge[] cs = new Challenge[3]; { int found = 0; while (found != 3) { Challenge c = new Challenge(ds[found]); ArrayList<Operator> operators = c.getChallenge(); boolean fail = false; // Throw away bad Challenges that use the same operator twice in a row for (int i = 2; i < operators.size(); i++) { if (operators.get(i).getClass().equals(operators.get(i-1).getClass())) { fail = true; } } if (!fail) { cs[found++] = c; } } } int[] solutions = { cs[0].getSolution(), cs[1].getSolution(), cs[2].getSolution() }; // Open Files List<String> head = null; List<String> tail = null; List<String> chHead = null; List<String> chTail = null; try { Path headP = FileSystems.getDefault().getPath("tex", "head.tex"); Path tailP = FileSystems.getDefault().getPath("tex", "tail.tex"); Path chHeadP = FileSystems.getDefault().getPath("tex", "challengeBefore.tex"); Path chTailP = FileSystems.getDefault().getPath("tex", "challengeAfter.tex"); Charset charset = Charset.defaultCharset(); head = Files.readAllLines(headP, charset); tail = Files.readAllLines(tailP, charset); chHead = Files.readAllLines(chHeadP, charset); chTail = Files.readAllLines(chTailP, charset); } catch (Exception e) { e.printStackTrace(); } // Print Document for (String s : head) { System.out.println(s); } for (Challenge c : cs) { for (String s : chHead) { System.out.println(s); } for (Operator o : c.getChallenge()) { System.out.print(o.toTexString()); System.out.print(" & "); } System.out.println("\\textcolor{white}{?} \\\\"); for (String s : chTail) { System.out.println(s); } } System.out.println("\\begin{turn}{180}"); System.out.format("Lösungen: %d, %d, %d\n", solutions[0], solutions[1], solutions[2]); System.out.println("\\end{turn}"); for (String s : tail) { System.out.println(s); } }
diff --git a/skype-bot-core/src/main/java/org/zeroturnaround/skypebot/SkypeChatBot.java b/skype-bot-core/src/main/java/org/zeroturnaround/skypebot/SkypeChatBot.java index f0b9b5d..8c8443b 100644 --- a/skype-bot-core/src/main/java/org/zeroturnaround/skypebot/SkypeChatBot.java +++ b/skype-bot-core/src/main/java/org/zeroturnaround/skypebot/SkypeChatBot.java @@ -1,130 +1,130 @@ package org.zeroturnaround.skypebot; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import java.util.concurrent.Executors; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeroturnaround.skypebot.pid.PIDUtil; import org.zeroturnaround.skypebot.plugins.Plugins; import org.zeroturnaround.skypebot.web.WebServer; public class SkypeChatBot extends Thread { private static final Logger log = LoggerFactory.getLogger(SkypeChatBot.class); public static void main(String[] args) throws Exception { writePID(); initConfiguration(); initCommands(); startWebServer(); boolean success = startSkypeEngine(); if (!success) { log.error("Unable to log in. Exiting."); System.exit(1); } else { log.info("Logged in. All systems green."); } } private static void writePID() throws IOException { File f = new File("skype-bot.pid"); //FileUtils.writeStringToFile(f, PIDUtil.getPID()); } private static void initCommands() { Plugins.reload(); } public static boolean startSkypeEngine() throws InterruptedException { try { SkypeKitRuntime.init().start(); // sleep a bit to be sure Thread.sleep(3000); } catch (Exception e) { log.info("I was unable to start runtime myself. I'll assume that it is started somehow manually"); } SkypeEngine sEngine = new SkypeEngine(); sEngine.connect(); for (int i = 0; i < 3; i++) { if (sEngine.isConnected()) { break; } Thread.sleep(5000); } return sEngine.isConnected(); } public static void startWebServer() { Executors.newSingleThreadExecutor().execute(new WebServer()); } private static void initConfiguration() { String homeDir = System.getProperty("skypeBotHome", "."); Properties props = new Properties(); File propsFile = new File(new File(homeDir), "personal.properties"); try { if (propsFile.exists()) { props.load(new FileReader(propsFile)); } else { propsFile = new File("project.properties"); if (propsFile.exists()) { props.load(new FileReader(propsFile)); } } } catch (FileNotFoundException e) { throw new RuntimeException("Unable to read properties file " + propsFile.getAbsolutePath(), e); } catch (IOException e) { throw new RuntimeException("Unable to read properties file " + propsFile.getAbsolutePath(), e); } Configuration.props = props; Configuration.skypeUsername = props.getProperty("username", null); Configuration.skypePassword = props.getProperty("password", null); Configuration.pemFile = props.getProperty("pemfile", null); // empty string here is important. Configuration.postApiKey = props.getProperty("postApiKey", ""); if (Configuration.pemFile == null || Configuration.skypePassword == null || Configuration.skypeUsername == null) { - String msg = "Unable to find username, password or pemfile from project.properties nor persona.properties. Exiting"; + String msg = "Unable to find username, password or pemfile from project.properties nor personal.properties. Exiting"; log.error(msg); System.err.println(msg); System.exit(1); } // normalize pem file File file = new File(Configuration.pemFile); if (file.exists()) { try { Configuration.pemFile = file.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Unable to find the configuration file " + Configuration.pemFile); } // make sure that there is an accompanying DER file file = new File(Configuration.pemFile.replaceAll(".pem", ".der")); if (!file.exists()) { throw new RuntimeException("You need to have an accompanying DER file! Use the command " + "'openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER -in myKeyPair.pem -out myKeyPair.der'"); } Configuration.setAdmins(Configuration.getProperty("adminfile")); } }
true
true
private static void initConfiguration() { String homeDir = System.getProperty("skypeBotHome", "."); Properties props = new Properties(); File propsFile = new File(new File(homeDir), "personal.properties"); try { if (propsFile.exists()) { props.load(new FileReader(propsFile)); } else { propsFile = new File("project.properties"); if (propsFile.exists()) { props.load(new FileReader(propsFile)); } } } catch (FileNotFoundException e) { throw new RuntimeException("Unable to read properties file " + propsFile.getAbsolutePath(), e); } catch (IOException e) { throw new RuntimeException("Unable to read properties file " + propsFile.getAbsolutePath(), e); } Configuration.props = props; Configuration.skypeUsername = props.getProperty("username", null); Configuration.skypePassword = props.getProperty("password", null); Configuration.pemFile = props.getProperty("pemfile", null); // empty string here is important. Configuration.postApiKey = props.getProperty("postApiKey", ""); if (Configuration.pemFile == null || Configuration.skypePassword == null || Configuration.skypeUsername == null) { String msg = "Unable to find username, password or pemfile from project.properties nor persona.properties. Exiting"; log.error(msg); System.err.println(msg); System.exit(1); } // normalize pem file File file = new File(Configuration.pemFile); if (file.exists()) { try { Configuration.pemFile = file.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Unable to find the configuration file " + Configuration.pemFile); } // make sure that there is an accompanying DER file file = new File(Configuration.pemFile.replaceAll(".pem", ".der")); if (!file.exists()) { throw new RuntimeException("You need to have an accompanying DER file! Use the command " + "'openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER -in myKeyPair.pem -out myKeyPair.der'"); } Configuration.setAdmins(Configuration.getProperty("adminfile")); }
private static void initConfiguration() { String homeDir = System.getProperty("skypeBotHome", "."); Properties props = new Properties(); File propsFile = new File(new File(homeDir), "personal.properties"); try { if (propsFile.exists()) { props.load(new FileReader(propsFile)); } else { propsFile = new File("project.properties"); if (propsFile.exists()) { props.load(new FileReader(propsFile)); } } } catch (FileNotFoundException e) { throw new RuntimeException("Unable to read properties file " + propsFile.getAbsolutePath(), e); } catch (IOException e) { throw new RuntimeException("Unable to read properties file " + propsFile.getAbsolutePath(), e); } Configuration.props = props; Configuration.skypeUsername = props.getProperty("username", null); Configuration.skypePassword = props.getProperty("password", null); Configuration.pemFile = props.getProperty("pemfile", null); // empty string here is important. Configuration.postApiKey = props.getProperty("postApiKey", ""); if (Configuration.pemFile == null || Configuration.skypePassword == null || Configuration.skypeUsername == null) { String msg = "Unable to find username, password or pemfile from project.properties nor personal.properties. Exiting"; log.error(msg); System.err.println(msg); System.exit(1); } // normalize pem file File file = new File(Configuration.pemFile); if (file.exists()) { try { Configuration.pemFile = file.getCanonicalPath(); } catch (IOException e) { throw new RuntimeException(e); } } else { throw new RuntimeException("Unable to find the configuration file " + Configuration.pemFile); } // make sure that there is an accompanying DER file file = new File(Configuration.pemFile.replaceAll(".pem", ".der")); if (!file.exists()) { throw new RuntimeException("You need to have an accompanying DER file! Use the command " + "'openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER -in myKeyPair.pem -out myKeyPair.der'"); } Configuration.setAdmins(Configuration.getProperty("adminfile")); }
diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/core/BundleResourceHandler.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/core/BundleResourceHandler.java index ef97501d..0de516f3 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/core/BundleResourceHandler.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/core/BundleResourceHandler.java @@ -1,279 +1,279 @@ /******************************************************************************* * Copyright (c) 2004, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.osgi.framework.internal.core; import java.io.IOException; import java.net.*; import org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry; import org.eclipse.osgi.baseadaptor.loader.BaseClassLoader; import org.eclipse.osgi.internal.baseadaptor.AdaptorMsg; import org.eclipse.osgi.util.NLS; import org.osgi.framework.*; /** * URLStreamHandler the bundleentry and bundleresource protocols. */ public abstract class BundleResourceHandler extends URLStreamHandler { public static final String SECURITY_AUTHORIZED = "SECURITY_AUTHORIZED"; //$NON-NLS-1$ protected static BundleContext context; protected BundleEntry bundleEntry; /** * Constructor for a bundle protocol resource URLStreamHandler. */ public BundleResourceHandler() { this(null); } public BundleResourceHandler(BundleEntry bundleEntry) { this.bundleEntry = bundleEntry; } /** * Parse reference URL. */ protected void parseURL(URL url, String str, int start, int end) { if (end < start) return; if (url.getPath() != null) // A call to a URL constructor has been made that uses an authorized URL as its context. // Null out bundleEntry because it will not be valid for the new path bundleEntry = null; String spec = ""; //$NON-NLS-1$ if (start < end) spec = str.substring(start, end); end -= start; //Default is to use path and bundleId from context String path = url.getPath(); String bundleId = url.getHost(); int resIndex = 0; // must start at 0 index if using a context int pathIdx = 0; if (spec.startsWith("//")) { //$NON-NLS-1$ int bundleIdIdx = 2; pathIdx = spec.indexOf('/', bundleIdIdx); if (pathIdx == -1) { pathIdx = end; // Use default path = ""; //$NON-NLS-1$ } int bundleIdEnd = spec.indexOf(':', bundleIdIdx); if (bundleIdEnd > pathIdx || bundleIdEnd == -1) bundleIdEnd = pathIdx; if (bundleIdEnd < pathIdx - 1) try { resIndex = Integer.parseInt(spec.substring(bundleIdEnd + 1, pathIdx)); } catch (NumberFormatException e) { // do nothing; results in resIndex == 0 } bundleId = spec.substring(bundleIdIdx, bundleIdEnd); } if (pathIdx < end && spec.charAt(pathIdx) == '/') path = spec.substring(pathIdx, end); else if (end > pathIdx) { if (path == null || path.equals("")) //$NON-NLS-1$ path = "/"; //$NON-NLS-1$ int last = path.lastIndexOf('/') + 1; if (last == 0) path = spec.substring(pathIdx, end); else path = path.substring(0, last) + spec.substring(pathIdx, end); } if (path == null) path = ""; //$NON-NLS-1$ //modify path if there's any relative references + // see RFC2396 Section 5.2 + // Note: For ".." references above the root the approach taken is removing them from the resolved path + if (path.endsWith("/.") || path.endsWith("/..")) //$NON-NLS-1$ //$NON-NLS-2$ + path = path + '/'; int dotIndex; while ((dotIndex = path.indexOf("/./")) >= 0) //$NON-NLS-1$ path = path.substring(0, dotIndex + 1) + path.substring(dotIndex + 3); - if (path.endsWith("/.")) //$NON-NLS-1$ - path = path.substring(0, path.length() - 1); while ((dotIndex = path.indexOf("/../")) >= 0) { //$NON-NLS-1$ if (dotIndex != 0) path = path.substring(0, path.lastIndexOf('/', dotIndex - 1)) + path.substring(dotIndex + 3); else path = path.substring(dotIndex + 3); } - if (path.endsWith("/..") && path.length() > 3) //$NON-NLS-1$ - path = path.substring(0, path.length() - 2); while ((dotIndex = path.indexOf("//")) >= 0) //$NON-NLS-1$ path = path.substring(0, dotIndex + 1) + path.substring(dotIndex + 2); // Check the permission of the caller to see if they // are allowed access to the resource. checkAdminPermission(context.getBundle(Long.parseLong(bundleId))); // Setting the authority portion of the URL to SECURITY_ATHORIZED // ensures that this URL was created by using this parseURL // method. The openConnection method will only open URLs // that have the authority set to this. setURL(url, url.getProtocol(), bundleId, resIndex, SECURITY_AUTHORIZED, null, path, null, url.getRef()); } /** * Establishes a connection to the resource specified by <code>URL</code>. * Since different protocols may have unique ways of connecting, it must be * overridden by the subclass. * * @return java.net.URLConnection * @param url java.net.URL * * @exception IOException thrown if an IO error occurs during connection establishment */ protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) // if the bundleEntry is not null then return quick return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); // check to make sure that this URL was created using the // parseURL method. This ensures the security check was done // at URL construction. if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { // No admin security check was made better check now. checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); } /** * Finds the bundle entry for this protocal. This is handled * differently for Bundle.gerResource() and Bundle.getEntry() * because getResource uses the bundle classloader and getEntry * only used the base bundle file. * @param url The URL to find the BundleEntry for. * @return the bundle entry */ abstract protected BundleEntry findBundleEntry(URL url, AbstractBundle bundle) throws IOException; /** * Converts a bundle URL to a String. * * @param url the URL. * @return a string representation of the URL. */ protected String toExternalForm(URL url) { StringBuffer result = new StringBuffer(url.getProtocol()); result.append("://"); //$NON-NLS-1$ String bundleId = url.getHost(); if ((bundleId != null) && (bundleId.length() > 0)) result.append(bundleId); int index = url.getPort(); if (index > 0) result.append(':').append(index); String path = url.getPath(); if (path != null) { if ((path.length() > 0) && (path.charAt(0) != '/')) /* if name doesn't have a leading slash */ { result.append("/"); //$NON-NLS-1$ } result.append(path); } String ref = url.getRef(); if (ref != null && ref.length() > 0) result.append('#').append(ref); return (result.toString()); } public static void setContext(BundleContext context) { BundleResourceHandler.context = context; } protected int hashCode(URL url) { int hash = 0; String protocol = url.getProtocol(); if (protocol != null) hash += protocol.hashCode(); String host = url.getHost(); if (host != null) hash += host.hashCode(); String path = url.getPath(); if (path != null) hash += path.hashCode(); return hash; } protected boolean equals(URL url1, URL url2) { return sameFile(url1, url2); } protected synchronized InetAddress getHostAddress(URL url) { return null; } protected boolean hostsEqual(URL url1, URL url2) { String host1 = url1.getHost(); String host2 = url2.getHost(); if (host1 != null && host2 != null) return host1.equalsIgnoreCase(host2); return (host1 == null && host2 == null); } protected boolean sameFile(URL url1, URL url2) { String p1 = url1.getProtocol(); String p2 = url2.getProtocol(); if (!((p1 == p2) || (p1 != null && p1.equalsIgnoreCase(p2)))) return false; if (!hostsEqual(url1, url2)) return false; if (url1.getPort() != url2.getPort()) return false; String a1 = url1.getAuthority(); String a2 = url2.getAuthority(); if (!((a1 == a2) || (a1 != null && a1.equals(a2)))) return false; String path1 = url1.getPath(); String path2 = url2.getPath(); if (!((path1 == path2) || (path1 != null && path1.equals(path2)))) return false; return true; } protected void checkAdminPermission(Bundle bundle) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new AdminPermission(bundle, AdminPermission.RESOURCE)); } } protected static BaseClassLoader getBundleClassLoader(AbstractBundle bundle) { BundleLoader loader = bundle.getBundleLoader(); if (loader == null) return null; return (BaseClassLoader) loader.createClassLoader(); } }
false
true
protected void parseURL(URL url, String str, int start, int end) { if (end < start) return; if (url.getPath() != null) // A call to a URL constructor has been made that uses an authorized URL as its context. // Null out bundleEntry because it will not be valid for the new path bundleEntry = null; String spec = ""; //$NON-NLS-1$ if (start < end) spec = str.substring(start, end); end -= start; //Default is to use path and bundleId from context String path = url.getPath(); String bundleId = url.getHost(); int resIndex = 0; // must start at 0 index if using a context int pathIdx = 0; if (spec.startsWith("//")) { //$NON-NLS-1$ int bundleIdIdx = 2; pathIdx = spec.indexOf('/', bundleIdIdx); if (pathIdx == -1) { pathIdx = end; // Use default path = ""; //$NON-NLS-1$ } int bundleIdEnd = spec.indexOf(':', bundleIdIdx); if (bundleIdEnd > pathIdx || bundleIdEnd == -1) bundleIdEnd = pathIdx; if (bundleIdEnd < pathIdx - 1) try { resIndex = Integer.parseInt(spec.substring(bundleIdEnd + 1, pathIdx)); } catch (NumberFormatException e) { // do nothing; results in resIndex == 0 } bundleId = spec.substring(bundleIdIdx, bundleIdEnd); } if (pathIdx < end && spec.charAt(pathIdx) == '/') path = spec.substring(pathIdx, end); else if (end > pathIdx) { if (path == null || path.equals("")) //$NON-NLS-1$ path = "/"; //$NON-NLS-1$ int last = path.lastIndexOf('/') + 1; if (last == 0) path = spec.substring(pathIdx, end); else path = path.substring(0, last) + spec.substring(pathIdx, end); } if (path == null) path = ""; //$NON-NLS-1$ //modify path if there's any relative references int dotIndex; while ((dotIndex = path.indexOf("/./")) >= 0) //$NON-NLS-1$ path = path.substring(0, dotIndex + 1) + path.substring(dotIndex + 3); if (path.endsWith("/.")) //$NON-NLS-1$ path = path.substring(0, path.length() - 1); while ((dotIndex = path.indexOf("/../")) >= 0) { //$NON-NLS-1$ if (dotIndex != 0) path = path.substring(0, path.lastIndexOf('/', dotIndex - 1)) + path.substring(dotIndex + 3); else path = path.substring(dotIndex + 3); } if (path.endsWith("/..") && path.length() > 3) //$NON-NLS-1$ path = path.substring(0, path.length() - 2); while ((dotIndex = path.indexOf("//")) >= 0) //$NON-NLS-1$ path = path.substring(0, dotIndex + 1) + path.substring(dotIndex + 2); // Check the permission of the caller to see if they // are allowed access to the resource. checkAdminPermission(context.getBundle(Long.parseLong(bundleId))); // Setting the authority portion of the URL to SECURITY_ATHORIZED // ensures that this URL was created by using this parseURL // method. The openConnection method will only open URLs // that have the authority set to this. setURL(url, url.getProtocol(), bundleId, resIndex, SECURITY_AUTHORIZED, null, path, null, url.getRef()); }
protected void parseURL(URL url, String str, int start, int end) { if (end < start) return; if (url.getPath() != null) // A call to a URL constructor has been made that uses an authorized URL as its context. // Null out bundleEntry because it will not be valid for the new path bundleEntry = null; String spec = ""; //$NON-NLS-1$ if (start < end) spec = str.substring(start, end); end -= start; //Default is to use path and bundleId from context String path = url.getPath(); String bundleId = url.getHost(); int resIndex = 0; // must start at 0 index if using a context int pathIdx = 0; if (spec.startsWith("//")) { //$NON-NLS-1$ int bundleIdIdx = 2; pathIdx = spec.indexOf('/', bundleIdIdx); if (pathIdx == -1) { pathIdx = end; // Use default path = ""; //$NON-NLS-1$ } int bundleIdEnd = spec.indexOf(':', bundleIdIdx); if (bundleIdEnd > pathIdx || bundleIdEnd == -1) bundleIdEnd = pathIdx; if (bundleIdEnd < pathIdx - 1) try { resIndex = Integer.parseInt(spec.substring(bundleIdEnd + 1, pathIdx)); } catch (NumberFormatException e) { // do nothing; results in resIndex == 0 } bundleId = spec.substring(bundleIdIdx, bundleIdEnd); } if (pathIdx < end && spec.charAt(pathIdx) == '/') path = spec.substring(pathIdx, end); else if (end > pathIdx) { if (path == null || path.equals("")) //$NON-NLS-1$ path = "/"; //$NON-NLS-1$ int last = path.lastIndexOf('/') + 1; if (last == 0) path = spec.substring(pathIdx, end); else path = path.substring(0, last) + spec.substring(pathIdx, end); } if (path == null) path = ""; //$NON-NLS-1$ //modify path if there's any relative references // see RFC2396 Section 5.2 // Note: For ".." references above the root the approach taken is removing them from the resolved path if (path.endsWith("/.") || path.endsWith("/..")) //$NON-NLS-1$ //$NON-NLS-2$ path = path + '/'; int dotIndex; while ((dotIndex = path.indexOf("/./")) >= 0) //$NON-NLS-1$ path = path.substring(0, dotIndex + 1) + path.substring(dotIndex + 3); while ((dotIndex = path.indexOf("/../")) >= 0) { //$NON-NLS-1$ if (dotIndex != 0) path = path.substring(0, path.lastIndexOf('/', dotIndex - 1)) + path.substring(dotIndex + 3); else path = path.substring(dotIndex + 3); } while ((dotIndex = path.indexOf("//")) >= 0) //$NON-NLS-1$ path = path.substring(0, dotIndex + 1) + path.substring(dotIndex + 2); // Check the permission of the caller to see if they // are allowed access to the resource. checkAdminPermission(context.getBundle(Long.parseLong(bundleId))); // Setting the authority portion of the URL to SECURITY_ATHORIZED // ensures that this URL was created by using this parseURL // method. The openConnection method will only open URLs // that have the authority set to this. setURL(url, url.getProtocol(), bundleId, resIndex, SECURITY_AUTHORIZED, null, path, null, url.getRef()); }
diff --git a/bundles/org.eclipse.ecf.protocol.nntp.store.derby/src/org/eclipse/ecf/protocol/nntp/store/derby/internal/ArticleDAO.java b/bundles/org.eclipse.ecf.protocol.nntp.store.derby/src/org/eclipse/ecf/protocol/nntp/store/derby/internal/ArticleDAO.java index a8466c4..7a74f1a 100644 --- a/bundles/org.eclipse.ecf.protocol.nntp.store.derby/src/org/eclipse/ecf/protocol/nntp/store/derby/internal/ArticleDAO.java +++ b/bundles/org.eclipse.ecf.protocol.nntp.store.derby/src/org/eclipse/ecf/protocol/nntp/store/derby/internal/ArticleDAO.java @@ -1,652 +1,652 @@ /******************************************************************************* * Copyright (c) 2010 Weltevree Beheer BV, Remain Software & Industrial-TSI * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wim Jongman - initial API and implementation * * *******************************************************************************/ package org.eclipse.ecf.protocol.nntp.store.derby.internal; import java.io.Reader; import java.io.StringReader; import java.sql.Clob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import org.eclipse.ecf.protocol.nntp.core.ArticleFactory; import org.eclipse.ecf.protocol.nntp.core.Debug; import org.eclipse.ecf.protocol.nntp.core.StringUtils; import org.eclipse.ecf.protocol.nntp.model.IArticle; import org.eclipse.ecf.protocol.nntp.model.INewsgroup; import org.eclipse.ecf.protocol.nntp.model.SALVO; import org.eclipse.ecf.protocol.nntp.model.StoreException; public class ArticleDAO { private final Connection connection; private PreparedStatement insertArticle; private PreparedStatement updateArticle; private PreparedStatement deleteArticle; private PreparedStatement getArticleRange; private PreparedStatement getArticleHeader; private PreparedStatement deleteArticleHeader; private PreparedStatement getArticleBody; private PreparedStatement deleteArticleBody; private PreparedStatement insertArticleHeader; private PreparedStatement insertArticleBody; private PreparedStatement updateArticleBody; private PreparedStatement getOldestArticle; private PreparedStatement getNewestArticle; private PreparedStatement deleteArticleReply; private PreparedStatement insertArticleReply; private PreparedStatement getArticleByUri; private PreparedStatement getArticleByID; private PreparedStatement getArticleReplies; private PreparedStatement getArticleIdsFromUser; private PreparedStatement getMarkedArticles; public ArticleDAO(Connection connection) throws StoreException { this.connection = connection; prepareStatements(); } private void prepareStatements() throws StoreException { try { getArticleHeader = connection .prepareStatement("select * from articleheader where articleid = ?"); getArticleBody = connection .prepareStatement("select * from articlebody where articleid = ?"); getArticleRange = connection .prepareStatement("select * from article where (articleNumber between ? and ?) and newsgroupId = ?"); getArticleByUri = connection .prepareStatement("select * from article where uri = ?"); getArticleByID = connection .prepareStatement("select * from article where ID = ? and newsgroupId = ?"); getArticleReplies = connection .prepareStatement("Select article.ID, " + "article.messageID, " + "article.uri, " + "article.newsgroupID, " + "article.articleNumber, " + "article.isMarked, " + "article.isRead " + "from articleReply " + "left outer join " + "article on article.ID = articleReply.articleID " + "where messageIDRepliedto = ?"); getOldestArticle = connection .prepareStatement("select * from article where newsgroupId = ? order by articleNumber asc"); getOldestArticle.setMaxRows(1); getNewestArticle = connection .prepareStatement("select * from article where newsgroupId = ? order by articleNumber desc"); getNewestArticle.setMaxRows(1); insertArticle = connection.prepareStatement( "insert into Article ( messageID, uri, newsgroupID, articleNumber, " + "isMarked," + "isRead) values(?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); insertArticleHeader = connection .prepareStatement("insert into ArticleHeader (articleid, attribute, value) values(?, ?, ?)"); insertArticleReply = connection .prepareStatement("insert into ArticleReply (articleid, messageIDRepliedTo) values(?, ?)"); insertArticleBody = connection .prepareStatement("insert into ArticleBody (articleid, body) values(?, ?)"); updateArticle = connection .prepareStatement("update Article set messageID = ?, uri = ?, " + "newsgroupid = ?, articleNumber = ?," + "isMarked = ?," + "isRead = ? where messageID = ?"); updateArticleBody = connection .prepareStatement("update Articlebody set articleID = ?, body = ? where articleID = ?"); deleteArticle = connection .prepareStatement("delete from article where uri like ? "); deleteArticleHeader = connection .prepareStatement("delete from articleheader where articleid = ?"); deleteArticleReply = connection .prepareStatement("delete from articleReply where articleid = ?"); deleteArticleBody = connection .prepareStatement("delete from articlebody where articleid = ?"); getArticleIdsFromUser = connection .prepareStatement("select articleid from articleheader where attribute = 'From:' and value = ?"); getMarkedArticles = connection - .prepareStatement("select * from article where isMarked = 1 and newsgroupId = ?"); + .prepareStatement("select * from article where isMarked = '1' and newsgroupId = ?"); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } public IArticle[] getArticles(INewsgroup newsgroup, int from, int to) throws StoreException { try { getArticleRange.setInt(1, from); getArticleRange.setInt(2, to); getArticleRange.setInt(3, Integer.parseInt(newsgroup.getProperty("DB_ID"))); getArticleRange.execute(); ResultSet r = getArticleRange.getResultSet(); if (r == null) return new IArticle[0]; ArrayList result = new ArrayList(); while (r.next()) { IArticle article = ArticleFactory.createArticle( getArticleNumber(r), newsgroup); article.setMarked(isMarked(r)); article.setRead(isRead(r)); article.setProperty("DB_ID", getArticleID(r) + ""); loadArticleHeaders(article, getArticleID(r)); result.add(article); } r.close(); return (IArticle[]) result.toArray(new IArticle[0]); } catch (Exception e) { throw new StoreException(e.getMessage(), e); } } public IArticle getOldestArticle(INewsgroup newsgroup) throws StoreException { return processOneArticle(getOldestArticle, newsgroup); } public IArticle getNewestArticle(INewsgroup newsgroup) throws StoreException { return processOneArticle(getNewestArticle, newsgroup); } private IArticle processOneArticle(PreparedStatement stat, INewsgroup newsgroup) throws StoreException { try { stat.setInt(1, Integer.parseInt(newsgroup.getProperty("DB_ID"))); stat.execute(); ResultSet r = stat.getResultSet(); if (r == null) return null; while (r.next()) { IArticle article = ArticleFactory.createArticle( getArticleNumber(r), newsgroup); article.setMarked(isMarked(r)); article.setRead(isRead(r)); article.setProperty("DB_ID", getArticleID(r) + ""); loadArticleHeaders(article, getArticleID(r)); return article; } r.close(); return null; } catch (Exception e) { throw new StoreException(e.getMessage(), e); } } private boolean isRead(ResultSet r) throws SQLException { return r.getString(7).equals("1"); } private boolean isMarked(ResultSet r) throws SQLException { return r.getString(6).equals("1"); } private int getArticleNumber(ResultSet r) throws SQLException { return r.getInt(5); } private int getArticleID(ResultSet r) throws SQLException { return r.getInt(1); } public void insertArticle(IArticle article) throws StoreException { article.setProperty("DB_ID", processArticle(insertArticle, article) + ""); insertArticleHeader(article); insertArticleReplies(article); } public void insertArticle(IArticle article, String[] body) throws StoreException { insertArticle(article); insertArticleBody(article, body); } public void updateArticle(IArticle article, String[] body) throws StoreException { updateArticle(article); updateArticleBody(article, body); } public void updateArticle(IArticle article) throws StoreException { deleteArticleHeader(article); processArticle(updateArticle, article); insertArticleHeader(article); } public void insertArticleReplies(IArticle article) throws StoreException { processArticleReplies(insertArticleReply, article); } private void processArticleReplies(PreparedStatement statement, IArticle article) throws StoreException { if (article.getLastReference() != null) { try { statement.setInt(1, Integer.parseInt(article.getProperty("DB_ID"))); statement.setString(2, article.getLastReference()); statement.execute(); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } } public void deleteArticleReplies(IArticle article) throws StoreException { try { int id = Integer.parseInt(article.getProperty("DB_ID")); deleteArticleReply.setInt(1, id); deleteArticleReply.execute(); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } public void deleteArticle(IArticle article) throws StoreException { processDeleteArticle(article.getURL()); } private void processDeleteArticle(String url) throws StoreException { try { deleteArticle.setString(1, url); deleteArticle.execute(); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } private int processArticle(PreparedStatement statement, IArticle article) throws StoreException { try { statement.setString(1, article.getMessageId()); statement.setString(2, article.getURL()); statement.setInt(3, Integer.parseInt(article.getNewsgroup() .getProperty("DB_ID"))); statement.setInt(4, article.getArticleNumber()); statement.setString(5, article.isMarked() ? "1" : "0"); statement.setString(6, article.isRead() ? "1" : "0"); if (statement == updateArticle) { statement.setString(7, article.getMessageId()); } statement.execute(); ResultSet r = statement.getGeneratedKeys(); if (r != null && r.next()) { int result = r.getInt(1); r.close(); return result; } return 0; } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } private void loadArticleHeaders(IArticle article, int articleID) throws StoreException { try { getArticleHeader.setInt(1, articleID); getArticleHeader.execute(); ResultSet r = getArticleHeader.getResultSet(); if (r == null) return; while (r.next()) { article.setHeaderAttributeValue(r.getString(2), r.getString(3)); } r.close(); } catch (Exception e) { throw new StoreException(e.getMessage(), e); } } public void insertArticleBody(IArticle article, String[] body) throws StoreException { processArticleBody(insertArticleBody, article, body); } public String[] getArticleBody(IArticle article) throws StoreException { try { getArticleBody.setInt(1, Integer.parseInt(article.getProperty("DB_ID"))); getArticleBody.execute(); ResultSet r = getArticleBody.getResultSet(); while (r.next()) { Clob clob = r.getClob(2); Reader is = clob.getCharacterStream(); StringBuffer body = new StringBuffer(1024); int c = is.read(); while (c > 0) { body.append((char) c); c = is.read(); } r.close(); return StringUtils.split(body.toString(), SALVO.CRLF); } } catch (Exception e) { throw new StoreException(e.getMessage(), e); } return new String[0]; } public void deleteArticleBody(IArticle article) throws StoreException { try { int id = Integer.parseInt(article.getProperty("DB_ID")); deleteArticleBody.setInt(1, id); deleteArticleBody.execute(); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } public void updateArticleBody(IArticle article, String[] body) throws StoreException { processArticleBody(updateArticleBody, article, body); } private void processArticleBody(PreparedStatement statement, IArticle article, String[] body) throws StoreException { try { statement.setInt(1, Integer.parseInt(article.getProperty("DB_ID"))); StringBuffer buffer = new StringBuffer(body.length * 80); for (int i = 0; i < body.length; i++) { String string = body[i]; buffer.append(string + SALVO.CRLF); } statement.setClob(2, new StringReader(buffer.toString())); if (statement == updateArticleBody) statement.setInt(3, Integer.parseInt(article.getProperty("DB_ID"))); statement.execute(); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } public void insertArticleHeader(IArticle article) throws StoreException { processArticleHeader(insertArticleHeader, article); } public void deleteArticleHeader(IArticle article) throws StoreException { try { int id = Integer.parseInt(article.getProperty("DB_ID")); deleteArticleHeader.setInt(1, id); deleteArticleHeader.execute(); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } private void processArticleHeader(PreparedStatement statement, IArticle article) throws StoreException { try { int r = Debug.timerStart(getClass()); String[] headerAttributes = article.getHeaderAttributes(); String[] headerAttrValues = article.getHeaderAttributeValues(); int articleID = Integer.parseInt(article.getProperty("DB_ID")); Debug.timerStop(getClass(), r); for (int i = 0; i < headerAttributes.length; i++) { String attr = headerAttributes[i]; statement.setInt(1, articleID); statement.setString(2, attr); statement.setString(3, headerAttrValues[i]); statement.execute(); } } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } public void deleteArticle(INewsgroup group) throws StoreException { processDeleteArticle(group.getURL() + "%"); } public IArticle getArticle(INewsgroup group, String URL) throws StoreException { return internalGetArticleByString(getArticleByUri, group, URL); } public boolean hasArticle(IArticle article) throws StoreException { return getArticles(article.getNewsgroup(), article.getArticleNumber(), article.getArticleNumber()).length != 0; } private IArticle internalGetArticleByString(PreparedStatement s, INewsgroup group, String URL) throws StoreException { try { s.setString(1, URL); s.execute(); ResultSet r = s.getResultSet(); if (r == null) throw new StoreException("Article with uri/messageID " + URL + " not in the database"); if (r.next()) { new NewsgroupDAO(connection) .getNewsgroup(null, getNewsgroup(r)); IArticle article = ArticleFactory.createArticle( getArticleNumber(r), group); article.setMarked(isMarked(r)); article.setRead(isRead(r)); article.setProperty("DB_ID", getArticleID(r) + ""); loadArticleHeaders(article, getArticleID(r)); r.close(); return article; } } catch (Exception e) { throw new StoreException(e.getMessage(), e); } return null; } private int getNewsgroup(ResultSet r) throws SQLException { return r.getInt(4); } public IArticle[] getFollowUps(IArticle articleIn) throws StoreException { try { getArticleReplies.setString(1, articleIn.getMessageId()); getArticleReplies.execute(); ResultSet r = getArticleReplies.getResultSet(); if (r == null) return new IArticle[0]; ArrayList result = new ArrayList(); while (r.next()) { IArticle article = ArticleFactory.createArticle( getArticleNumber(r), articleIn.getNewsgroup()); article.setMarked(isMarked(r)); article.setRead(isRead(r)); article.setProperty("DB_ID", getArticleID(r) + ""); loadArticleHeaders(article, getArticleID(r)); result.add(article); } r.close(); return (IArticle[]) result.toArray(new IArticle[0]); } catch (Exception e) { throw new StoreException(e.getMessage(), e); } } /** * Get articlesIds of a particular user * * @param userId * Full user name * @return articlesId s of a particular user * @throws StoreException */ public Integer[] getArticleIdsFromUser(String userId) throws StoreException { try { getArticleIdsFromUser.setString(1, userId); getArticleIdsFromUser.execute(); ResultSet r = getArticleIdsFromUser.getResultSet(); if (r == null) { return null; } ArrayList<Integer> result = new ArrayList<Integer>(); while (r.next()) { result.add(r.getInt(1)); } r.close(); Integer output[] = new Integer[result.size()]; output = result.toArray(output); return output; } catch (Exception e) { throw new StoreException(e.getMessage(), e); } } /** * Get a article from the articleId * * @param newsgroup * Newsgroup * @param id * articleId * @return article corresponds to given articleId * @throws StoreException */ public IArticle getArticleById(INewsgroup newsgroup, int id) throws StoreException { try { getArticleByID.setInt(1, id); getArticleByID.setInt(2, Integer.parseInt(newsgroup.getProperty("DB_ID"))); getArticleByID.execute(); ResultSet r = getArticleByID.getResultSet(); if (r == null) return null; IArticle article = null; while (r.next()) { article = ArticleFactory.createArticle(getArticleNumber(r), newsgroup); article.setMarked(isMarked(r)); article.setRead(isRead(r)); article.setProperty("DB_ID", getArticleID(r) + ""); loadArticleHeaders(article, getArticleID(r)); } r.close(); return article; } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } } /** * Get marked articles for a particular newsgroup * * @param newsgroup * Newsgroup * @return marked articles for a particular newsgroup * @throws StoreException */ public IArticle[] getMarkedArticles(INewsgroup newsgroup) throws StoreException { try { getMarkedArticles.setInt(1, Integer.parseInt(newsgroup.getProperty("DB_ID"))); getMarkedArticles.execute(); ResultSet r = getMarkedArticles.getResultSet(); if (r == null) return new IArticle[0]; ArrayList result = new ArrayList(); while (r.next()) { IArticle article = ArticleFactory.createArticle( getArticleNumber(r), newsgroup); article.setMarked(isMarked(r)); article.setRead(isRead(r)); article.setProperty("DB_ID", getArticleID(r) + ""); loadArticleHeaders(article, getArticleID(r)); result.add(article); } r.close(); return (IArticle[]) result.toArray(new IArticle[0]); } catch (Exception e) { throw new StoreException(e.getMessage(), e); } } }
true
true
private void prepareStatements() throws StoreException { try { getArticleHeader = connection .prepareStatement("select * from articleheader where articleid = ?"); getArticleBody = connection .prepareStatement("select * from articlebody where articleid = ?"); getArticleRange = connection .prepareStatement("select * from article where (articleNumber between ? and ?) and newsgroupId = ?"); getArticleByUri = connection .prepareStatement("select * from article where uri = ?"); getArticleByID = connection .prepareStatement("select * from article where ID = ? and newsgroupId = ?"); getArticleReplies = connection .prepareStatement("Select article.ID, " + "article.messageID, " + "article.uri, " + "article.newsgroupID, " + "article.articleNumber, " + "article.isMarked, " + "article.isRead " + "from articleReply " + "left outer join " + "article on article.ID = articleReply.articleID " + "where messageIDRepliedto = ?"); getOldestArticle = connection .prepareStatement("select * from article where newsgroupId = ? order by articleNumber asc"); getOldestArticle.setMaxRows(1); getNewestArticle = connection .prepareStatement("select * from article where newsgroupId = ? order by articleNumber desc"); getNewestArticle.setMaxRows(1); insertArticle = connection.prepareStatement( "insert into Article ( messageID, uri, newsgroupID, articleNumber, " + "isMarked," + "isRead) values(?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); insertArticleHeader = connection .prepareStatement("insert into ArticleHeader (articleid, attribute, value) values(?, ?, ?)"); insertArticleReply = connection .prepareStatement("insert into ArticleReply (articleid, messageIDRepliedTo) values(?, ?)"); insertArticleBody = connection .prepareStatement("insert into ArticleBody (articleid, body) values(?, ?)"); updateArticle = connection .prepareStatement("update Article set messageID = ?, uri = ?, " + "newsgroupid = ?, articleNumber = ?," + "isMarked = ?," + "isRead = ? where messageID = ?"); updateArticleBody = connection .prepareStatement("update Articlebody set articleID = ?, body = ? where articleID = ?"); deleteArticle = connection .prepareStatement("delete from article where uri like ? "); deleteArticleHeader = connection .prepareStatement("delete from articleheader where articleid = ?"); deleteArticleReply = connection .prepareStatement("delete from articleReply where articleid = ?"); deleteArticleBody = connection .prepareStatement("delete from articlebody where articleid = ?"); getArticleIdsFromUser = connection .prepareStatement("select articleid from articleheader where attribute = 'From:' and value = ?"); getMarkedArticles = connection .prepareStatement("select * from article where isMarked = 1 and newsgroupId = ?"); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } }
private void prepareStatements() throws StoreException { try { getArticleHeader = connection .prepareStatement("select * from articleheader where articleid = ?"); getArticleBody = connection .prepareStatement("select * from articlebody where articleid = ?"); getArticleRange = connection .prepareStatement("select * from article where (articleNumber between ? and ?) and newsgroupId = ?"); getArticleByUri = connection .prepareStatement("select * from article where uri = ?"); getArticleByID = connection .prepareStatement("select * from article where ID = ? and newsgroupId = ?"); getArticleReplies = connection .prepareStatement("Select article.ID, " + "article.messageID, " + "article.uri, " + "article.newsgroupID, " + "article.articleNumber, " + "article.isMarked, " + "article.isRead " + "from articleReply " + "left outer join " + "article on article.ID = articleReply.articleID " + "where messageIDRepliedto = ?"); getOldestArticle = connection .prepareStatement("select * from article where newsgroupId = ? order by articleNumber asc"); getOldestArticle.setMaxRows(1); getNewestArticle = connection .prepareStatement("select * from article where newsgroupId = ? order by articleNumber desc"); getNewestArticle.setMaxRows(1); insertArticle = connection.prepareStatement( "insert into Article ( messageID, uri, newsgroupID, articleNumber, " + "isMarked," + "isRead) values(?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); insertArticleHeader = connection .prepareStatement("insert into ArticleHeader (articleid, attribute, value) values(?, ?, ?)"); insertArticleReply = connection .prepareStatement("insert into ArticleReply (articleid, messageIDRepliedTo) values(?, ?)"); insertArticleBody = connection .prepareStatement("insert into ArticleBody (articleid, body) values(?, ?)"); updateArticle = connection .prepareStatement("update Article set messageID = ?, uri = ?, " + "newsgroupid = ?, articleNumber = ?," + "isMarked = ?," + "isRead = ? where messageID = ?"); updateArticleBody = connection .prepareStatement("update Articlebody set articleID = ?, body = ? where articleID = ?"); deleteArticle = connection .prepareStatement("delete from article where uri like ? "); deleteArticleHeader = connection .prepareStatement("delete from articleheader where articleid = ?"); deleteArticleReply = connection .prepareStatement("delete from articleReply where articleid = ?"); deleteArticleBody = connection .prepareStatement("delete from articlebody where articleid = ?"); getArticleIdsFromUser = connection .prepareStatement("select articleid from articleheader where attribute = 'From:' and value = ?"); getMarkedArticles = connection .prepareStatement("select * from article where isMarked = '1' and newsgroupId = ?"); } catch (SQLException e) { throw new StoreException(e.getMessage(), e); } }
diff --git a/SublimeJava.java b/SublimeJava.java index da622ac..d226054 100644 --- a/SublimeJava.java +++ b/SublimeJava.java @@ -1,555 +1,560 @@ /* Copyright (c) 2012 Fredrik Ehnbom This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ import java.lang.reflect.*; import java.net.*; import java.io.*; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.jar.*; public class SublimeJava { private static String getInstancedType(Class<?> c, String gen, String ret, String[] templateParam) { if (gen.startsWith("class ")) gen = gen.substring("class ".length()); { // This is a bit odd, and I'm not sure it's correct. Seems "gen" returns an absolute // class path that isn't correct. I've only seen this for the specific class that is // in the repro case of issue #26, but it probably happens elsewhere too so could // have to be tweaked. // // In short, gen will list Tests.Tests$Foo whereas the correct type would be just // Tests$Foo String pat = "(\\w+\\.)+"+ Pattern.quote(ret); Pattern p = Pattern.compile(pat); Matcher m = p.matcher(gen); if (m.find()) { gen = m.replaceAll(Matcher.quoteReplacement(ret)); } } if (!gen.equals(ret)) { boolean set = false; TypeVariable<?> tv[] = c.getTypeParameters(); for (int i = 0; i < tv.length && i < templateParam.length; i++) { String pat = "((^|[<,\\s])+)" + tv[i].getName() + "(([,\\s>]|$)+)"; Pattern p = Pattern.compile(pat); Matcher m = p.matcher(gen); if (m.find()) { gen = m.replaceAll(Matcher.quoteReplacement(m.group(1) + templateParam[i] + m.group(3))); } } ret = gen; } return ret; } private static String[] getCompletion(Method m, String filter, String[] templateParam) { String str = m.getName(); if (!str.startsWith(filter)) return null; str += "("; String ins = str; int count = 1; Type[] generic = m.getGenericParameterTypes(); Class[] normal = m.getParameterTypes(); for (int i = 0; i < normal.length; i++) { if (count > 1) { str += ", "; ins += ", "; } String gen = generic[i].toString(); String ret = normal[i].getName(); ret = getInstancedType(m.getDeclaringClass(), gen, ret, templateParam); str += ret; ins += "${"+count + ":" + ret.replace("$", "\\$") + "}"; count++; } str += ")\t" + getInstancedType(m.getDeclaringClass(), m.getGenericReturnType().toString(), m.getReturnType().getName(), templateParam); ins += ")"; return new String[] {str, ins}; } private static String[] getCompletion(Field f, String filter, String[] templateArgs) { String str = f.getName(); if (!str.startsWith(filter)) return null; String rep = str + "\t" + getInstancedType(f.getDeclaringClass(), f.getGenericType().toString(), f.getType().getName(), templateArgs); return new String[] {rep, str}; } private static String[] getCompletion(Class clazz, String filter, String[] templateArgs) { return new String[] {clazz.getSimpleName() + "\tclass", clazz.getSimpleName()}; } private static <T> String[] getCompletion(T t, String filter, String[] templateArgs) { if (t instanceof Method) { return getCompletion((Method)t, filter, templateArgs); } else if (t instanceof Field) { return getCompletion((Field)t, filter, templateArgs); } else if (t instanceof Class) { return getCompletion((Class)t, filter, templateArgs); } return null; } private static final String sep = ";;--;;"; private static String getClassname(String pack, String clazz) { if (pack.endsWith(".*")) { return pack.substring(0, pack.length()-2) + "." + clazz; } else if (pack.length() != 0) { return pack + "$" + clazz; } return clazz; } private static final int STATIC_BIT = 1 << 0; private static final int PRIVATE_BIT = 1 << 1; private static final int PROTECTED_BIT = 1 << 2; private static final int PUBLIC_BIT = 1 << 3; private static <T> int getModifiers(T t) { int modifiers = 0; if (t instanceof Method) { Method m = (Method) t; modifiers = m.getModifiers(); } else if (t instanceof Field) { Field f = (Field) t; modifiers = f.getModifiers(); } else if (t instanceof Class) { Class c = (Class) t; modifiers = c.getModifiers(); } int returnvalue = 0; if (Modifier.isStatic(modifiers)) returnvalue |= STATIC_BIT; if (Modifier.isPrivate(modifiers)) returnvalue |= PRIVATE_BIT; if (Modifier.isProtected(modifiers)) returnvalue |= PROTECTED_BIT; if (Modifier.isPublic(modifiers)) returnvalue |= PUBLIC_BIT; return returnvalue; } private static <T> void dumpCompletions(T[] arr, String filter, String[] templateArgs) { for (T t : arr) { String[] completion = getCompletion(t, filter, templateArgs); if (completion == null) { continue; } System.out.println(completion[0] + sep + completion[1] + sep + getModifiers(t)); } } private static boolean getReturnType(Field[] fields, String filter, String templateParam[]) { for (Field f : fields) { if (filter.equals(f.getName())) { String gen = f.getGenericType().toString(); String ret = f.getType().getName(); ret = getInstancedType(f.getDeclaringClass(), gen, ret, templateParam); System.out.println("" + ret); return true; } } return false; } private static boolean getReturnType(Method[] methods, String filter, String templateParam[]) { for (Method m : methods) { if (filter.equals(m.getName())) { String gen = m.getGenericReturnType().toString(); String ret = m.getReturnType().getName(); ret = getInstancedType(m.getDeclaringClass(), gen, ret, templateParam); System.out.println("" + ret); return true; } } return false; } private static boolean getReturnType(Class[] classes, String filter, String templateParam[]) { for (Class clazz : classes) { if (filter.equals(clazz.getSimpleName())) { System.out.println(clazz.getName()); return true; } } return false; } private static boolean isPackage(String packageName) throws IOException { Package p = Package.getPackage(packageName); if (p != null) return true; ArrayList<String> paths = new ArrayList<String>(); paths.add("java/lang/String.class"); for (String s : System.getProperty("java.class.path").split(System.getProperty("path.separator"))) { if (!paths.contains(s)) paths.add(s); } packageName = packageName.replace(".", "/"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for (String s : paths) { URL url = classLoader.getResource(s + "/" + packageName); if (url != null) return true; else url = classLoader.getResource(s); if (url == null) continue; String filename = URLDecoder.decode(url.getFile(), "UTF-8"); if (url.getProtocol().equals("jar")) { filename = filename.substring(5, filename.indexOf("!")); JarFile jf = new JarFile(filename); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(packageName)) { return true; } } } else { File folder = new File(filename); return folder.exists(); } } return false; } private static void completePackage(String packageName) throws IOException { ArrayList<String> paths = new ArrayList<String>(); paths.add("java/lang/String.class"); for (String s : System.getProperty("java.class.path").split(System.getProperty("path.separator"))) { if (!paths.contains(s)) paths.add(s); } packageName = packageName.replace(".", "/"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for (String s : paths) { URL url = null; if (s.endsWith(".class")) url = classLoader.getResource(s); else { String path = "file://" + new File(s).getAbsolutePath(); if (path.endsWith(".jar")) { path = "jar:" + path + "!/" + packageName; } else { path += "/" + packageName; } try { System.err.println("path: " + path); url = new URL(path); } catch (Exception e) {} } if (url == null) continue; System.err.println("s: " + s); System.err.println("packagename: " + packageName); System.err.println("url: " + url); String filename = URLDecoder.decode(url.getFile(), "UTF-8"); ArrayList<String> packages = new ArrayList<String>(); if (url.getProtocol().equals("jar")) { filename = filename.substring(5, filename.indexOf("!")); JarFile jf = new JarFile(filename); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(packageName)) { name = name.substring(packageName.length()+1); int idx = name.indexOf('/'); if (idx != -1) { name = name.substring(0, idx); if (!packages.contains(name)) { packages.add(name); System.out.println(name + "\tpackage" + sep + name); } continue; } name = name.replace(".class", "").replace('/', '.'); System.out.println(name + "\tclass" + sep + name); } } } else { File folder = new File(filename); File[] files = folder.listFiles(); if (files == null) continue; for (File f : files) { String name = f.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length()-6); System.out.println(name + "\tclass" + sep + name); } else if (f.isDirectory()) { System.out.println(name + "\tpackage" + sep + name); } } } } } public static void main(String... unusedargs) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean first = true; while (true) { try { if (!first) // Just to indicate that there's no more output from the command and we're ready for new input System.out.println(";;--;;"); first = false; String cmd = in.readLine(); if (cmd == null) break; String args[] = cmd.split(";;--;;"); System.err.println(args.length); for (int i = 0; i < args.length; i++) { System.err.println(args[i]); } try { if (args[0].equals("-quit")) { System.err.println("quitting upon request"); return; } else if (args[0].equals("-findclass")) { String line = null; ArrayList<String> packages = new ArrayList<String>(); try { while ((line = in.readLine()) != null) { if (line.compareTo(sep) == 0) break; packages.add(line); } } catch (Exception e) { } boolean found = false; for (String pack : packages) { try { String classname = getClassname(pack, args[1]); System.err.println("Testing for: " + classname); Class c = Class.forName(classname); System.out.println("" + c.getName()); found = true; break; } catch (Exception e) { } } if (found) continue; // Still haven't found anything, so try to see if it's an internal class for (String pack : packages) { String classname = getClassname(pack, args[1]); while (!found && classname.indexOf('.') != -1) { int idx = classname.lastIndexOf('.'); classname = classname.substring(0, idx) + "$" + classname.substring(idx+1); try { System.err.println("Testing for: " + classname); Class c = Class.forName(classname); System.out.println("" + c.getName()); found = true; break; } catch (Exception e) { } } if (found) break; } // Nothing yet.. Is it a package by any chance? if (isPackage(args[1])) System.out.println(args[1]); continue; } if (args.length < 2) continue; Class<?> c = Class.forName(args[1]); String filter = ""; if (args.length >= 3) { filter = args[2]; if (filter.equals(sep)) { filter = ""; } } int len = args.length - 3; if (len < 0) len = 0; String[] templateParam = new String[len]; for (int i = 0; i < len; i++) { templateParam[i] = args[i+3]; } if (args[0].equals("-complete")) { dumpCompletions(c.getFields(), filter, templateParam); dumpCompletions(c.getDeclaredFields(), filter, templateParam); dumpCompletions(c.getMethods(), filter, templateParam); dumpCompletions(c.getDeclaredMethods(), filter, templateParam); dumpCompletions(c.getClasses(), filter, templateParam); dumpCompletions(c.getDeclaredClasses(), filter, templateParam); } else if (args[0].equals("-returntype")) { if (getReturnType(c.getDeclaredFields(), filter, templateParam)) continue; if (getReturnType(c.getDeclaredMethods(), filter, templateParam)) continue; if (getReturnType(c.getDeclaredClasses(), filter, templateParam)) continue; if (getReturnType(c.getFields(), filter, templateParam)) continue; if (getReturnType(c.getMethods(), filter, templateParam)) continue; if (getReturnType(c.getClasses(), filter, templateParam)) continue; } } catch (ClassNotFoundException x) { // Maybe it's a package then? if (args[0].equals("-complete")) { completePackage(args[1]); } else if (args[0].equals("-returntype")) { String name = args[1] + "." + args[2]; if (isPackage(name)) System.out.println(name); } } } + catch (Error e) + { + System.err.println("Error caught: " + e.getMessage()); + e.printStackTrace(System.err); + } catch (Exception e) { System.err.println("Exception caught: " + e.getMessage()); e.printStackTrace(System.err); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); } } }
true
true
public static void main(String... unusedargs) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean first = true; while (true) { try { if (!first) // Just to indicate that there's no more output from the command and we're ready for new input System.out.println(";;--;;"); first = false; String cmd = in.readLine(); if (cmd == null) break; String args[] = cmd.split(";;--;;"); System.err.println(args.length); for (int i = 0; i < args.length; i++) { System.err.println(args[i]); } try { if (args[0].equals("-quit")) { System.err.println("quitting upon request"); return; } else if (args[0].equals("-findclass")) { String line = null; ArrayList<String> packages = new ArrayList<String>(); try { while ((line = in.readLine()) != null) { if (line.compareTo(sep) == 0) break; packages.add(line); } } catch (Exception e) { } boolean found = false; for (String pack : packages) { try { String classname = getClassname(pack, args[1]); System.err.println("Testing for: " + classname); Class c = Class.forName(classname); System.out.println("" + c.getName()); found = true; break; } catch (Exception e) { } } if (found) continue; // Still haven't found anything, so try to see if it's an internal class for (String pack : packages) { String classname = getClassname(pack, args[1]); while (!found && classname.indexOf('.') != -1) { int idx = classname.lastIndexOf('.'); classname = classname.substring(0, idx) + "$" + classname.substring(idx+1); try { System.err.println("Testing for: " + classname); Class c = Class.forName(classname); System.out.println("" + c.getName()); found = true; break; } catch (Exception e) { } } if (found) break; } // Nothing yet.. Is it a package by any chance? if (isPackage(args[1])) System.out.println(args[1]); continue; } if (args.length < 2) continue; Class<?> c = Class.forName(args[1]); String filter = ""; if (args.length >= 3) { filter = args[2]; if (filter.equals(sep)) { filter = ""; } } int len = args.length - 3; if (len < 0) len = 0; String[] templateParam = new String[len]; for (int i = 0; i < len; i++) { templateParam[i] = args[i+3]; } if (args[0].equals("-complete")) { dumpCompletions(c.getFields(), filter, templateParam); dumpCompletions(c.getDeclaredFields(), filter, templateParam); dumpCompletions(c.getMethods(), filter, templateParam); dumpCompletions(c.getDeclaredMethods(), filter, templateParam); dumpCompletions(c.getClasses(), filter, templateParam); dumpCompletions(c.getDeclaredClasses(), filter, templateParam); } else if (args[0].equals("-returntype")) { if (getReturnType(c.getDeclaredFields(), filter, templateParam)) continue; if (getReturnType(c.getDeclaredMethods(), filter, templateParam)) continue; if (getReturnType(c.getDeclaredClasses(), filter, templateParam)) continue; if (getReturnType(c.getFields(), filter, templateParam)) continue; if (getReturnType(c.getMethods(), filter, templateParam)) continue; if (getReturnType(c.getClasses(), filter, templateParam)) continue; } } catch (ClassNotFoundException x) { // Maybe it's a package then? if (args[0].equals("-complete")) { completePackage(args[1]); } else if (args[0].equals("-returntype")) { String name = args[1] + "." + args[2]; if (isPackage(name)) System.out.println(name); } } } catch (Exception e) { System.err.println("Exception caught: " + e.getMessage()); e.printStackTrace(System.err); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); } }
public static void main(String... unusedargs) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean first = true; while (true) { try { if (!first) // Just to indicate that there's no more output from the command and we're ready for new input System.out.println(";;--;;"); first = false; String cmd = in.readLine(); if (cmd == null) break; String args[] = cmd.split(";;--;;"); System.err.println(args.length); for (int i = 0; i < args.length; i++) { System.err.println(args[i]); } try { if (args[0].equals("-quit")) { System.err.println("quitting upon request"); return; } else if (args[0].equals("-findclass")) { String line = null; ArrayList<String> packages = new ArrayList<String>(); try { while ((line = in.readLine()) != null) { if (line.compareTo(sep) == 0) break; packages.add(line); } } catch (Exception e) { } boolean found = false; for (String pack : packages) { try { String classname = getClassname(pack, args[1]); System.err.println("Testing for: " + classname); Class c = Class.forName(classname); System.out.println("" + c.getName()); found = true; break; } catch (Exception e) { } } if (found) continue; // Still haven't found anything, so try to see if it's an internal class for (String pack : packages) { String classname = getClassname(pack, args[1]); while (!found && classname.indexOf('.') != -1) { int idx = classname.lastIndexOf('.'); classname = classname.substring(0, idx) + "$" + classname.substring(idx+1); try { System.err.println("Testing for: " + classname); Class c = Class.forName(classname); System.out.println("" + c.getName()); found = true; break; } catch (Exception e) { } } if (found) break; } // Nothing yet.. Is it a package by any chance? if (isPackage(args[1])) System.out.println(args[1]); continue; } if (args.length < 2) continue; Class<?> c = Class.forName(args[1]); String filter = ""; if (args.length >= 3) { filter = args[2]; if (filter.equals(sep)) { filter = ""; } } int len = args.length - 3; if (len < 0) len = 0; String[] templateParam = new String[len]; for (int i = 0; i < len; i++) { templateParam[i] = args[i+3]; } if (args[0].equals("-complete")) { dumpCompletions(c.getFields(), filter, templateParam); dumpCompletions(c.getDeclaredFields(), filter, templateParam); dumpCompletions(c.getMethods(), filter, templateParam); dumpCompletions(c.getDeclaredMethods(), filter, templateParam); dumpCompletions(c.getClasses(), filter, templateParam); dumpCompletions(c.getDeclaredClasses(), filter, templateParam); } else if (args[0].equals("-returntype")) { if (getReturnType(c.getDeclaredFields(), filter, templateParam)) continue; if (getReturnType(c.getDeclaredMethods(), filter, templateParam)) continue; if (getReturnType(c.getDeclaredClasses(), filter, templateParam)) continue; if (getReturnType(c.getFields(), filter, templateParam)) continue; if (getReturnType(c.getMethods(), filter, templateParam)) continue; if (getReturnType(c.getClasses(), filter, templateParam)) continue; } } catch (ClassNotFoundException x) { // Maybe it's a package then? if (args[0].equals("-complete")) { completePackage(args[1]); } else if (args[0].equals("-returntype")) { String name = args[1] + "." + args[2]; if (isPackage(name)) System.out.println(name); } } } catch (Error e) { System.err.println("Error caught: " + e.getMessage()); e.printStackTrace(System.err); } catch (Exception e) { System.err.println("Exception caught: " + e.getMessage()); e.printStackTrace(System.err); } } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); } }
diff --git a/trunk/jbehave-maven-plugin/src/main/java/org/jbehave/mojo/ScenarioClassLoader.java b/trunk/jbehave-maven-plugin/src/main/java/org/jbehave/mojo/ScenarioClassLoader.java index f36fcfb3..c3c91040 100644 --- a/trunk/jbehave-maven-plugin/src/main/java/org/jbehave/mojo/ScenarioClassLoader.java +++ b/trunk/jbehave-maven-plugin/src/main/java/org/jbehave/mojo/ScenarioClassLoader.java @@ -1,80 +1,80 @@ package org.jbehave.mojo; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import org.jbehave.scenario.Scenario; /** * Extends URLClassLoader to instantiate Scenarios. * * @author Mauro Talevi */ public class ScenarioClassLoader extends URLClassLoader { public ScenarioClassLoader(List<String> classpathElements) throws MalformedURLException { super(classpathURLs(classpathElements), Scenario.class.getClassLoader()); } public ScenarioClassLoader(List<String> classpathElements, ClassLoader parent) throws MalformedURLException { super(classpathURLs(classpathElements), parent); } /** * Loads and instantiates a Scenario class * * @param scenarioClassName the name of the Scenario class * @return A Scenario instance */ public Scenario newScenario(String scenarioClassName) { try { Scenario scenario = (Scenario) loadClass(scenarioClassName).getConstructor(ClassLoader.class).newInstance( this); Thread.currentThread().setContextClassLoader(this); return scenario; } catch (ClassCastException e) { String message = "The scenario '" + scenarioClassName + "' must be of type '" + Scenario.class.getName() +"'"; throw new RuntimeException(message, e); } catch (Exception e) { String message = "The Scenario '" + scenarioClassName - + "' could not be instantiated with classpath element:s " + asShortPaths(getURLs()); + + "' could not be instantiated with classpath elements: " + asShortPaths(getURLs()); throw new RuntimeException(message, e); } } private List<String> asShortPaths(URL[] urls) { List<String> names = new ArrayList<String>(); for (URL url : urls) { String path = url.getPath(); if (isJar(path)) { names.add(shortPath(path)); } else { names.add(path); } } return names; } private static String shortPath(String path) { return path.substring(path.lastIndexOf("/") + 1); } private static boolean isJar(String path) { return path.endsWith(".jar"); } private static URL[] classpathURLs(List<String> elements) throws MalformedURLException { List<URL> urls = new ArrayList<URL>(); if (elements != null) { for (String element : elements) { urls.add(new File(element).toURL()); } } return urls.toArray(new URL[urls.size()]); } }
true
true
public Scenario newScenario(String scenarioClassName) { try { Scenario scenario = (Scenario) loadClass(scenarioClassName).getConstructor(ClassLoader.class).newInstance( this); Thread.currentThread().setContextClassLoader(this); return scenario; } catch (ClassCastException e) { String message = "The scenario '" + scenarioClassName + "' must be of type '" + Scenario.class.getName() +"'"; throw new RuntimeException(message, e); } catch (Exception e) { String message = "The Scenario '" + scenarioClassName + "' could not be instantiated with classpath element:s " + asShortPaths(getURLs()); throw new RuntimeException(message, e); } }
public Scenario newScenario(String scenarioClassName) { try { Scenario scenario = (Scenario) loadClass(scenarioClassName).getConstructor(ClassLoader.class).newInstance( this); Thread.currentThread().setContextClassLoader(this); return scenario; } catch (ClassCastException e) { String message = "The scenario '" + scenarioClassName + "' must be of type '" + Scenario.class.getName() +"'"; throw new RuntimeException(message, e); } catch (Exception e) { String message = "The Scenario '" + scenarioClassName + "' could not be instantiated with classpath elements: " + asShortPaths(getURLs()); throw new RuntimeException(message, e); } }
diff --git a/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/ToggleCommentHandlerGenerator.java b/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/ToggleCommentHandlerGenerator.java index a03e1e9a1..60c17b33f 100644 --- a/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/ToggleCommentHandlerGenerator.java +++ b/Core/SDK/org.emftext.sdk.codegen.resource.ui/src/org/emftext/sdk/codegen/resource/ui/generators/ui/ToggleCommentHandlerGenerator.java @@ -1,245 +1,245 @@ /******************************************************************************* * Copyright (c) 2006-2013 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.ui.generators.ui; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.LINKED_HASH_MAP; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MAP; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.ABSTRACT_HANDLER; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.BAD_LOCATION_EXCEPTION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.BUSY_INDICATOR; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.DISPLAY; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.EXECUTION_EVENT; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.EXECUTION_EXCEPTION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.HANDLER_UTIL; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_DOCUMENT; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_DOCUMENT_EXTENSION_3; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_EDITOR_PART; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_REGION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_SELECTION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_TEXT_OPERATION_TARGET; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_TEXT_SELECTION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.I_TYPED_REGION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.PLATFORM_UI; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.REGION; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.SHELL; import static org.emftext.sdk.codegen.resource.ui.UIClassNameConstants.TEXT_UTILITIES; import org.emftext.sdk.codegen.parameters.ArtifactParameter; import org.emftext.sdk.codegen.resource.GenerationContext; import org.emftext.sdk.codegen.resource.ui.generators.UIJavaBaseGenerator; import de.devboost.codecomposers.java.JavaComposite; public class ToggleCommentHandlerGenerator extends UIJavaBaseGenerator<ArtifactParameter<GenerationContext>> { @Override public void generateJavaContents(JavaComposite sc) { sc.add("package " + getResourcePackageName() + ";");sc.addLineBreak();sc.addImportsPlaceholder(); sc.addLineBreak(); sc.add("public class " + getResourceClassName() + " extends " + ABSTRACT_HANDLER(sc) + " {"); sc.addLineBreak(); addFields(sc); sc.addLineBreak(); addMethods(sc); sc.add("}"); } private void addFields(JavaComposite sc) { sc.add("public static String[] COMMENT_PREFIXES = new String[] { \"//\" };"); sc.addLineBreak(); sc.add("private " + I_DOCUMENT(sc) + " document;"); sc.add("private " + I_TEXT_OPERATION_TARGET(sc) + " operationTarget;"); sc.add("private " + MAP + "<String, String[]> prefixesMap;"); } private void addMethods(JavaComposite sc) { addIsEnableMethod(sc); addExecuteMethod(sc); sc.addComment("Parts of the implementation below have been copied from org.eclipse.jdt.internal.ui.javaeditor.ToggleCommentAction."); addIsSelectionCommentedMethod(sc); addGetTextBlockFromSelectionMethod(sc); addGetFirstCompleteLineOfRegionMethod(sc); addIsBlockCommentedMethod(sc); } private void addIsEnableMethod(JavaComposite sc) { sc.add("@Override"); sc.addLineBreak(); sc.add("public boolean isEnabled() {"); sc.add(I_EDITOR_PART(sc) + " activeEditor = " + PLATFORM_UI(sc) + ".getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();"); sc.add("if (activeEditor instanceof " + editorClassName + ") {"); sc.add(I_TEXT_OPERATION_TARGET(sc) + " operationTarget = (" + I_TEXT_OPERATION_TARGET(sc) + ") activeEditor.getAdapter(" + I_TEXT_OPERATION_TARGET(sc) + ".class);"); sc.add("return (operationTarget != null && operationTarget.canDoOperation(" + I_TEXT_OPERATION_TARGET(sc) + ".PREFIX) && operationTarget.canDoOperation(" + I_TEXT_OPERATION_TARGET(sc) + ".STRIP_PREFIX));"); sc.add("}"); sc.add("return false;"); sc.add("}"); sc.addLineBreak(); } private void addExecuteMethod(JavaComposite sc) { sc.add("public Object execute(" + EXECUTION_EVENT(sc) + " event) throws " + EXECUTION_EXCEPTION(sc) + " {"); sc.add(I_EDITOR_PART(sc) + " editorPart = " + HANDLER_UTIL(sc) + ".getActiveEditor(event);"); sc.add(editorClassName + " editor = null;"); sc.addLineBreak(); sc.add("if (editorPart instanceof " + editorClassName + ") {"); sc.add("editor = (" + editorClassName + ") editorPart;"); sc.add("operationTarget = (" + I_TEXT_OPERATION_TARGET(sc) + ") editorPart.getAdapter(" + I_TEXT_OPERATION_TARGET(sc) + ".class);"); sc.add("document = editor.getDocumentProvider().getDocument(editor.getEditorInput());"); sc.add("}"); sc.add("if (editor == null || operationTarget == null || document == null) {"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); // TODO Use default prefixes and content types from SourceViewerConfiguration if possible sc.add("prefixesMap = new " + LINKED_HASH_MAP + "<String, String[]>();"); sc.add("prefixesMap.put(" + I_DOCUMENT(sc) + ".DEFAULT_CONTENT_TYPE, COMMENT_PREFIXES);"); sc.addLineBreak(); - sc.add(I_SELECTION(sc) + " currentSelection = " + HANDLER_UTIL(sc) + ".getCurrentSelection(event);"); + sc.add(I_SELECTION(sc) + " currentSelection = editor.getSelectionProvider().getSelection();"); sc.add("final int operationCode;"); sc.add("if (isSelectionCommented(currentSelection)) {"); sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".STRIP_PREFIX;"); sc.add("} else {"); sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".PREFIX;"); sc.add("}"); sc.addLineBreak(); sc.add("if (!operationTarget.canDoOperation(operationCode)) {"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); sc.add(SHELL(sc) + " shell = editorPart.getSite().getShell();"); sc.add(DISPLAY(sc) + " display = null;"); sc.add("if (shell != null && !shell.isDisposed()) {"); sc.add("display = shell.getDisplay();"); sc.add("}"); sc.addLineBreak(); sc.add(BUSY_INDICATOR(sc) + ".showWhile(display, new Runnable() {"); sc.add("public void run() {"); sc.add("operationTarget.doOperation(operationCode);"); sc.add("}"); sc.add("});"); sc.addLineBreak(); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); } private void addIsSelectionCommentedMethod(JavaComposite sc) { sc.add("private boolean isSelectionCommented(" + I_SELECTION(sc) + " selection) {"); sc.add("if (!(selection instanceof " + I_TEXT_SELECTION(sc) + ")) {"); sc.add("return false;"); sc.add("}"); sc.add(I_TEXT_SELECTION(sc) + " textSelection = (" + I_TEXT_SELECTION(sc) + ") selection;"); sc.add("if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) {"); sc.add("return false;"); sc.add("}"); sc.add("try {"); sc.add(I_REGION(sc) + " block = getTextBlockFromSelection(textSelection, document);"); sc.add(I_TYPED_REGION(sc) + "[] regions = " + TEXT_UTILITIES(sc) + ".computePartitioning(document, " + I_DOCUMENT_EXTENSION_3(sc) + ".DEFAULT_PARTITIONING, block.getOffset(), block.getLength(), false);"); sc.add("int[] lines = new int[regions.length * 2]; // [startline, endline, startline, endline, ...]"); sc.add("for (int i = 0, j = 0; i < regions.length; i++, j+= 2) {"); sc.addComment("start line of region"); sc.add("lines[j] = getFirstCompleteLineOfRegion(regions[i], document);"); sc.addComment("end line of region"); sc.add("int length = regions[i].getLength();"); sc.add("int offset = regions[i].getOffset() + length;"); sc.add("if (length > 0) {"); sc.add("offset--;"); sc.add("}"); sc.add("lines[j + 1] = (lines[j] == -1 ? -1 : document.getLineOfOffset(offset));"); sc.add("}"); sc.addComment("Perform the check"); sc.add("for (int i = 0, j = 0; i < regions.length; i++, j += 2) {"); sc.add("String[] prefixes = prefixesMap.get(regions[i].getType());"); sc.add("if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0) {"); sc.add("if (!isBlockCommented(lines[j], lines[j + 1], prefixes, document)) {"); sc.add("return false;"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("return true;"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION(sc) + " x) {"); sc.addComment("should not happen"); sc.add("}"); sc.add("return false;"); sc.add("}"); sc.addLineBreak(); } private void addGetTextBlockFromSelectionMethod(JavaComposite sc) { sc.add("private " + I_REGION(sc) + " getTextBlockFromSelection(" + I_TEXT_SELECTION(sc) + " selection, " + I_DOCUMENT(sc) + " document) {"); sc.add("try {"); sc.add(I_REGION(sc) + " line = document.getLineInformationOfOffset(selection.getOffset());"); sc.add("int length = selection.getLength() == 0 ? line.getLength() : selection.getLength() + (selection.getOffset() - line.getOffset());"); sc.add("return new " + REGION(sc) + "(line.getOffset(), length);"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION(sc) + " x) {"); sc.addComment("should not happen"); sc.add("}"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); } private void addGetFirstCompleteLineOfRegionMethod(JavaComposite sc) { sc.add("private int getFirstCompleteLineOfRegion(" + I_REGION(sc) + " region, " + I_DOCUMENT(sc) + " document) {"); sc.add("try {"); sc.add("final int startLine = document.getLineOfOffset(region.getOffset());"); sc.add("int offset = document.getLineOffset(startLine);"); sc.add("if (offset >= region.getOffset()) {"); sc.add("return startLine;"); sc.add("}"); sc.add("final int nextLine = startLine + 1;"); sc.add("if (nextLine == document.getNumberOfLines()) {"); sc.add("return -1;"); sc.add("}"); sc.add("offset = document.getLineOffset(nextLine);"); sc.add("return (offset > region.getOffset() + region.getLength() ? -1 : nextLine);"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION(sc) + " x) {"); sc.addComment("should not happen"); sc.add("}"); sc.add("return -1;"); sc.add("}"); sc.addLineBreak(); } private void addIsBlockCommentedMethod(JavaComposite sc) { sc.add("private boolean isBlockCommented(int startLine, int endLine, String[] prefixes, " + I_DOCUMENT(sc) + " document) {"); sc.add("try {"); sc.addComment("check for occurrences of prefixes in the given lines"); sc.add("for (int i = startLine; i <= endLine; i++) {"); sc.add(I_REGION(sc) + " line = document.getLineInformation(i);"); sc.add("String text = document.get(line.getOffset(), line.getLength());"); sc.add("int[] found = " + TEXT_UTILITIES(sc) + ".indexOf(prefixes, text, 0);"); sc.add("if (found[0] == -1) {"); sc.addComment("found a line which is not commented"); sc.add("return false;"); sc.add("}"); sc.add("String s = document.get(line.getOffset(), found[0]);"); sc.add("s = s.trim();"); sc.add("if (s.length() != 0) {"); sc.addComment("found a line which is not commented"); sc.add("return false;"); sc.add("}"); sc.add("}"); sc.add("return true;"); sc.add("} catch (" + BAD_LOCATION_EXCEPTION(sc) + " x) {"); sc.addComment("should not happen"); sc.add("}"); sc.add("return false;"); sc.add("}"); sc.addLineBreak(); } }
true
true
private void addExecuteMethod(JavaComposite sc) { sc.add("public Object execute(" + EXECUTION_EVENT(sc) + " event) throws " + EXECUTION_EXCEPTION(sc) + " {"); sc.add(I_EDITOR_PART(sc) + " editorPart = " + HANDLER_UTIL(sc) + ".getActiveEditor(event);"); sc.add(editorClassName + " editor = null;"); sc.addLineBreak(); sc.add("if (editorPart instanceof " + editorClassName + ") {"); sc.add("editor = (" + editorClassName + ") editorPart;"); sc.add("operationTarget = (" + I_TEXT_OPERATION_TARGET(sc) + ") editorPart.getAdapter(" + I_TEXT_OPERATION_TARGET(sc) + ".class);"); sc.add("document = editor.getDocumentProvider().getDocument(editor.getEditorInput());"); sc.add("}"); sc.add("if (editor == null || operationTarget == null || document == null) {"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); // TODO Use default prefixes and content types from SourceViewerConfiguration if possible sc.add("prefixesMap = new " + LINKED_HASH_MAP + "<String, String[]>();"); sc.add("prefixesMap.put(" + I_DOCUMENT(sc) + ".DEFAULT_CONTENT_TYPE, COMMENT_PREFIXES);"); sc.addLineBreak(); sc.add(I_SELECTION(sc) + " currentSelection = " + HANDLER_UTIL(sc) + ".getCurrentSelection(event);"); sc.add("final int operationCode;"); sc.add("if (isSelectionCommented(currentSelection)) {"); sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".STRIP_PREFIX;"); sc.add("} else {"); sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".PREFIX;"); sc.add("}"); sc.addLineBreak(); sc.add("if (!operationTarget.canDoOperation(operationCode)) {"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); sc.add(SHELL(sc) + " shell = editorPart.getSite().getShell();"); sc.add(DISPLAY(sc) + " display = null;"); sc.add("if (shell != null && !shell.isDisposed()) {"); sc.add("display = shell.getDisplay();"); sc.add("}"); sc.addLineBreak(); sc.add(BUSY_INDICATOR(sc) + ".showWhile(display, new Runnable() {"); sc.add("public void run() {"); sc.add("operationTarget.doOperation(operationCode);"); sc.add("}"); sc.add("});"); sc.addLineBreak(); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); }
private void addExecuteMethod(JavaComposite sc) { sc.add("public Object execute(" + EXECUTION_EVENT(sc) + " event) throws " + EXECUTION_EXCEPTION(sc) + " {"); sc.add(I_EDITOR_PART(sc) + " editorPart = " + HANDLER_UTIL(sc) + ".getActiveEditor(event);"); sc.add(editorClassName + " editor = null;"); sc.addLineBreak(); sc.add("if (editorPart instanceof " + editorClassName + ") {"); sc.add("editor = (" + editorClassName + ") editorPart;"); sc.add("operationTarget = (" + I_TEXT_OPERATION_TARGET(sc) + ") editorPart.getAdapter(" + I_TEXT_OPERATION_TARGET(sc) + ".class);"); sc.add("document = editor.getDocumentProvider().getDocument(editor.getEditorInput());"); sc.add("}"); sc.add("if (editor == null || operationTarget == null || document == null) {"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); // TODO Use default prefixes and content types from SourceViewerConfiguration if possible sc.add("prefixesMap = new " + LINKED_HASH_MAP + "<String, String[]>();"); sc.add("prefixesMap.put(" + I_DOCUMENT(sc) + ".DEFAULT_CONTENT_TYPE, COMMENT_PREFIXES);"); sc.addLineBreak(); sc.add(I_SELECTION(sc) + " currentSelection = editor.getSelectionProvider().getSelection();"); sc.add("final int operationCode;"); sc.add("if (isSelectionCommented(currentSelection)) {"); sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".STRIP_PREFIX;"); sc.add("} else {"); sc.add("operationCode = " + I_TEXT_OPERATION_TARGET(sc) + ".PREFIX;"); sc.add("}"); sc.addLineBreak(); sc.add("if (!operationTarget.canDoOperation(operationCode)) {"); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); sc.add(SHELL(sc) + " shell = editorPart.getSite().getShell();"); sc.add(DISPLAY(sc) + " display = null;"); sc.add("if (shell != null && !shell.isDisposed()) {"); sc.add("display = shell.getDisplay();"); sc.add("}"); sc.addLineBreak(); sc.add(BUSY_INDICATOR(sc) + ".showWhile(display, new Runnable() {"); sc.add("public void run() {"); sc.add("operationTarget.doOperation(operationCode);"); sc.add("}"); sc.add("});"); sc.addLineBreak(); sc.add("return null;"); sc.add("}"); sc.addLineBreak(); }
diff --git a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/simulation/SimulationControlSystem.java b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/simulation/SimulationControlSystem.java index 7d8f43af6..6a92f832c 100644 --- a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/simulation/SimulationControlSystem.java +++ b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/simulation/SimulationControlSystem.java @@ -1,289 +1,289 @@ /******************************************************************************* * Copyright (c) 2005 The Regents of the University of California. * This material was produced under U.S. Government contract W-7405-ENG-36 * for Los Alamos National Laboratory, which is operated by the University * of California for the U.S. Department of Energy. The U.S. Government has * rights to use, reproduce, and distribute this software. NEITHER THE * GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified * to produce derivative works, such modified software should be clearly marked, * so as not to confuse it with the version available from LANL. * * Additionally, this program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * LA-CC 04-115 *******************************************************************************/ package org.eclipse.ptp.rtsystem.simulation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import org.eclipse.ptp.core.IPProcess; import org.eclipse.ptp.core.PTPCorePlugin; import org.eclipse.ptp.rtsystem.IControlSystem; import org.eclipse.ptp.rtsystem.IMonitoringSystem; import org.eclipse.ptp.rtsystem.IRuntimeListener; import org.eclipse.ptp.rtsystem.JobRunConfiguration; import org.eclipse.ptp.rtsystem.RuntimeEvent; public class SimulationControlSystem implements IControlSystem { protected int numJobs = -1; protected List listeners = new ArrayList(2); protected String spawned_app_state = null; protected int spawned_num_procs = 0; protected int spawned_procs_per_node = 0; protected int spawned_first_node = 0; protected String spawned_app_signal = new String(""); protected String spawned_app_exit_code = new String(""); protected Thread runningAppEventsThread = null; protected Thread runningAppFinishThread = null; protected HashMap processMap; public SimulationControlSystem() { } public void startup() { processMap = new HashMap(); } /* returns the new job name that it started - unique */ public String run(JobRunConfiguration jobRunConfig) { if (spawned_app_state != null && (spawned_app_state.equals(IPProcess.STARTING) || spawned_app_state .equals(IPProcess.RUNNING))) { System.out .println("Another job already running, unable to start a new one."); return null; } numJobs++; final String s = new String("job" + numJobs); spawned_num_procs = spawned_procs_per_node = spawned_first_node = 0; this.spawned_num_procs = jobRunConfig.getNumberOfProcesses(); this.spawned_procs_per_node = jobRunConfig.getNumberOfProcessesPerNode(); this.spawned_first_node = jobRunConfig.getFirstNodeNumber(); - processMap.put(s, new Integer("spawned_num_procs")); + processMap.put(s, new Integer(spawned_num_procs)); spawned_app_state = IPProcess.RUNNING; spawned_app_exit_code = new String(""); spawned_app_signal = new String(""); /* UNCOMMENT THIS IF YOU WANT THE JOB YOU SPAWN TO PRINT RANDOM TEXT OUTPUT * AND RANDOMLY EXIT AFTER 30SECS OR SO Runnable runningAppEventsRunnable = new Runnable() { public void run() { String job = new String("job" + numJobs); int numProcsInJob = ((Integer) (processMap.get(job))) .intValue(); while (true) { try { Thread.sleep(1000 + ((int) (Math.random() * 3000))); } catch (Exception e) { } if (!spawned_app_state.equals(IPProcess.RUNNING)) return; for (int i = 0; i < numProcsInJob; i++) { RuntimeEvent event = new RuntimeEvent( RuntimeEvent.EVENT_PROCESS_OUTPUT); event.setText((int) (Math.random() * 10000) + " random text"); fireEvent(new String("job" + numJobs + "_process" + i), event); } } } }; runningAppEventsThread = new Thread(runningAppEventsRunnable); runningAppEventsThread.start(); Runnable runningAppFinishRunnable = new Runnable() { public void run() { try { Thread.sleep(30000); } catch (Exception e) { } if (!spawned_app_state.equals(IPProcess.RUNNING)) return; spawned_app_state = IPProcess.EXITED; spawned_app_exit_code = new String("0"); System.out .println("Simulating spawned application terminating normally."); processMap.remove(s); fireEvent(new String("job" + numJobs), new RuntimeEvent( RuntimeEvent.EVENT_JOB_EXITED)); } }; runningAppFinishThread = new Thread(runningAppFinishRunnable); runningAppFinishThread.start(); */ return new String(s); } public void abortJob(String jobName) { spawned_app_state = IPProcess.EXITED_SIGNALLED; spawned_app_signal = new String("SIGTERM"); String s = new String("job" + numJobs); processMap.remove(s); } public String[] getJobs() { int i = 0; Set set = processMap.keySet(); String[] ne = new String[set.size()]; Iterator it = set.iterator(); while (it.hasNext()) { String key = (String) it.next(); ne[i++] = new String(key); } return ne; } /* get the processes pertaining to a certain job */ public String[] getProcesses(String jobName) { /* find this machineName in the map - if it's there */ if (!processMap.containsKey(jobName)) return null; int n = ((Integer) (processMap.get(jobName))).intValue(); String[] ne = new String[n]; for (int i = 0; i < ne.length; i++) { /* prepend this node name with the machine name */ ne[i] = new String(jobName + "_process" + i); } return ne; } /* * this is a major kludge, sorry but this is a dummy implementation anyway * so hack this up if you want to change the process to node mapping - this * assumes a certain number of jobs with a set number of processes in each * job */ public String getProcessNodeName(String procName) { // System.out.println("getProcessNodeName("+procName+")"); String job = procName.substring(0, procName.indexOf("process") - 1); // System.out.println("job = "+job); // String job = procName.substring(0, 4); /* ok this is coming from the fake job */ if (job.equals("job" + numJobs)) { String s = procName.substring(procName.indexOf("process") + 7, procName.length()); // System.out.println("proc # = "+s); int procNum = -1; try { procNum = (new Integer(s)).intValue(); } catch (NumberFormatException e) { } if (procNum != -1) { return "machine0_node" + spawned_first_node + (procNum / spawned_procs_per_node); } } return ""; } public String getProcessStatus(String procName) { String job = procName.substring(0, 4); if (job.equals("job" + numJobs)) { // System.out.println("PROCSTATE = "+spawned_app_state); return spawned_app_state; } return "-1"; } public String getProcessExitCode(String procName) { String job = procName.substring(0, 4); if (job.equals("job" + numJobs)) { // System.out.println("PROCSTATE = "+spawned_app_state); return spawned_app_exit_code; } return "-1"; } public String getProcessSignal(String procName) { String job = procName.substring(0, 4); if (job.equals("job" + numJobs)) { // System.out.println("PROCSTATE = "+spawned_app_state); return spawned_app_signal; } return "-1"; } public int getProcessPID(String procName) { return ((int)(Math.random() * 10000)) + 1000; } public void addRuntimeListener(IRuntimeListener listener) { listeners.add(listener); } public void removeRuntimeListener(IRuntimeListener listener) { listeners.remove(listener); } protected synchronized void fireEvent(String ne, RuntimeEvent event) { if (listeners == null) return; Iterator i = listeners.iterator(); while (i.hasNext()) { IRuntimeListener listener = (IRuntimeListener) i.next(); switch (event.getEventNumber()) { case RuntimeEvent.EVENT_NODE_STATUS_CHANGE: listener.runtimeNodeStatusChange(ne); break; case RuntimeEvent.EVENT_PROCESS_OUTPUT: listener.runtimeProcessOutput(ne, event.getText()); break; case RuntimeEvent.EVENT_JOB_EXITED: listener.runtimeJobExited(ne); break; case RuntimeEvent.EVENT_JOB_STATE_CHANGED: listener.runtimeJobStateChanged(ne); break; case RuntimeEvent.EVENT_NEW_JOB: listener.runtimeNewJob(ne); break; } } } public void shutdown() { listeners.clear(); listeners = null; } }
true
true
public String run(JobRunConfiguration jobRunConfig) { if (spawned_app_state != null && (spawned_app_state.equals(IPProcess.STARTING) || spawned_app_state .equals(IPProcess.RUNNING))) { System.out .println("Another job already running, unable to start a new one."); return null; } numJobs++; final String s = new String("job" + numJobs); spawned_num_procs = spawned_procs_per_node = spawned_first_node = 0; this.spawned_num_procs = jobRunConfig.getNumberOfProcesses(); this.spawned_procs_per_node = jobRunConfig.getNumberOfProcessesPerNode(); this.spawned_first_node = jobRunConfig.getFirstNodeNumber(); processMap.put(s, new Integer("spawned_num_procs")); spawned_app_state = IPProcess.RUNNING; spawned_app_exit_code = new String(""); spawned_app_signal = new String(""); /* UNCOMMENT THIS IF YOU WANT THE JOB YOU SPAWN TO PRINT RANDOM TEXT OUTPUT * AND RANDOMLY EXIT AFTER 30SECS OR SO Runnable runningAppEventsRunnable = new Runnable() { public void run() { String job = new String("job" + numJobs); int numProcsInJob = ((Integer) (processMap.get(job))) .intValue(); while (true) { try { Thread.sleep(1000 + ((int) (Math.random() * 3000))); } catch (Exception e) { } if (!spawned_app_state.equals(IPProcess.RUNNING)) return; for (int i = 0; i < numProcsInJob; i++) { RuntimeEvent event = new RuntimeEvent( RuntimeEvent.EVENT_PROCESS_OUTPUT); event.setText((int) (Math.random() * 10000) + " random text"); fireEvent(new String("job" + numJobs + "_process" + i), event); } } } }; runningAppEventsThread = new Thread(runningAppEventsRunnable); runningAppEventsThread.start(); Runnable runningAppFinishRunnable = new Runnable() { public void run() { try { Thread.sleep(30000); } catch (Exception e) { } if (!spawned_app_state.equals(IPProcess.RUNNING)) return; spawned_app_state = IPProcess.EXITED; spawned_app_exit_code = new String("0"); System.out .println("Simulating spawned application terminating normally."); processMap.remove(s); fireEvent(new String("job" + numJobs), new RuntimeEvent( RuntimeEvent.EVENT_JOB_EXITED)); } }; runningAppFinishThread = new Thread(runningAppFinishRunnable); runningAppFinishThread.start(); */ return new String(s); }
public String run(JobRunConfiguration jobRunConfig) { if (spawned_app_state != null && (spawned_app_state.equals(IPProcess.STARTING) || spawned_app_state .equals(IPProcess.RUNNING))) { System.out .println("Another job already running, unable to start a new one."); return null; } numJobs++; final String s = new String("job" + numJobs); spawned_num_procs = spawned_procs_per_node = spawned_first_node = 0; this.spawned_num_procs = jobRunConfig.getNumberOfProcesses(); this.spawned_procs_per_node = jobRunConfig.getNumberOfProcessesPerNode(); this.spawned_first_node = jobRunConfig.getFirstNodeNumber(); processMap.put(s, new Integer(spawned_num_procs)); spawned_app_state = IPProcess.RUNNING; spawned_app_exit_code = new String(""); spawned_app_signal = new String(""); /* UNCOMMENT THIS IF YOU WANT THE JOB YOU SPAWN TO PRINT RANDOM TEXT OUTPUT * AND RANDOMLY EXIT AFTER 30SECS OR SO Runnable runningAppEventsRunnable = new Runnable() { public void run() { String job = new String("job" + numJobs); int numProcsInJob = ((Integer) (processMap.get(job))) .intValue(); while (true) { try { Thread.sleep(1000 + ((int) (Math.random() * 3000))); } catch (Exception e) { } if (!spawned_app_state.equals(IPProcess.RUNNING)) return; for (int i = 0; i < numProcsInJob; i++) { RuntimeEvent event = new RuntimeEvent( RuntimeEvent.EVENT_PROCESS_OUTPUT); event.setText((int) (Math.random() * 10000) + " random text"); fireEvent(new String("job" + numJobs + "_process" + i), event); } } } }; runningAppEventsThread = new Thread(runningAppEventsRunnable); runningAppEventsThread.start(); Runnable runningAppFinishRunnable = new Runnable() { public void run() { try { Thread.sleep(30000); } catch (Exception e) { } if (!spawned_app_state.equals(IPProcess.RUNNING)) return; spawned_app_state = IPProcess.EXITED; spawned_app_exit_code = new String("0"); System.out .println("Simulating spawned application terminating normally."); processMap.remove(s); fireEvent(new String("job" + numJobs), new RuntimeEvent( RuntimeEvent.EVENT_JOB_EXITED)); } }; runningAppFinishThread = new Thread(runningAppFinishRunnable); runningAppFinishThread.start(); */ return new String(s); }
diff --git a/src/test/java/dk/statsbiblioteket/newspaper/md5checker/MD5CheckerComponentTest.java b/src/test/java/dk/statsbiblioteket/newspaper/md5checker/MD5CheckerComponentTest.java index c81a8bd..33682eb 100644 --- a/src/test/java/dk/statsbiblioteket/newspaper/md5checker/MD5CheckerComponentTest.java +++ b/src/test/java/dk/statsbiblioteket/newspaper/md5checker/MD5CheckerComponentTest.java @@ -1,65 +1,65 @@ package dk.statsbiblioteket.newspaper.md5checker; import org.testng.Assert; import org.testng.annotations.Test; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; /** Test MD5 checker */ public class MD5CheckerComponentTest { @Test /** * Test checking checksums on two batches */ public void testDoWorkOnBatch() throws Exception { MD5CheckerComponent md5CheckerComponent = new MockupIteratorSuper(System.getProperties()); // Run on first batch with one wrong checksum ResultCollector result = new ResultCollector( md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); Batch batch = new Batch("400022028241"); batch.setRoundTripNumber(1); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert one failure with the expected report Assert.assertFalse(result.isSuccess(), result.toReport() + "\n"); String expected = "<result tool=\"" + md5CheckerComponent.getComponentName() + "\" xmlns=\"http://schemas.statsbiblioteket.dk/result/\">\n" + " <outcome>Failure</outcome>\n" + " <date>[date]</date>\n" + " <failures>\n" + " <failure>\n" + " <filereference>B400022028241-RT1/400022028241-14/1795-06-13-01/AdresseContoirsEfterretninger-1795-06-13-01-0006-brik.jp2/contents</filereference>\n" + " <type>checksum</type>\n" + - " <component>" + md5CheckerComponent.getComponentName() + "-" + md5CheckerComponent.getComponentVersion() + "</component>\n" + " <component>MockupIteratorSuper</component>\n" + - " <description>Expected checksum d41d8cd98f00b204e9800998ecf8427f, but was d41d8cd98f00b204e9800998ecf8427e</description>\n" + " <description>2F-O1: Expected checksum d41d8cd98f00b204e9800998ecf8427f, but was d41d8cd98f00b204e9800998ecf8427e</description>\n" + " </failure>\n" + " </failures>\n" + "</result>"; Assert.assertEquals( result.toReport() .replaceAll("<date>[^<]*</date>", "<date>[date]</date>"), expected); // Run on second batch with no wrong checksums result = new ResultCollector(md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); batch = new Batch("400022028241"); batch.setRoundTripNumber(2); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert no errors Assert.assertTrue(result.isSuccess(), result.toReport() + "\n"); } }
false
true
public void testDoWorkOnBatch() throws Exception { MD5CheckerComponent md5CheckerComponent = new MockupIteratorSuper(System.getProperties()); // Run on first batch with one wrong checksum ResultCollector result = new ResultCollector( md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); Batch batch = new Batch("400022028241"); batch.setRoundTripNumber(1); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert one failure with the expected report Assert.assertFalse(result.isSuccess(), result.toReport() + "\n"); String expected = "<result tool=\"" + md5CheckerComponent.getComponentName() + "\" xmlns=\"http://schemas.statsbiblioteket.dk/result/\">\n" + " <outcome>Failure</outcome>\n" + " <date>[date]</date>\n" + " <failures>\n" + " <failure>\n" + " <filereference>B400022028241-RT1/400022028241-14/1795-06-13-01/AdresseContoirsEfterretninger-1795-06-13-01-0006-brik.jp2/contents</filereference>\n" + " <type>checksum</type>\n" + " <component>" + md5CheckerComponent.getComponentName() + "-" + md5CheckerComponent.getComponentVersion() + "</component>\n" + " <description>Expected checksum d41d8cd98f00b204e9800998ecf8427f, but was d41d8cd98f00b204e9800998ecf8427e</description>\n" + " </failure>\n" + " </failures>\n" + "</result>"; Assert.assertEquals( result.toReport() .replaceAll("<date>[^<]*</date>", "<date>[date]</date>"), expected); // Run on second batch with no wrong checksums result = new ResultCollector(md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); batch = new Batch("400022028241"); batch.setRoundTripNumber(2); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert no errors Assert.assertTrue(result.isSuccess(), result.toReport() + "\n"); }
public void testDoWorkOnBatch() throws Exception { MD5CheckerComponent md5CheckerComponent = new MockupIteratorSuper(System.getProperties()); // Run on first batch with one wrong checksum ResultCollector result = new ResultCollector( md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); Batch batch = new Batch("400022028241"); batch.setRoundTripNumber(1); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert one failure with the expected report Assert.assertFalse(result.isSuccess(), result.toReport() + "\n"); String expected = "<result tool=\"" + md5CheckerComponent.getComponentName() + "\" xmlns=\"http://schemas.statsbiblioteket.dk/result/\">\n" + " <outcome>Failure</outcome>\n" + " <date>[date]</date>\n" + " <failures>\n" + " <failure>\n" + " <filereference>B400022028241-RT1/400022028241-14/1795-06-13-01/AdresseContoirsEfterretninger-1795-06-13-01-0006-brik.jp2/contents</filereference>\n" + " <type>checksum</type>\n" + " <component>MockupIteratorSuper</component>\n" + " <description>2F-O1: Expected checksum d41d8cd98f00b204e9800998ecf8427f, but was d41d8cd98f00b204e9800998ecf8427e</description>\n" + " </failure>\n" + " </failures>\n" + "</result>"; Assert.assertEquals( result.toReport() .replaceAll("<date>[^<]*</date>", "<date>[date]</date>"), expected); // Run on second batch with no wrong checksums result = new ResultCollector(md5CheckerComponent.getComponentName(), md5CheckerComponent.getComponentVersion()); batch = new Batch("400022028241"); batch.setRoundTripNumber(2); md5CheckerComponent.doWorkOnBatch(batch, result); // Assert no errors Assert.assertTrue(result.isSuccess(), result.toReport() + "\n"); }
diff --git a/JFTP/src/org/jcooke212/jftp/FSHandler.java b/JFTP/src/org/jcooke212/jftp/FSHandler.java index 23428e3..0449328 100644 --- a/JFTP/src/org/jcooke212/jftp/FSHandler.java +++ b/JFTP/src/org/jcooke212/jftp/FSHandler.java @@ -1,61 +1,62 @@ package org.jcooke212.jftp; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import android.content.Context; import android.os.Environment; import android.widget.Toast; public class FSHandler { public static class LocalSystem { private static String currentDir; public static void getFileSystem(ArrayList<String> list) { list.clear(); File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath()); File[] files = root.listFiles(); for(File x: files) { list.add(x.getName()); } Collections.sort(list, String.CASE_INSENSITIVE_ORDER); currentDir = root.getAbsolutePath(); } public static void traverseFS(ArrayList<String> list, String target, Context appContext) throws IOException { currentDir += "/" + target; File dir = new File(currentDir); File root = Environment.getExternalStorageDirectory(); if(dir.isDirectory()) { list.clear(); if(!dir.getCanonicalPath().equals(root.getCanonicalPath())) { list.add(".."); } File[] files = dir.listFiles(); for(File x: files) { list.add(x.getName()); } Collections.sort(list, String.CASE_INSENSITIVE_ORDER); currentDir = dir.getCanonicalPath(); } else { Toast.makeText(appContext, R.string.not_dir, Toast.LENGTH_LONG).show(); + currentDir = currentDir.substring(0, currentDir.lastIndexOf("/")); } } } public static class RemoteSystem { } }
true
true
public static void traverseFS(ArrayList<String> list, String target, Context appContext) throws IOException { currentDir += "/" + target; File dir = new File(currentDir); File root = Environment.getExternalStorageDirectory(); if(dir.isDirectory()) { list.clear(); if(!dir.getCanonicalPath().equals(root.getCanonicalPath())) { list.add(".."); } File[] files = dir.listFiles(); for(File x: files) { list.add(x.getName()); } Collections.sort(list, String.CASE_INSENSITIVE_ORDER); currentDir = dir.getCanonicalPath(); } else { Toast.makeText(appContext, R.string.not_dir, Toast.LENGTH_LONG).show(); } }
public static void traverseFS(ArrayList<String> list, String target, Context appContext) throws IOException { currentDir += "/" + target; File dir = new File(currentDir); File root = Environment.getExternalStorageDirectory(); if(dir.isDirectory()) { list.clear(); if(!dir.getCanonicalPath().equals(root.getCanonicalPath())) { list.add(".."); } File[] files = dir.listFiles(); for(File x: files) { list.add(x.getName()); } Collections.sort(list, String.CASE_INSENSITIVE_ORDER); currentDir = dir.getCanonicalPath(); } else { Toast.makeText(appContext, R.string.not_dir, Toast.LENGTH_LONG).show(); currentDir = currentDir.substring(0, currentDir.lastIndexOf("/")); } }
diff --git a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java index 7bdde4b6f..c551f3330 100644 --- a/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java +++ b/dspace-api/src/main/java/org/dspace/app/statistics/LogAnalyser.java @@ -1,1360 +1,1360 @@ /* * LogAnalyser.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2009, The DSpace Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the DSpace Foundation nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.statistics; import org.dspace.app.statistics.LogLine; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import java.sql.SQLException; import java.lang.Long; import java.lang.StringBuffer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * This class performs all the actual analysis of a given set of DSpace log * files. Most input can be configured; use the -help flag for a full list * of usage information. * * The output of this file is plain text and forms an "aggregation" file which * can then be used for display purposes using the related ReportGenerator * class. * * @author Richard Jones */ public class LogAnalyser { // set up our class globals // FIXME: there are so many of these perhaps they should exist in a static // object of their own ///////////////// // aggregators ///////////////// /** aggregator for all actions performed in the system */ private static Map actionAggregator; /** aggregator for all searches performed */ private static Map searchAggregator; /** aggregator for user logins */ private static Map userAggregator; /** aggregator for item views */ private static Map itemAggregator; /** aggregator for current archive state statistics */ private static Map archiveStats; /** warning counter */ private static int warnCount = 0; /** log line counter */ private static int lineCount = 0; ////////////////// // config data ////////////////// /** list of actions to be included in the general summary */ private static List generalSummary; /** list of words not to be aggregated */ private static List excludeWords; /** list of search types to be ignored, such as "author:" */ private static List excludeTypes; /** list of characters to be excluded */ private static List excludeChars; /** list of item types to be reported on in the current state */ private static List itemTypes; /** bottom limit to output for search word analysis */ private static int searchFloor; /** bottom limit to output for item view analysis */ private static int itemFloor; /** number of items from most popular to be looked up in the database */ private static int itemLookup; /** mode to use for user email display */ private static String userEmail; /** URL of the service being analysed */ private static String url; /** Name of the service being analysed */ private static String name; /** Name of the service being analysed */ private static String hostName; /** the average number of views per item */ private static int views = 0; /////////////////////// // regular expressions /////////////////////// /** Exclude characters regular expression pattern */ private static Pattern excludeCharRX = null; /** handle indicator string regular expression pattern */ private static Pattern handleRX = null; /** item id indicator string regular expression pattern */ private static Pattern itemRX = null; /** query string indicator regular expression pattern */ private static Pattern queryRX = null; /** collection indicator regular expression pattern */ private static Pattern collectionRX = null; /** community indicator regular expression pattern */ private static Pattern communityRX = null; /** results indicator regular expression pattern */ private static Pattern resultsRX = null; /** single character regular expression pattern */ private static Pattern singleRX = null; /** a pattern to match a valid version 1.3 log file line */ private static Pattern valid13 = null; /** a pattern to match a valid version 1.4 log file line */ private static Pattern valid14 = null; /** pattern to match valid log file names */ private static Pattern logRegex = null; /** pattern to match commented out lines from the config file */ private static Pattern comment = Pattern.compile("^#"); /** pattern to match genuine lines from the config file */ private static Pattern real = Pattern.compile("^(.+)=(.+)"); /** pattern to match all search types */ private static Pattern typeRX = null; /** pattern to match all search types */ private static Pattern wordRX = null; ////////////////////////// // Miscellaneous variables ////////////////////////// /** process timing clock */ private static Calendar startTime = null; ///////////////////////// // command line options //////////////////////// /** the log directory to be analysed */ private static String logDir = ConfigurationManager.getProperty("log.dir"); /** the regex to describe the file name format */ private static String fileTemplate = "dspace\\.log.*"; /** the config file from which to configure the analyser */ public static String configFile = ConfigurationManager.getProperty("dspace.dir") + File.separator + "config" + File.separator + "dstat.cfg"; /** the output file to which to write aggregation data */ private static String outFile = ConfigurationManager.getProperty("log.dir") + File.separator + "dstat.dat"; /** the starting date of the report */ private static Date startDate = null; /** the end date of the report */ private static Date endDate = null; /** the starting date of the report as obtained from the log files */ private static Date logStartDate = null; /** the end date of the report as obtained from the log files */ private static Date logEndDate = null; /** are we looking stuff up in the database */ private static boolean lookUp = false; /** * main method to be run from command line. See usage information for * details as to how to use the command line flags (-help) */ public static void main(String [] argv) throws Exception, SQLException { // first, start the processing clock startTime = new GregorianCalendar(); // create context as super user Context context = new Context(); context.setIgnoreAuthorization(true); // set up our command line variables String myLogDir = null; String myFileTemplate = null; String myConfigFile = null; String myOutFile = null; Date myStartDate = null; Date myEndDate = null; boolean myLookUp = false; // read in our command line options for (int i = 0; i < argv.length; i++) { if (argv[i].equals("-log")) { myLogDir = argv[i+1]; } if (argv[i].equals("-file")) { myFileTemplate = argv[i+1]; } if (argv[i].equals("-cfg")) { myConfigFile = argv[i+1]; } if (argv[i].equals("-out")) { myOutFile = argv[i+1]; } if (argv[i].equals("-help")) { LogAnalyser.usage(); System.exit(0); } if (argv[i].equals("-start")) { myStartDate = parseDate(argv[i+1]); } if (argv[i].equals("-end")) { myEndDate = parseDate(argv[i+1]); } if (argv[i].equals("-lookup")) { myLookUp = true; } } // now call the method which actually processes the logs processLogs(context, myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); } /** * using the pre-configuration information passed here, analyse the logs * and produce the aggregation file * * @param context the DSpace context object this occurs under * @param myLogDir the passed log directory. Uses default if null * @param myFileTemplate the passed file name regex. Uses default if null * @param myConfigFile the DStat config file. Uses default if null * @param myOutFile the file to which to output aggregation data. Uses default if null * @param myStartDate the desired start of the analysis. Starts from the beginning otherwise * @param myEndDate the desired end of the analysis. Goes to the end otherwise * @param myLookUp force a lookup of the database */ public static void processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) throws IOException, SQLException { // FIXME: perhaps we should have all parameters and aggregators put // together in a single aggregating object // if the timer has not yet been started, then start it startTime = new GregorianCalendar(); //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // set the parameters for this analysis setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); // pre prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; // read in the config information, throwing an error if we fail to open // the given config file readConfig(configFile); // assemble the regular expressions for later use (requires the file // template to build the regex to match it setRegex(fileTemplate); // get the log files File[] logFiles = getLogFiles(logDir); // standard loop counter int i = 0; // for every log file do analysis // FIXME: it is easy to implement not processing log files after the // dates exceed the end boundary, but is there an easy way to do it // for the start of the file? Note that we can assume that the contents // of the log file are sequential, but can we assume the files are // provided in a data sequence? for (i = 0; i < logFiles.length; i++) { // check to see if this file is a log file agains the global regex Matcher matchRegex = logRegex.matcher(logFiles[i].getName()); if (matchRegex.matches()) { // if it is a log file, open it up and lets have a look at the // contents. try { fr = new FileReader(logFiles[i].toString()); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read log file " + logFiles[i].toString()); System.exit(0); } // for each line in the file do the analysis // FIXME: perhaps each section needs to be dolled out to an // analysing class to allow pluggability of other methods of // analysis, and ease of code reading too - Pending further thought String line = null; while ((line = br.readLine()) != null) { // get the log line object LogLine logLine = getLogLine(line); // if there are line segments get on with the analysis if (logLine != null) { // first find out if we are constraining by date and // if so apply the restrictions - if (!logLine.afterDate(startDate)) + if ((startDate != null) && (!logLine.afterDate(startDate))) { continue; } - if (!logLine.beforeDate(endDate)) + if ((endDate !=null) && (!logLine.beforeDate(endDate))) { break; } // count the number of lines parsed lineCount++; // if we are not constrained by date, register the date // as the start/end date if it is the earliest/latest so far // FIXME: this should probably have a method of its own if (startDate == null) { if (logStartDate != null) { if (logLine.beforeDate(logStartDate)) { logStartDate = logLine.getDate(); } } else { logStartDate = logLine.getDate(); } } if (endDate == null) { if (logEndDate != null) { if (logLine.afterDate(logEndDate)) { logEndDate = logLine.getDate(); } } else { logEndDate = logLine.getDate(); } } // count the warnings if (logLine.isLevel("WARN")) { // FIXME: really, this ought to be some kind of level // aggregator warnCount++; } // is the action a search? if (logLine.isAction("search")) { // get back all the valid search words from the query String[] words = analyseQuery(logLine.getParams()); // for each search word add to the aggregator or // increment the aggregator's counter for (int j = 0; j < words.length; j++) { // FIXME: perhaps aggregators ought to be objects // themselves searchAggregator.put(words[j], increment(searchAggregator, words[j])); } } // is the action a login, and are we counting user logins? if (logLine.isAction("login") && !userEmail.equals("off")) { userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser())); } // is the action an item view? if (logLine.isAction("view_item")) { String handle = logLine.getParams(); // strip the handle string Matcher matchHandle = handleRX.matcher(handle); handle = matchHandle.replaceAll(""); // strip the item id string Matcher matchItem = itemRX.matcher(handle); handle = matchItem.replaceAll(""); handle.trim(); // either add the handle to the aggregator or // increment its counter itemAggregator.put(handle, increment(itemAggregator, handle)); } // log all the activity actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction())); } } // close the file reading buffers br.close(); fr.close(); } } // do we want to do a database lookup? Do so only if the start and // end dates are null or lookUp is true // FIXME: this is a kind of separate section. Would it be worth building // the summary string separately and then inserting it into the real // summary later? Especially if we make the archive analysis more complex archiveStats.put("All Items", getNumItems(context)); for (i = 0; i < itemTypes.size(); i++) { archiveStats.put(itemTypes.get(i), getNumItems(context, (String) itemTypes.get(i))); } // now do the host name and url lookup hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); name = ConfigurationManager.getProperty("dspace.name").trim(); url = ConfigurationManager.getProperty("dspace.url").trim(); if ((url != null) && (!url.endsWith("/"))) { url = url + "/"; } // do the average views analysis if (((Integer) archiveStats.get("All Items")).intValue() != 0) { // FIXME: this is dependent on their being a query on the db, which // there might not always be if it becomes configurable Double avg = new Double( Math.ceil( ((Integer) actionAggregator.get("view_item")).intValue() / ((Integer) archiveStats.get("All Items")).intValue())); views = avg.intValue(); } // finally, write the output createOutput(); return; } /** * set the passed parameters up as global class variables. This has to * be done in a separate method because the API permits for running from * the command line with args or calling the processLogs method statically * from elsewhere * * @param myLogDir the log file directory to be analysed * @param myFileTemplate regex for log file names * @param myConfigFile config file to use for dstat * @param myOutFile file to write the aggregation into * @param myStartDate requested log reporting start date * @param myEndDate requested log reporting end date * @param myLookUp requested look up force flag */ public static void setParameters(String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) { if (myLogDir != null) { logDir = myLogDir; } if (myFileTemplate != null) { fileTemplate = myFileTemplate; } if (myConfigFile != null) { configFile = myConfigFile; } if (myStartDate != null) { startDate = myStartDate; } if (myEndDate != null) { endDate = myEndDate; } if (myLogDir != null) { lookUp = myLookUp; } if (myOutFile != null) { outFile = myOutFile; } return; } /** * generate the analyser's output to the specified out file */ public static void createOutput() { // start a string buffer to hold the final output StringBuffer summary = new StringBuffer(); // define an iterator that will be used to go over the hashmap keys Iterator keys = null; // output the number of lines parsed summary.append("log_lines=" + Integer.toString(lineCount) + "\n"); // output the number of warnings encountered summary.append("warnings=" + Integer.toString(warnCount) + "\n"); // set the general summary config up in the aggregator file for (int i = 0; i < generalSummary.size(); i++) { summary.append("general_summary=" + generalSummary.get(i) + "\n"); } // output the host name summary.append("server_name=" + hostName + "\n"); // output the service name summary.append("service_name=" + name + "\n"); // output the date information if necessary SimpleDateFormat sdf = new SimpleDateFormat("dd'/'MM'/'yyyy"); if (startDate != null) { summary.append("start_date=" + sdf.format(startDate) + "\n"); } else if (logStartDate != null) { summary.append("start_date=" + sdf.format(logStartDate) + "\n"); } if (endDate != null) { summary.append("end_date=" + sdf.format(endDate) + "\n"); } else if (logEndDate != null) { summary.append("end_date=" + sdf.format(logEndDate) + "\n"); } // write out the archive stats keys = archiveStats.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); summary.append("archive." + key + "=" + archiveStats.get(key) + "\n"); } // write out the action aggregation results keys = actionAggregator.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); summary.append("action." + key + "=" + actionAggregator.get(key) + "\n"); } // depending on the config settings for reporting on emails output the // login information summary.append("user_email=" + userEmail + "\n"); int address = 1; keys = userAggregator.keySet().iterator(); // for each email address either write out the address and the count // or alias it with an "Address X" label, to keep the data confidential // FIXME: the users reporting should also have a floor value while (keys.hasNext()) { String key = (String) keys.next(); summary.append("user."); if (userEmail.equals("on")) { summary.append(key + "=" + userAggregator.get(key) + "\n"); } else if (userEmail.equals("alias")) { summary.append("Address " + Integer.toString(address++) + "=" + userAggregator.get(key) + "\n"); } } // FIXME: all values which have floors set should provide an "other" // record which counts how many other things which didn't make it into // the listing there are // output the search word information summary.append("search_floor=" + searchFloor + "\n"); keys = searchAggregator.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (((Integer) searchAggregator.get(key)).intValue() >= searchFloor) { summary.append("search." + key + "=" + searchAggregator.get(key) + "\n"); } } // FIXME: we should do a lot more with the search aggregator // Possible feature list: // - constrain by collection/community perhaps? // - we should consider building our own aggregator class which can // be full of rich data. Perhaps this and the Stats class should // be the same thing. // item viewing information summary.append("item_floor=" + itemFloor + "\n"); summary.append("host_url=" + url + "\n"); summary.append("item_lookup=" + itemLookup + "\n"); // write out the item access information keys = itemAggregator.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (((Integer) itemAggregator.get(key)).intValue() >= itemFloor) { summary.append("item." + key + "=" + itemAggregator.get(key) + "\n"); } } // output the average views per item if (views > 0) { summary.append("avg_item_views=" + views + "\n"); } // insert the analysis processing time information Calendar endTime = new GregorianCalendar(); long timeInMillis = (endTime.getTimeInMillis() - startTime.getTimeInMillis()); summary.append("analysis_process_time=" + Long.toString(timeInMillis / 1000) + "\n"); // finally write the string into the output file try { BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); out.write(summary.toString()); out.flush(); out.close(); } catch (IOException e) { System.out.println("Unable to write to output file " + outFile); System.exit(0); } return; } /** * get an array of file objects representing the passed log directory * * @param logDir the log directory in which to pick up files * * @return an array of file objects representing the given logDir */ public static File[] getLogFiles(String logDir) { // open the log files directory, read in the files, check that they // match the passed regular expression then analyse the content File logs = new File(logDir); // if log dir is not a directory throw and error and exit if (!logs.isDirectory()) { System.out.println("Passed log directory is not a directory"); System.exit(0); } // get the files in the directory return logs.listFiles(); } /** * set up the regular expressions to be used by this analyser. Mostly this * exists to provide a degree of segregation and readability to the code * and to ensure that you only need to set up the regular expressions to * be used once * * @param fileTemplate the regex to be used to identify dspace log files */ public static void setRegex(String fileTemplate) { // build the exclude characters regular expression StringBuffer charRegEx = new StringBuffer(); charRegEx.append("["); for (int i = 0; i < excludeChars.size(); i++) { charRegEx.append("\\" + (String) excludeChars.get(i)); } charRegEx.append("]"); excludeCharRX = Pattern.compile(charRegEx.toString()); // regular expression to find handle indicators in strings handleRX = Pattern.compile("handle="); // regular expression to find item_id indicators in strings itemRX = Pattern.compile(",item_id=.*$"); // regular expression to find query indicators in strings queryRX = Pattern.compile("query="); // regular expression to find collections in strings collectionRX = Pattern.compile("collection_id=[0-9]*,"); // regular expression to find communities in strings communityRX = Pattern.compile("community_id=[0-9]*,"); // regular expression to find search result sets resultsRX = Pattern.compile(",results=(.*)"); // regular expressions to find single characters anywhere in the string singleRX = Pattern.compile("( . |^. | .$)"); // set up the standard log file line regular expression String logLine13 = "^(\\d\\d\\d\\d-\\d\\d\\-\\d\\d) \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d (\\w+)\\s+\\S+ @ ([^:]+):[^:]+:([^:]+):(.*)"; String logLine14 = "^(\\d\\d\\d\\d-\\d\\d\\-\\d\\d) \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d (\\w+)\\s+\\S+ @ ([^:]+):[^:]+:[^:]+:([^:]+):(.*)"; valid13 = Pattern.compile(logLine13); valid14 = Pattern.compile(logLine14); // set up the pattern for validating log file names logRegex = Pattern.compile(fileTemplate); // set up the pattern for matching any of the query types StringBuffer typeRXString = new StringBuffer(); typeRXString.append("("); for (int i = 0; i < excludeTypes.size(); i++) { if (i > 0) { typeRXString.append("|"); } typeRXString.append((String) excludeTypes.get(i)); } typeRXString.append(")"); typeRX = Pattern.compile(typeRXString.toString()); // set up the pattern for matching any of the words to exclude StringBuffer wordRXString = new StringBuffer(); wordRXString.append("("); for (int i = 0; i < excludeWords.size(); i++) { if (i > 0) { wordRXString.append("|"); } wordRXString.append(" " + (String) excludeWords.get(i) + " "); wordRXString.append("|"); wordRXString.append("^" + (String) excludeWords.get(i) + " "); wordRXString.append("|"); wordRXString.append(" " + (String) excludeWords.get(i) + "$"); } wordRXString.append(")"); wordRX = Pattern.compile(wordRXString.toString()); return; } /** * read in the given config file and populate the class globals * * @param configFile the config file to read in */ public static void readConfig(String configFile) throws IOException { //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; String record = null; try { fr = new FileReader(configFile); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read config file: " + configFile); System.exit(0); } // read in the config file and set up our instance variables while ((record = br.readLine()) != null) { // check to see what kind of line we have Matcher matchComment = comment.matcher(record); Matcher matchReal = real.matcher(record); // if the line is not a comment and is real, read it in if (!matchComment.matches() && matchReal.matches()) { // lift the values out of the matcher's result groups String key = matchReal.group(1).trim(); String value = matchReal.group(2).trim(); // read the config values into our instance variables (see // documentation for more info on config params) if (key.equals("general.summary")) { actionAggregator.put(value, new Integer(0)); generalSummary.add(value); } if (key.equals("exclude.word")) { excludeWords.add(value); } if (key.equals("exclude.type")) { excludeTypes.add(value); } if (key.equals("exclude.character")) { excludeChars.add(value); } if (key.equals("item.type")) { itemTypes.add(value); } if (key.equals("item.floor")) { itemFloor = Integer.parseInt(value); } if (key.equals("search.floor")) { searchFloor = Integer.parseInt(value); } if (key.equals("item.lookup")) { itemLookup = Integer.parseInt(value); } if (key.equals("user.email")) { userEmail = value; } } } // close the inputs br.close(); fr.close(); return; } /** * increment the value of the given map at the given key by one. * * @param map the map whose value we want to increase * @param key the key of the map whose value to increase * * @return an integer object containing the new value */ public static Integer increment(Map map, String key) { Integer newValue = null; if (map.containsKey(key)) { // FIXME: this seems like a ridiculous way to add Integers newValue = new Integer(((Integer) map.get(key)).intValue() + 1); } else { newValue = new Integer(1); } return newValue; } /** * Take the standard date string requested at the command line and convert * it into a Date object. Throws and error and exits if the date does * not parse * * @param date the string representation of the date * * @return a date object containing the date, with the time set to * 00:00:00 */ public static Date parseDate(String date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd"); Date parsedDate = null; try { parsedDate = sdf.parse(date); } catch (ParseException e) { System.out.println("The date is not in the correct format"); System.exit(0); } return parsedDate; } /** * Take the date object and convert it into a string of the form YYYY-MM-DD * * @param date the date to be converted * * @return A string of the form YYYY-MM-DD */ public static String unParseDate(Date date) { // Use SimpleDateFormat SimpleDateFormat sdf = new SimpleDateFormat("yyyy'-'MM'-'dd"); return sdf.format(date); } /** * Take a search query string and pull out all of the meaningful information * from it, giving the results in the form of a String array, a single word * to each element * * @param query the search query to be analysed * * @return the string array containing meaningful search terms */ public static String[] analyseQuery(String query) { // register our standard loop counter int i = 0; // make the query string totally lower case, to ensure we don't miss out // on matches due to capitalisation query = query.toLowerCase(); // now perform successive find and replace operations using pre-defined // global regular expressions Matcher matchQuery = queryRX.matcher(query); query = matchQuery.replaceAll(" "); Matcher matchCollection = collectionRX.matcher(query); query = matchCollection.replaceAll(" "); Matcher matchCommunity = communityRX.matcher(query); query = matchCommunity.replaceAll(" "); Matcher matchResults = resultsRX.matcher(query); query = matchResults.replaceAll(" "); Matcher matchTypes = typeRX.matcher(query); query = matchTypes.replaceAll(" "); Matcher matchChars = excludeCharRX.matcher(query); query = matchChars.replaceAll(" "); Matcher matchWords = wordRX.matcher(query); query = matchWords.replaceAll(" "); Matcher single = singleRX.matcher(query); query = single.replaceAll(" "); // split the remaining string by whitespace, trim and stuff into an // array to be returned StringTokenizer st = new StringTokenizer(query); String[] words = new String[st.countTokens()]; for (i = 0; i < words.length; i++) { words[i] = st.nextToken().trim(); } // FIXME: some single characters are still slipping through the net; // why? and how do we fix it? return words; } /** * split the given line into it's relevant segments if applicable (i.e. the * line matches the required regular expression. * * @param line the line to be segmented * @return a Log Line object for the given line */ public static LogLine getLogLine(String line) { // FIXME: consider moving this code into the LogLine class. To do this // we need to much more carefully define the structure and behaviour // of the LogLine class Matcher match; if (line.indexOf(":ip_addr") > 0) { match = valid14.matcher(line); } else { match = valid13.matcher(line); } if (match.matches()) { // set up a new log line object LogLine logLine = new LogLine(parseDate(match.group(1).trim()), LogManager.unescapeLogField(match.group(2)).trim(), LogManager.unescapeLogField(match.group(3)).trim(), LogManager.unescapeLogField(match.group(4)).trim(), LogManager.unescapeLogField(match.group(5)).trim()); return logLine; } else { return null; } } /** * get the number of items in the archive which were accessioned between * the provided start and end dates, with the given value for the DC field * 'type' (unqualified) * * @param context the DSpace context for the action * @param type value for DC field 'type' (unqualified) * * @return an integer containing the relevant count */ public static Integer getNumItems(Context context, String type) throws SQLException { boolean oracle = false; if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { oracle = true; } // FIXME: this method is clearly not optimised // FIXME: we don't yet collect total statistics, such as number of items // withdrawn, number in process of submission etc. We should probably do // that // start the type constraint String typeQuery = null; if (type != null) { typeQuery = "SELECT item_id " + "FROM metadatavalue " + "WHERE text_value LIKE '%" + type + "%' " + "AND metadata_field_id = (" + " SELECT metadata_field_id " + " FROM metadatafieldregistry " + " WHERE element = 'type' " + " AND qualifier IS NULL) "; } // start the date constraint query buffer StringBuffer dateQuery = new StringBuffer(); if (oracle) { dateQuery.append("SELECT /*+ ORDERED_PREDICATES */ item_id "); } else { dateQuery.append("SELECT item_id "); } dateQuery.append("FROM metadatavalue " + "WHERE metadata_field_id = (" + " SELECT metadata_field_id " + " FROM metadatafieldregistry " + " WHERE element = 'date' " + " AND qualifier = 'accessioned') "); if (startDate != null) { if (oracle) { dateQuery.append(" AND TO_TIMESTAMP( TO_CHAR(text_value), "+ "'yyyy-mm-dd\"T\"hh24:mi:ss\"Z\"' ) > TO_DATE('" + unParseDate(startDate) + "', 'yyyy-MM-dd') "); } else { dateQuery.append(" AND text_value::timestamp > '" + unParseDate(startDate) + "'::timestamp "); } } if (endDate != null) { if (oracle) { dateQuery.append(" AND TO_TIMESTAMP( TO_CHAR(text_value), "+ "'yyyy-mm-dd\"T\"hh24:mi:ss\"Z\"' ) < TO_DATE('" + unParseDate(endDate) + "', 'yyyy-MM-dd') "); } else { dateQuery.append(" AND text_value::timestamp < '" + unParseDate(endDate) + "'::timestamp "); } } // build the final query StringBuffer query = new StringBuffer(); query.append("SELECT COUNT(*) AS num " + "FROM item " + "WHERE in_archive = " + (oracle ? "1 " : "true ") + "AND withdrawn = " + (oracle ? "0 " : "false ")); if (startDate != null || endDate != null) { query.append(" AND item_id IN ( " + dateQuery.toString() + ") "); } if (type != null) { query.append(" AND item_id IN ( " + typeQuery + ") "); } TableRow row = DatabaseManager.querySingle(context, query.toString()); Integer numItems; if (oracle) { numItems = new Integer(row.getIntColumn("num")); } else { // for some reason the number column is of "long" data type! Long count = new Long(row.getLongColumn("num")); numItems = new Integer(count.intValue()); } return numItems; } /** * get the total number of items in the archive at time of execution, * ignoring all other constraints * * @param context the DSpace context the action is being performed in * * @return an Integer containing the number of items in the * archive */ public static Integer getNumItems(Context context) throws SQLException { return getNumItems(context, null); } /** * print out the usage information for this class to the standard out */ public static void usage() { String usage = "Usage Information:\n" + "LogAnalyser [options [parameters]]\n" + "-log [log directory]\n" + "\tOptional\n" + "\tSpecify a directory containing log files\n" + "\tDefault uses [dspace.dir]/log from dspace.cfg\n" + "-file [file name regex]\n" + "\tOptional\n" + "\tSpecify a regular expression as the file name template.\n" + "\tCurrently this needs to be correctly escaped for Java string handling (FIXME)\n" + "\tDefault uses dspace.log*\n" + "-cfg [config file path]\n" + "\tOptional\n" + "\tSpecify a config file to be used\n" + "\tDefault uses dstat.cfg in dspace config directory\n" + "-out [output file path]\n" + "\tOptional\n" + "\tSpecify an output file to write results into\n" + "\tDefault uses dstat.dat in dspace log directory\n" + "-start [YYYY-MM-DD]\n" + "\tOptional\n" + "\tSpecify the start date of the analysis\n" + "\tIf a start date is specified then no attempt to gather \n" + "\tcurrent database statistics will be made unless -lookup is\n" + "\talso passed\n" + "\tDefault is to start from the earliest date records exist for\n" + "-end [YYYY-MM-DD]\n" + "\tOptional\n" + "\tSpecify the end date of the analysis\n" + "\tIf an end date is specified then no attempt to gather \n" + "\tcurrent database statistics will be made unless -lookup is\n" + "\talso passed\n" + "\tDefault is to work up to the last date records exist for\n" + "-lookup\n" + "\tOptional\n" + "\tForce a lookup of the current database statistics\n" + "\tOnly needs to be used if date constraints are also in place\n" + "-help\n" + "\tdisplay this usage information\n"; System.out.println(usage); } }
false
true
public static void processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) throws IOException, SQLException { // FIXME: perhaps we should have all parameters and aggregators put // together in a single aggregating object // if the timer has not yet been started, then start it startTime = new GregorianCalendar(); //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // set the parameters for this analysis setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); // pre prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; // read in the config information, throwing an error if we fail to open // the given config file readConfig(configFile); // assemble the regular expressions for later use (requires the file // template to build the regex to match it setRegex(fileTemplate); // get the log files File[] logFiles = getLogFiles(logDir); // standard loop counter int i = 0; // for every log file do analysis // FIXME: it is easy to implement not processing log files after the // dates exceed the end boundary, but is there an easy way to do it // for the start of the file? Note that we can assume that the contents // of the log file are sequential, but can we assume the files are // provided in a data sequence? for (i = 0; i < logFiles.length; i++) { // check to see if this file is a log file agains the global regex Matcher matchRegex = logRegex.matcher(logFiles[i].getName()); if (matchRegex.matches()) { // if it is a log file, open it up and lets have a look at the // contents. try { fr = new FileReader(logFiles[i].toString()); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read log file " + logFiles[i].toString()); System.exit(0); } // for each line in the file do the analysis // FIXME: perhaps each section needs to be dolled out to an // analysing class to allow pluggability of other methods of // analysis, and ease of code reading too - Pending further thought String line = null; while ((line = br.readLine()) != null) { // get the log line object LogLine logLine = getLogLine(line); // if there are line segments get on with the analysis if (logLine != null) { // first find out if we are constraining by date and // if so apply the restrictions if (!logLine.afterDate(startDate)) { continue; } if (!logLine.beforeDate(endDate)) { break; } // count the number of lines parsed lineCount++; // if we are not constrained by date, register the date // as the start/end date if it is the earliest/latest so far // FIXME: this should probably have a method of its own if (startDate == null) { if (logStartDate != null) { if (logLine.beforeDate(logStartDate)) { logStartDate = logLine.getDate(); } } else { logStartDate = logLine.getDate(); } } if (endDate == null) { if (logEndDate != null) { if (logLine.afterDate(logEndDate)) { logEndDate = logLine.getDate(); } } else { logEndDate = logLine.getDate(); } } // count the warnings if (logLine.isLevel("WARN")) { // FIXME: really, this ought to be some kind of level // aggregator warnCount++; } // is the action a search? if (logLine.isAction("search")) { // get back all the valid search words from the query String[] words = analyseQuery(logLine.getParams()); // for each search word add to the aggregator or // increment the aggregator's counter for (int j = 0; j < words.length; j++) { // FIXME: perhaps aggregators ought to be objects // themselves searchAggregator.put(words[j], increment(searchAggregator, words[j])); } } // is the action a login, and are we counting user logins? if (logLine.isAction("login") && !userEmail.equals("off")) { userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser())); } // is the action an item view? if (logLine.isAction("view_item")) { String handle = logLine.getParams(); // strip the handle string Matcher matchHandle = handleRX.matcher(handle); handle = matchHandle.replaceAll(""); // strip the item id string Matcher matchItem = itemRX.matcher(handle); handle = matchItem.replaceAll(""); handle.trim(); // either add the handle to the aggregator or // increment its counter itemAggregator.put(handle, increment(itemAggregator, handle)); } // log all the activity actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction())); } } // close the file reading buffers br.close(); fr.close(); } } // do we want to do a database lookup? Do so only if the start and // end dates are null or lookUp is true // FIXME: this is a kind of separate section. Would it be worth building // the summary string separately and then inserting it into the real // summary later? Especially if we make the archive analysis more complex archiveStats.put("All Items", getNumItems(context)); for (i = 0; i < itemTypes.size(); i++) { archiveStats.put(itemTypes.get(i), getNumItems(context, (String) itemTypes.get(i))); } // now do the host name and url lookup hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); name = ConfigurationManager.getProperty("dspace.name").trim(); url = ConfigurationManager.getProperty("dspace.url").trim(); if ((url != null) && (!url.endsWith("/"))) { url = url + "/"; } // do the average views analysis if (((Integer) archiveStats.get("All Items")).intValue() != 0) { // FIXME: this is dependent on their being a query on the db, which // there might not always be if it becomes configurable Double avg = new Double( Math.ceil( ((Integer) actionAggregator.get("view_item")).intValue() / ((Integer) archiveStats.get("All Items")).intValue())); views = avg.intValue(); } // finally, write the output createOutput(); return; }
public static void processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile, String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp) throws IOException, SQLException { // FIXME: perhaps we should have all parameters and aggregators put // together in a single aggregating object // if the timer has not yet been started, then start it startTime = new GregorianCalendar(); //instantiate aggregators actionAggregator = new HashMap(); searchAggregator = new HashMap(); userAggregator = new HashMap(); itemAggregator = new HashMap(); archiveStats = new HashMap(); //instantiate lists generalSummary = new ArrayList(); excludeWords = new ArrayList(); excludeTypes = new ArrayList(); excludeChars = new ArrayList(); itemTypes = new ArrayList(); // set the parameters for this analysis setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp); // pre prepare our standard file readers and buffered readers FileReader fr = null; BufferedReader br = null; // read in the config information, throwing an error if we fail to open // the given config file readConfig(configFile); // assemble the regular expressions for later use (requires the file // template to build the regex to match it setRegex(fileTemplate); // get the log files File[] logFiles = getLogFiles(logDir); // standard loop counter int i = 0; // for every log file do analysis // FIXME: it is easy to implement not processing log files after the // dates exceed the end boundary, but is there an easy way to do it // for the start of the file? Note that we can assume that the contents // of the log file are sequential, but can we assume the files are // provided in a data sequence? for (i = 0; i < logFiles.length; i++) { // check to see if this file is a log file agains the global regex Matcher matchRegex = logRegex.matcher(logFiles[i].getName()); if (matchRegex.matches()) { // if it is a log file, open it up and lets have a look at the // contents. try { fr = new FileReader(logFiles[i].toString()); br = new BufferedReader(fr); } catch (IOException e) { System.out.println("Failed to read log file " + logFiles[i].toString()); System.exit(0); } // for each line in the file do the analysis // FIXME: perhaps each section needs to be dolled out to an // analysing class to allow pluggability of other methods of // analysis, and ease of code reading too - Pending further thought String line = null; while ((line = br.readLine()) != null) { // get the log line object LogLine logLine = getLogLine(line); // if there are line segments get on with the analysis if (logLine != null) { // first find out if we are constraining by date and // if so apply the restrictions if ((startDate != null) && (!logLine.afterDate(startDate))) { continue; } if ((endDate !=null) && (!logLine.beforeDate(endDate))) { break; } // count the number of lines parsed lineCount++; // if we are not constrained by date, register the date // as the start/end date if it is the earliest/latest so far // FIXME: this should probably have a method of its own if (startDate == null) { if (logStartDate != null) { if (logLine.beforeDate(logStartDate)) { logStartDate = logLine.getDate(); } } else { logStartDate = logLine.getDate(); } } if (endDate == null) { if (logEndDate != null) { if (logLine.afterDate(logEndDate)) { logEndDate = logLine.getDate(); } } else { logEndDate = logLine.getDate(); } } // count the warnings if (logLine.isLevel("WARN")) { // FIXME: really, this ought to be some kind of level // aggregator warnCount++; } // is the action a search? if (logLine.isAction("search")) { // get back all the valid search words from the query String[] words = analyseQuery(logLine.getParams()); // for each search word add to the aggregator or // increment the aggregator's counter for (int j = 0; j < words.length; j++) { // FIXME: perhaps aggregators ought to be objects // themselves searchAggregator.put(words[j], increment(searchAggregator, words[j])); } } // is the action a login, and are we counting user logins? if (logLine.isAction("login") && !userEmail.equals("off")) { userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser())); } // is the action an item view? if (logLine.isAction("view_item")) { String handle = logLine.getParams(); // strip the handle string Matcher matchHandle = handleRX.matcher(handle); handle = matchHandle.replaceAll(""); // strip the item id string Matcher matchItem = itemRX.matcher(handle); handle = matchItem.replaceAll(""); handle.trim(); // either add the handle to the aggregator or // increment its counter itemAggregator.put(handle, increment(itemAggregator, handle)); } // log all the activity actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction())); } } // close the file reading buffers br.close(); fr.close(); } } // do we want to do a database lookup? Do so only if the start and // end dates are null or lookUp is true // FIXME: this is a kind of separate section. Would it be worth building // the summary string separately and then inserting it into the real // summary later? Especially if we make the archive analysis more complex archiveStats.put("All Items", getNumItems(context)); for (i = 0; i < itemTypes.size(); i++) { archiveStats.put(itemTypes.get(i), getNumItems(context, (String) itemTypes.get(i))); } // now do the host name and url lookup hostName = ConfigurationManager.getProperty("dspace.hostname").trim(); name = ConfigurationManager.getProperty("dspace.name").trim(); url = ConfigurationManager.getProperty("dspace.url").trim(); if ((url != null) && (!url.endsWith("/"))) { url = url + "/"; } // do the average views analysis if (((Integer) archiveStats.get("All Items")).intValue() != 0) { // FIXME: this is dependent on their being a query on the db, which // there might not always be if it becomes configurable Double avg = new Double( Math.ceil( ((Integer) actionAggregator.get("view_item")).intValue() / ((Integer) archiveStats.get("All Items")).intValue())); views = avg.intValue(); } // finally, write the output createOutput(); return; }
diff --git a/src/de/raptor2101/GalDroid/Activities/ImageViewActivity.java b/src/de/raptor2101/GalDroid/Activities/ImageViewActivity.java index f816c54..8c8a151 100644 --- a/src/de/raptor2101/GalDroid/Activities/ImageViewActivity.java +++ b/src/de/raptor2101/GalDroid/Activities/ImageViewActivity.java @@ -1,216 +1,216 @@ /* * GalDroid - a webgallery frontend for android * Copyright (C) 2011 Raptor 2101 [[email protected]] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.raptor2101.GalDroid.Activities; import java.util.List; import android.graphics.Matrix; import android.graphics.PointF; import android.os.Bundle; import android.util.FloatMath; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Gallery; import de.raptor2101.GalDroid.R; import de.raptor2101.GalDroid.WebGallery.GalleryImageAdapter; import de.raptor2101.GalDroid.WebGallery.GalleryImageAdapter.DisplayTarget; import de.raptor2101.GalDroid.WebGallery.GalleryImageAdapter.TitleConfig; import de.raptor2101.GalDroid.WebGallery.GalleryImageView; import de.raptor2101.GalDroid.WebGallery.Interfaces.GalleryObject; public class ImageViewActivity extends GalleryActivity implements OnTouchListener, OnItemSelectedListener { private enum TouchMode { None, Drag, Zoom, } private Gallery mGalleryFullscreen; private Gallery mGalleryThumbnails; private PointF mScalePoint = new PointF(); private float mTouchStartY, mTouchStartX, mOldDist=1, minDragHeight; private GalleryImageAdapter mAdapterFullscreen,mAdapterThumbnails; private TouchMode mTouchMode; @Override public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.image_view_activity); mGalleryFullscreen = (Gallery) findViewById(R.id.singleImageGallery); mGalleryThumbnails = (Gallery) findViewById(R.id.thumbnailImageGallery); mGalleryFullscreen.setSystemUiVisibility(View.STATUS_BAR_HIDDEN); mGalleryFullscreen.setWillNotCacheDrawing(true); mGalleryFullscreen.setWillNotCacheDrawing(true); LayoutParams params = this.getWindow().getAttributes(); minDragHeight = params.height/5f; mAdapterFullscreen = new GalleryImageAdapter(this, new Gallery.LayoutParams(params.width,params.height)); mAdapterFullscreen.setTitleConfig(TitleConfig.HideTitle); mAdapterFullscreen.setDisplayTarget(DisplayTarget.FullScreen); mGalleryFullscreen.setAdapter(mAdapterFullscreen); mAdapterThumbnails = new GalleryImageAdapter(this, new Gallery.LayoutParams(100,100)); mAdapterThumbnails.setTitleConfig(TitleConfig.HideTitle); mAdapterThumbnails.setDisplayTarget(DisplayTarget.Thumbnails); mGalleryThumbnails.setAdapter(mAdapterThumbnails); mGalleryFullscreen.setOnTouchListener(this); mGalleryFullscreen.setOnItemSelectedListener(this); mGalleryThumbnails.setOnItemSelectedListener(this); super.onCreate(savedInstanceState); } @Override public void onBackPressed() { GalleryImageAdapter adapter = (GalleryImageAdapter) mGalleryFullscreen.getAdapter(); adapter.cleanUp(); adapter = (GalleryImageAdapter) mGalleryThumbnails.getAdapter(); adapter.cleanUp(); super.onBackPressed(); } @Override protected void onResume() { GalleryImageAdapter adapter = (GalleryImageAdapter) mGalleryFullscreen.getAdapter(); adapter.refreshImages(); adapter = (GalleryImageAdapter) mGalleryThumbnails.getAdapter(); adapter.refreshImages(); super.onResume(); } public boolean onTouch(View v, MotionEvent event) { Log.d("ImageViewActivity", "EventAction: " + event.getAction()); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: mTouchStartY = event.getY(); mTouchStartX = event.getX(); mTouchMode = TouchMode.Drag; break; case MotionEvent.ACTION_POINTER_3_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: case MotionEvent.ACTION_POINTER_DOWN: - mOldDist = getSpacing(event); + /*mOldDist = getSpacing(event); if(mOldDist > 10f) { mTouchMode = TouchMode.Zoom; setScalePoint(event); - } + }*/ break; case MotionEvent.ACTION_POINTER_3_UP: case MotionEvent.ACTION_POINTER_2_UP: case MotionEvent.ACTION_POINTER_UP: mTouchMode = TouchMode.None; break; case MotionEvent.ACTION_UP: if(mTouchMode == TouchMode.Drag) { if(Math.abs(event.getX()-mTouchStartX) < 50) { float diffY = event.getY()-mTouchStartY; if(Math.abs(diffY)>minDragHeight) { if(diffY > 0 && mGalleryThumbnails.getVisibility() == View.VISIBLE) { mGalleryThumbnails.setVisibility(View.GONE); } else if(diffY < 0 && mGalleryThumbnails.getVisibility() == View.GONE) { mGalleryThumbnails.setVisibility(View.VISIBLE); } } } } break; case MotionEvent.ACTION_MOVE: if(mTouchMode == TouchMode.Zoom) { float dist = getSpacing(event); if(dist > 10f) { GalleryImageView imageView = (GalleryImageView) mGalleryFullscreen.getSelectedView(); float scale = dist/mOldDist; if(scale >= 1 && scale <= 10) { Log.d("ImageViewActivity", "ACTION_MOVE Scale:" + scale); Matrix matrix = imageView.getImageMatrix(); matrix.postScale(scale, scale, mScalePoint.x-imageView.getLeft(), mScalePoint.y-imageView.getTop()); imageView.setImageMatrix(matrix); } } } break; } return false; } private float getSpacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } private void setScalePoint(MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); mScalePoint.set(x / 2, y / 2); } public void onItemSelected(AdapterView<?> gallery, View view, int position, long arg3) { setCurrentIndex(position); if(gallery == mGalleryFullscreen){ mGalleryThumbnails.setSelection(position); } else { mGalleryFullscreen.setSelection(position); } } public void onNothingSelected(AdapterView<?> arg0) { // Empty Stub, cause nothing todo } @Override public void onGalleryObjectsLoaded(List<GalleryObject> galleryObjects) { mAdapterFullscreen.setGalleryObjects(galleryObjects); mAdapterThumbnails.setGalleryObjects(galleryObjects); int currentIndex = getCurrentIndex(); if(currentIndex == -1){ currentIndex = getIntent().getExtras().getInt("Current Index"); } mGalleryFullscreen.setSelection(currentIndex); mGalleryThumbnails.setSelection(currentIndex); } }
false
true
public boolean onTouch(View v, MotionEvent event) { Log.d("ImageViewActivity", "EventAction: " + event.getAction()); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: mTouchStartY = event.getY(); mTouchStartX = event.getX(); mTouchMode = TouchMode.Drag; break; case MotionEvent.ACTION_POINTER_3_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mOldDist = getSpacing(event); if(mOldDist > 10f) { mTouchMode = TouchMode.Zoom; setScalePoint(event); } break; case MotionEvent.ACTION_POINTER_3_UP: case MotionEvent.ACTION_POINTER_2_UP: case MotionEvent.ACTION_POINTER_UP: mTouchMode = TouchMode.None; break; case MotionEvent.ACTION_UP: if(mTouchMode == TouchMode.Drag) { if(Math.abs(event.getX()-mTouchStartX) < 50) { float diffY = event.getY()-mTouchStartY; if(Math.abs(diffY)>minDragHeight) { if(diffY > 0 && mGalleryThumbnails.getVisibility() == View.VISIBLE) { mGalleryThumbnails.setVisibility(View.GONE); } else if(diffY < 0 && mGalleryThumbnails.getVisibility() == View.GONE) { mGalleryThumbnails.setVisibility(View.VISIBLE); } } } } break; case MotionEvent.ACTION_MOVE: if(mTouchMode == TouchMode.Zoom) { float dist = getSpacing(event); if(dist > 10f) { GalleryImageView imageView = (GalleryImageView) mGalleryFullscreen.getSelectedView(); float scale = dist/mOldDist; if(scale >= 1 && scale <= 10) { Log.d("ImageViewActivity", "ACTION_MOVE Scale:" + scale); Matrix matrix = imageView.getImageMatrix(); matrix.postScale(scale, scale, mScalePoint.x-imageView.getLeft(), mScalePoint.y-imageView.getTop()); imageView.setImageMatrix(matrix); } } } break; } return false; }
public boolean onTouch(View v, MotionEvent event) { Log.d("ImageViewActivity", "EventAction: " + event.getAction()); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: mTouchStartY = event.getY(); mTouchStartX = event.getX(); mTouchMode = TouchMode.Drag; break; case MotionEvent.ACTION_POINTER_3_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: case MotionEvent.ACTION_POINTER_DOWN: /*mOldDist = getSpacing(event); if(mOldDist > 10f) { mTouchMode = TouchMode.Zoom; setScalePoint(event); }*/ break; case MotionEvent.ACTION_POINTER_3_UP: case MotionEvent.ACTION_POINTER_2_UP: case MotionEvent.ACTION_POINTER_UP: mTouchMode = TouchMode.None; break; case MotionEvent.ACTION_UP: if(mTouchMode == TouchMode.Drag) { if(Math.abs(event.getX()-mTouchStartX) < 50) { float diffY = event.getY()-mTouchStartY; if(Math.abs(diffY)>minDragHeight) { if(diffY > 0 && mGalleryThumbnails.getVisibility() == View.VISIBLE) { mGalleryThumbnails.setVisibility(View.GONE); } else if(diffY < 0 && mGalleryThumbnails.getVisibility() == View.GONE) { mGalleryThumbnails.setVisibility(View.VISIBLE); } } } } break; case MotionEvent.ACTION_MOVE: if(mTouchMode == TouchMode.Zoom) { float dist = getSpacing(event); if(dist > 10f) { GalleryImageView imageView = (GalleryImageView) mGalleryFullscreen.getSelectedView(); float scale = dist/mOldDist; if(scale >= 1 && scale <= 10) { Log.d("ImageViewActivity", "ACTION_MOVE Scale:" + scale); Matrix matrix = imageView.getImageMatrix(); matrix.postScale(scale, scale, mScalePoint.x-imageView.getLeft(), mScalePoint.y-imageView.getTop()); imageView.setImageMatrix(matrix); } } } break; } return false; }
diff --git a/PullPit/src/kea/kme/pullpit/server/services/Import.java b/PullPit/src/kea/kme/pullpit/server/services/Import.java index 0563875..4cfd6eb 100644 --- a/PullPit/src/kea/kme/pullpit/server/services/Import.java +++ b/PullPit/src/kea/kme/pullpit/server/services/Import.java @@ -1,84 +1,88 @@ package kea.kme.pullpit.server.services; import java.io.IOException; import java.sql.SQLException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import kea.kme.pullpit.server.persistence.LogHandler; import kea.kme.pullpit.server.persistence.PodioObjectHandler; import kea.kme.pullpit.server.podio.PodioImporter; public class Import extends HttpServlet { private static final long serialVersionUID = 4434374770986473879L; boolean[] done; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { - try { String isCron = req.getParameter("cron"); - if (isCron.equals("true")) - PodioObjectHandler.truncateAllPodioTables(); - } catch (Exception e) {} - res.getWriter().write("HTTP/1.0 200 OK"); - res.getWriter().close(); + if (isCron!=null) { + try { + PodioObjectHandler.truncateAllPodioTables(); + } catch (SQLException e) { + e.printStackTrace(System.err); + } + } else { + res.getWriter().write("HTTP/1.0 200 OK"); + res.getWriter().close(); + } createLog(); try { pullShows(); pullBands(); pullVenues(); writeStaticObjects(); } catch (Exception e) { e.printStackTrace(System.err); } } public void pullShows() throws Exception { PodioImporter importer = PodioImporter.getInstance(); updateLog("imp1", -1); updateLog("imp1", importer.pullShows()); } public void pullBands() throws Exception { PodioImporter importer = PodioImporter.getInstance(); updateLog("imp2", -1); updateLog("imp2", importer.pullBands()); } public void pullVenues() throws Exception { PodioImporter importer = PodioImporter.getInstance(); updateLog("imp3", -1); updateLog("imp3", importer.pullVenues()); } public void writeStaticObjects() throws Exception { PodioImporter importer = PodioImporter.getInstance(); updateLog("imp4", -1); updateLog("imp5", -1); updateLog("imp6", -1); updateLog("imp7", -1); int[] results = importer.writeStaticObjects(); for (int i = 0; i < results.length; i++) updateLog("imp" + (i + 4), results[i]); updateLog("status", 0); } private void updateLog(String key, int value) { try { LogHandler.updateImportLog(key, value); } catch (SQLException e) { e.printStackTrace(System.err); } } private void createLog() { try { LogHandler.createImportLog(); } catch (SQLException e) { e.printStackTrace(System.err); } } }
false
true
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { try { String isCron = req.getParameter("cron"); if (isCron.equals("true")) PodioObjectHandler.truncateAllPodioTables(); } catch (Exception e) {} res.getWriter().write("HTTP/1.0 200 OK"); res.getWriter().close(); createLog(); try { pullShows(); pullBands(); pullVenues(); writeStaticObjects(); } catch (Exception e) { e.printStackTrace(System.err); } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { String isCron = req.getParameter("cron"); if (isCron!=null) { try { PodioObjectHandler.truncateAllPodioTables(); } catch (SQLException e) { e.printStackTrace(System.err); } } else { res.getWriter().write("HTTP/1.0 200 OK"); res.getWriter().close(); } createLog(); try { pullShows(); pullBands(); pullVenues(); writeStaticObjects(); } catch (Exception e) { e.printStackTrace(System.err); } }
diff --git a/izpack-src/branches/4.3/src/lib/com/izforge/izpack/installer/Installer.java b/izpack-src/branches/4.3/src/lib/com/izforge/izpack/installer/Installer.java index b2bc87bf..7cb324ce 100644 --- a/izpack-src/branches/4.3/src/lib/com/izforge/izpack/installer/Installer.java +++ b/izpack-src/branches/4.3/src/lib/com/izforge/izpack/installer/Installer.java @@ -1,125 +1,128 @@ /* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2003 Jonathan Halliday * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.installer; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.NoSuchElementException; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.StringTool; /** * The program entry point. Selects between GUI and text install modes. * * @author Jonathan Halliday */ public class Installer { public static final int INSTALLER_GUI = 0, INSTALLER_AUTO = 1, INSTALLER_CONSOLE = 2; public static final int CONSOLE_INSTALL = 0, CONSOLE_GEN_TEMPLATE = 1, CONSOLE_FROM_TEMPLATE = 2; /* * The main method (program entry point). * * @param args The arguments passed on the command-line. */ public static void main(String[] args) { Debug.log(" - Logger initialized at '" + new Date(System.currentTimeMillis()) + "'."); Debug.log(" - commandline args: " + StringTool.stringArrayToSpaceSeparatedString(args)); // OS X tweakings if (System.getProperty("mrj.version") != null) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "IzPack"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); System.setProperty("com.apple.mrj.application.live-resize", "true"); } try { Iterator<String> args_it = Arrays.asList(args).iterator(); int type = INSTALLER_GUI; int consoleAction = CONSOLE_INSTALL; String path = null, langcode = null; while (args_it.hasNext()) { String arg = args_it.next().trim(); try { if ("-console".equalsIgnoreCase(arg)) { type = INSTALLER_CONSOLE; } else if ("-options-template".equalsIgnoreCase(arg)) { + type = INSTALLER_CONSOLE; consoleAction = CONSOLE_GEN_TEMPLATE; path = args_it.next().trim(); } else if ("-options".equalsIgnoreCase(arg)) { + type = INSTALLER_CONSOLE; consoleAction = CONSOLE_FROM_TEMPLATE; path = args_it.next().trim(); } else if ("-language".equalsIgnoreCase(arg)) { + type = INSTALLER_CONSOLE; langcode = args_it.next().trim(); } else { type = INSTALLER_AUTO; path = arg; } } catch (NoSuchElementException e) { System.err.println("- ERROR -"); System.err.println("Option \"" + arg + "\" requires an argument!"); System.exit(1); } } switch (type) { case INSTALLER_GUI: Class.forName("com.izforge.izpack.installer.GUIInstaller").newInstance(); break; case INSTALLER_AUTO: AutomatedInstaller ai = new AutomatedInstaller(path); ai.doInstall(); break; case INSTALLER_CONSOLE: ConsoleInstaller consoleInstaller = new ConsoleInstaller(langcode); consoleInstaller.run(consoleAction, path); break; } } catch (Exception e) { System.err.println("- ERROR -"); System.err.println(e.toString()); e.printStackTrace(); System.exit(1); } } }
false
true
public static void main(String[] args) { Debug.log(" - Logger initialized at '" + new Date(System.currentTimeMillis()) + "'."); Debug.log(" - commandline args: " + StringTool.stringArrayToSpaceSeparatedString(args)); // OS X tweakings if (System.getProperty("mrj.version") != null) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "IzPack"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); System.setProperty("com.apple.mrj.application.live-resize", "true"); } try { Iterator<String> args_it = Arrays.asList(args).iterator(); int type = INSTALLER_GUI; int consoleAction = CONSOLE_INSTALL; String path = null, langcode = null; while (args_it.hasNext()) { String arg = args_it.next().trim(); try { if ("-console".equalsIgnoreCase(arg)) { type = INSTALLER_CONSOLE; } else if ("-options-template".equalsIgnoreCase(arg)) { consoleAction = CONSOLE_GEN_TEMPLATE; path = args_it.next().trim(); } else if ("-options".equalsIgnoreCase(arg)) { consoleAction = CONSOLE_FROM_TEMPLATE; path = args_it.next().trim(); } else if ("-language".equalsIgnoreCase(arg)) { langcode = args_it.next().trim(); } else { type = INSTALLER_AUTO; path = arg; } } catch (NoSuchElementException e) { System.err.println("- ERROR -"); System.err.println("Option \"" + arg + "\" requires an argument!"); System.exit(1); } } switch (type) { case INSTALLER_GUI: Class.forName("com.izforge.izpack.installer.GUIInstaller").newInstance(); break; case INSTALLER_AUTO: AutomatedInstaller ai = new AutomatedInstaller(path); ai.doInstall(); break; case INSTALLER_CONSOLE: ConsoleInstaller consoleInstaller = new ConsoleInstaller(langcode); consoleInstaller.run(consoleAction, path); break; } } catch (Exception e) { System.err.println("- ERROR -"); System.err.println(e.toString()); e.printStackTrace(); System.exit(1); } }
public static void main(String[] args) { Debug.log(" - Logger initialized at '" + new Date(System.currentTimeMillis()) + "'."); Debug.log(" - commandline args: " + StringTool.stringArrayToSpaceSeparatedString(args)); // OS X tweakings if (System.getProperty("mrj.version") != null) { System.setProperty("com.apple.mrj.application.apple.menu.about.name", "IzPack"); System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); System.setProperty("com.apple.mrj.application.live-resize", "true"); } try { Iterator<String> args_it = Arrays.asList(args).iterator(); int type = INSTALLER_GUI; int consoleAction = CONSOLE_INSTALL; String path = null, langcode = null; while (args_it.hasNext()) { String arg = args_it.next().trim(); try { if ("-console".equalsIgnoreCase(arg)) { type = INSTALLER_CONSOLE; } else if ("-options-template".equalsIgnoreCase(arg)) { type = INSTALLER_CONSOLE; consoleAction = CONSOLE_GEN_TEMPLATE; path = args_it.next().trim(); } else if ("-options".equalsIgnoreCase(arg)) { type = INSTALLER_CONSOLE; consoleAction = CONSOLE_FROM_TEMPLATE; path = args_it.next().trim(); } else if ("-language".equalsIgnoreCase(arg)) { type = INSTALLER_CONSOLE; langcode = args_it.next().trim(); } else { type = INSTALLER_AUTO; path = arg; } } catch (NoSuchElementException e) { System.err.println("- ERROR -"); System.err.println("Option \"" + arg + "\" requires an argument!"); System.exit(1); } } switch (type) { case INSTALLER_GUI: Class.forName("com.izforge.izpack.installer.GUIInstaller").newInstance(); break; case INSTALLER_AUTO: AutomatedInstaller ai = new AutomatedInstaller(path); ai.doInstall(); break; case INSTALLER_CONSOLE: ConsoleInstaller consoleInstaller = new ConsoleInstaller(langcode); consoleInstaller.run(consoleAction, path); break; } } catch (Exception e) { System.err.println("- ERROR -"); System.err.println(e.toString()); e.printStackTrace(); System.exit(1); } }
diff --git a/core/src/main/java/hudson/util/CopyOnWriteList.java b/core/src/main/java/hudson/util/CopyOnWriteList.java index c209ce8f8..9f1628252 100644 --- a/core/src/main/java/hudson/util/CopyOnWriteList.java +++ b/core/src/main/java/hudson/util/CopyOnWriteList.java @@ -1,201 +1,203 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a 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, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 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 hudson.util; import com.thoughtworks.xstream.mapper.CannotResolveClassException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import static java.util.logging.Level.WARNING; /** * {@link List}-like implementation that has copy-on-write semantics. * * <p> * This class is suitable where highly concurrent access is needed, yet * the write operation is relatively uncommon. * * @author Kohsuke Kawaguchi */ public class CopyOnWriteList<E> implements Iterable<E> { private volatile List<? extends E> core; public CopyOnWriteList(List<E> core) { this(core,false); } private CopyOnWriteList(List<E> core, boolean noCopy) { this.core = noCopy ? core : new ArrayList<E>(core); } public CopyOnWriteList() { this.core = Collections.emptyList(); } public synchronized void add(E e) { List<E> n = new ArrayList<E>(core); n.add(e); core = n; } public synchronized void addAll(Collection<? extends E> items) { List<E> n = new ArrayList<E>(core); n.addAll(items); core = n; } /** * Removes an item from the list. * * @return * true if the list contained the item. False if it didn't, * in which case there's no change. */ public synchronized boolean remove(E e) { List<E> n = new ArrayList<E>(core); boolean r = n.remove(e); core = n; return r; } /** * Returns an iterator. */ public Iterator<E> iterator() { final Iterator<? extends E> itr = core.iterator(); return new Iterator<E>() { private E last; public boolean hasNext() { return itr.hasNext(); } public E next() { return last=itr.next(); } public void remove() { CopyOnWriteList.this.remove(last); } }; } /** * Completely replaces this list by the contents of the given list. */ public void replaceBy(CopyOnWriteList<? extends E> that) { this.core = that.core; } /** * Completely replaces this list by the contents of the given list. */ public void replaceBy(Collection<? extends E> that) { this.core = new ArrayList<E>(that); } /** * Completely replaces this list by the contents of the given list. */ public void replaceBy(E... that) { replaceBy(Arrays.asList(that)); } public void clear() { this.core = new ArrayList<E>(); } public E[] toArray(E[] array) { return core.toArray(array); } public List<E> getView() { return Collections.unmodifiableList(core); } public void addAllTo(Collection<? super E> dst) { dst.addAll(core); } public boolean isEmpty() { return core.isEmpty(); } public int size() { return core.size(); } /** * {@link Converter} implementation for XStream. */ public static final class ConverterImpl extends AbstractCollectionConverter { public ConverterImpl(Mapper mapper) { super(mapper); } public boolean canConvert(Class type) { return type==CopyOnWriteList.class; } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { for (Object o : (CopyOnWriteList) source) writeItem(o, context, writer); } @SuppressWarnings("unchecked") public CopyOnWriteList unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { // read the items from xml into a list List items = new ArrayList(); while (reader.hasMoreChildren()) { reader.moveDown(); try { Object item = readItem(reader, context, items); items.add(item); } catch (CannotResolveClassException e) { LOGGER.log(WARNING,"Failed to resolve class",e); + RobustReflectionConverter.addErrorInContext(context, e); } catch (LinkageError e) { LOGGER.log(WARNING,"Failed to resolve class",e); + RobustReflectionConverter.addErrorInContext(context, e); } reader.moveUp(); } return new CopyOnWriteList(items,true); } } private static final Logger LOGGER = Logger.getLogger(CopyOnWriteList.class.getName()); }
false
true
public CopyOnWriteList unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { // read the items from xml into a list List items = new ArrayList(); while (reader.hasMoreChildren()) { reader.moveDown(); try { Object item = readItem(reader, context, items); items.add(item); } catch (CannotResolveClassException e) { LOGGER.log(WARNING,"Failed to resolve class",e); } catch (LinkageError e) { LOGGER.log(WARNING,"Failed to resolve class",e); } reader.moveUp(); } return new CopyOnWriteList(items,true); }
public CopyOnWriteList unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { // read the items from xml into a list List items = new ArrayList(); while (reader.hasMoreChildren()) { reader.moveDown(); try { Object item = readItem(reader, context, items); items.add(item); } catch (CannotResolveClassException e) { LOGGER.log(WARNING,"Failed to resolve class",e); RobustReflectionConverter.addErrorInContext(context, e); } catch (LinkageError e) { LOGGER.log(WARNING,"Failed to resolve class",e); RobustReflectionConverter.addErrorInContext(context, e); } reader.moveUp(); } return new CopyOnWriteList(items,true); }
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java index b20a69b2..bdf0ae1d 100644 --- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java +++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/DefaultEditorAdaptor.java @@ -1,535 +1,539 @@ package net.sourceforge.vrapper.vim; import static java.lang.String.format; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import net.sourceforge.vrapper.keymap.KeyMap; import net.sourceforge.vrapper.keymap.KeyStroke; import net.sourceforge.vrapper.keymap.SpecialKey; import net.sourceforge.vrapper.keymap.vim.SimpleKeyStroke; import net.sourceforge.vrapper.log.VrapperLog; import net.sourceforge.vrapper.platform.Configuration.Option; import net.sourceforge.vrapper.platform.CursorService; import net.sourceforge.vrapper.platform.FileService; import net.sourceforge.vrapper.platform.HistoryService; import net.sourceforge.vrapper.platform.KeyMapProvider; import net.sourceforge.vrapper.platform.Platform; import net.sourceforge.vrapper.platform.PlatformSpecificModeProvider; import net.sourceforge.vrapper.platform.PlatformSpecificStateProvider; import net.sourceforge.vrapper.platform.SearchAndReplaceService; import net.sourceforge.vrapper.platform.SelectionService; import net.sourceforge.vrapper.platform.ServiceProvider; import net.sourceforge.vrapper.platform.TextContent; import net.sourceforge.vrapper.platform.UnderlyingEditorSettings; import net.sourceforge.vrapper.platform.UserInterfaceService; import net.sourceforge.vrapper.platform.ViewportService; import net.sourceforge.vrapper.utils.LineInformation; import net.sourceforge.vrapper.utils.Position; import net.sourceforge.vrapper.utils.PositionlessSelection; import net.sourceforge.vrapper.vim.commands.CommandExecutionException; import net.sourceforge.vrapper.vim.commands.Selection; import net.sourceforge.vrapper.vim.commands.TextObject; import net.sourceforge.vrapper.vim.modes.BlockwiseVisualMode; import net.sourceforge.vrapper.vim.modes.EditorMode; import net.sourceforge.vrapper.vim.modes.InsertMode; import net.sourceforge.vrapper.vim.modes.LinewiseVisualMode; import net.sourceforge.vrapper.vim.modes.ModeSwitchHint; import net.sourceforge.vrapper.vim.modes.NormalMode; import net.sourceforge.vrapper.vim.modes.ReplaceMode; import net.sourceforge.vrapper.vim.modes.VisualMode; import net.sourceforge.vrapper.vim.modes.commandline.CommandLineMode; import net.sourceforge.vrapper.vim.modes.commandline.CommandLineParser; import net.sourceforge.vrapper.vim.modes.commandline.PasteRegisterMode; import net.sourceforge.vrapper.vim.modes.commandline.SearchMode; import net.sourceforge.vrapper.vim.register.DefaultRegisterManager; import net.sourceforge.vrapper.vim.register.Register; import net.sourceforge.vrapper.vim.register.RegisterManager; public class DefaultEditorAdaptor implements EditorAdaptor, ModeChangeHintReceiver { // ugly global option, so unit tests can disable it // in order to be .vrapperrc-agnostic public static boolean SHOULD_READ_RC_FILE = true; private static final String CONFIG_FILE_NAME = ".vrapperrc"; private static final String WINDOWS_CONFIG_FILE_NAME = "_vrapperrc"; private EditorMode currentMode; private final Map<String, EditorMode> modeMap = new HashMap<String, EditorMode>(); private final TextContent modelContent; private final TextContent viewContent; private final CursorService cursorService; private final SelectionService selectionService; private final FileService fileService; private RegisterManager registerManager; private final RegisterManager globalRegisterManager; private final ViewportService viewportService; private final HistoryService historyService; private final UserInterfaceService userInterfaceService; private final ServiceProvider serviceProvider; private final KeyStrokeTranslator keyStrokeTranslator; private final KeyMapProvider keyMapProvider; private final UnderlyingEditorSettings editorSettings; private final LocalConfiguration configuration; private final PlatformSpecificStateProvider platformSpecificStateProvider; private final PlatformSpecificModeProvider platformSpecificModeProvider; private final SearchAndReplaceService searchAndReplaceService; private MacroRecorder macroRecorder; private MacroPlayer macroPlayer; public DefaultEditorAdaptor(final Platform editor, final RegisterManager registerManager, final boolean isActive) { this.modelContent = editor.getModelContent(); this.viewContent = editor.getViewContent(); this.cursorService = editor.getCursorService(); this.selectionService = editor.getSelectionService(); this.historyService = editor.getHistoryService(); this.registerManager = registerManager; this.globalRegisterManager = registerManager; this.serviceProvider = editor.getServiceProvider(); this.editorSettings = editor.getUnderlyingEditorSettings(); this.configuration = new SimpleLocalConfiguration(editor.getConfiguration()); final LocalConfigurationListener listener = new LocalConfigurationListener() { @Override public <T> void optionChanged(final Option<T> option, final T oldValue, final T newValue) { if("clipboard".equals(option.getId())) { if("unnamed".equals(newValue)) { final Register clipboardRegister = DefaultEditorAdaptor.this.getRegisterManager().getRegister(RegisterManager.REGISTER_NAME_CLIPBOARD); DefaultEditorAdaptor.this.getRegisterManager().setDefaultRegister(clipboardRegister); } else { final Register unnamedRegister = DefaultEditorAdaptor.this.getRegisterManager().getRegister(RegisterManager.REGISTER_NAME_UNNAMED); DefaultEditorAdaptor.this.getRegisterManager().setDefaultRegister(unnamedRegister); } } } }; this.configuration.addListener(listener); this.platformSpecificStateProvider = editor.getPlatformSpecificStateProvider(); this.platformSpecificModeProvider = editor.getPlatformSpecificModeProvider(); this.searchAndReplaceService = editor.getSearchAndReplaceService(); viewportService = editor.getViewportService(); userInterfaceService = editor.getUserInterfaceService(); keyMapProvider = editor.getKeyMapProvider(); keyStrokeTranslator = new KeyStrokeTranslator(); macroRecorder = new MacroRecorder(registerManager, userInterfaceService); macroPlayer = null; fileService = editor.getFileService(); __set_modes(this); readConfiguration(); setNewLineFromFirstLine(); if (isActive) { changeModeSafely(NormalMode.NAME); } } // this is public just for test purposes (Mockito spy as self) public void __set_modes(final DefaultEditorAdaptor self) { modeMap.clear(); final EditorMode[] modes = { new NormalMode(self), new VisualMode(self), new LinewiseVisualMode(self), new BlockwiseVisualMode(self), new InsertMode(self), new ReplaceMode(self), new CommandLineMode(self), new SearchMode(self), new PasteRegisterMode(self)}; for (final EditorMode mode: modes) { modeMap.put(mode.getName(), mode); } } @Override public void changeModeSafely(final String name, final ModeSwitchHint... hints) { try { changeMode(name, hints); } catch (final CommandExecutionException e) { VrapperLog.error("exception when changing mode", e); userInterfaceService.setErrorMessage(e.getMessage()); } } private void setNewLineFromFirstLine() { if (modelContent.getNumberOfLines() > 1) { final LineInformation first = modelContent.getLineInformation(0); final LineInformation second = modelContent.getLineInformation(1); final int start = first.getEndOffset(); final int end = second.getBeginOffset(); final String newLine = modelContent.getText(start, end-start); configuration.setNewLine(newLine); } } private void readConfiguration() { if (!SHOULD_READ_RC_FILE) { return; } String filename = CONFIG_FILE_NAME; final File homeDir = new File(System.getProperty("user.home")); File config = new File(homeDir, filename); if( ! config.exists()) { //if no .vrapperrc, look for _vrapperrc filename = WINDOWS_CONFIG_FILE_NAME; config = new File(homeDir, filename); } if(config.exists()) { sourceConfigurationFile(filename); } } @Override public boolean sourceConfigurationFile(final String filename) { final File homeDir = new File(System.getProperty("user.home")); final File config = new File(homeDir, filename); if(config.exists()) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(config)); String line; final CommandLineParser parser = new CommandLineParser(this); String trimmed; while((line = reader.readLine()) != null) { //*** skip over everything in a .vimrc file that we don't support ***// trimmed = line.trim().toLowerCase(); //ignore comments and key mappings we don't support if(trimmed.equals("") || trimmed.startsWith("\"") || trimmed.startsWith("let") || trimmed.contains("<leader>") || trimmed.contains("<silent>")) { continue; } if(trimmed.startsWith("if")) { //skip all conditional statements while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endif")) { break; } } continue; //skip "endif" line } if(trimmed.startsWith("func")) { //skip all function declarations while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endfunc")) { break; } } continue; //skip "endfunction" line } if(trimmed.startsWith("try")) { //skip all try declarations while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endtry")) { break; } } continue; //skip "endtry" line } + if(trimmed.startsWith(":")) { + //leading ':' is optional, skip it if it exists + line = line.substring(line.indexOf(':') +1); + } //attempt to parse this line parser.parseAndExecute(null, line.trim()); } } catch (final FileNotFoundException e) { // ignore } catch (final IOException e) { e.printStackTrace(); } finally { if(reader != null) { try { reader.close(); } catch (final IOException e) { e.printStackTrace(); } } } return true; } else { return false; } } @Override public void changeMode(final String modeName, final ModeSwitchHint... args) throws CommandExecutionException { EditorMode newMode = modeMap.get(modeName); if (newMode == null) { // Load extension modes final List<EditorMode> modes = platformSpecificModeProvider.getModes(this); for (final EditorMode mode : modes) { if (modeMap.containsKey(mode.getName())) { VrapperLog.error(format("Mode '%s' was already loaded!", mode.getName())); } else { modeMap.put(mode.getName(), mode); } } newMode = modeMap.get(modeName); if (newMode == null) { VrapperLog.error(format("There is no mode named '%s'", modeName)); return; } } if (currentMode != newMode) { final EditorMode oldMode = currentMode; if (currentMode != null) { currentMode.leaveMode(args); } try { currentMode = newMode; newMode.enterMode(args); userInterfaceService.setEditorMode(newMode.getDisplayName()); } catch(final CommandExecutionException e) { //failed to enter new mode, revert to previous mode //then let Exception bubble up currentMode = oldMode; oldMode.enterMode(); throw e; } } } @Override public boolean handleKey(final KeyStroke key) { macroRecorder.handleKey(key); return handleKeyOffRecord(key); } @Override public boolean handleKeyOffRecord(final KeyStroke key) { final boolean result = handleKey0(key); if (macroPlayer != null) { // while playing back one macro, another macro might be called // recursively. we need a fresh macro player for that. final MacroPlayer player = macroPlayer; macroPlayer = null; player.play(); } return result; } @Override public TextContent getModelContent() { return modelContent; } @Override public TextContent getViewContent() { return viewContent; } @Override public Position getPosition() { return cursorService.getPosition(); } @Override public void setPosition(final Position destination, final boolean updateStickyColumn) { cursorService.setPosition(destination, updateStickyColumn); } @Override public Selection getSelection() { return selectionService.getSelection(); } @Override public void setSelection(final Selection selection) { selectionService.setSelection(selection); } @Override public CursorService getCursorService() { return cursorService; } @Override public FileService getFileService() { return fileService; } @Override public ViewportService getViewportService() { return viewportService; } @Override public UserInterfaceService getUserInterfaceService() { return userInterfaceService; } @Override public RegisterManager getRegisterManager() { return registerManager; } @Override public HistoryService getHistory() { return historyService; } @Override public <T> T getService(final Class<T> serviceClass) { return serviceProvider.getService(serviceClass); } @Override public EditorMode getMode(final String name) { return modeMap.get(name); } @Override public KeyMapProvider getKeyMapProvider() { return keyMapProvider; } @Override public UnderlyingEditorSettings getEditorSettings() { return editorSettings; } @Override public PlatformSpecificStateProvider getPlatformSpecificStateProvider() { return platformSpecificStateProvider; } @Override public SearchAndReplaceService getSearchAndReplaceService() { return searchAndReplaceService; } @Override public void useGlobalRegisters() { registerManager = globalRegisterManager; swapMacroRecorder(); } @Override public void useLocalRegisters() { registerManager = new DefaultRegisterManager(); swapMacroRecorder(); } @Override public LocalConfiguration getConfiguration() { return configuration; } @Override public MacroRecorder getMacroRecorder() { return macroRecorder; } @Override public MacroPlayer getMacroPlayer() { if (macroPlayer == null) { macroPlayer = new MacroPlayer(this); } return macroPlayer; } private void swapMacroRecorder() { if (macroRecorder.isRecording()) { macroRecorder.stopRecording(); } macroRecorder = new MacroRecorder(registerManager, userInterfaceService); } /** * Note from Kevin: This method is a major source of frustration for me. * It has to handle the following scenarios but I can't unit test them: * - multi-character mapping completed in InsertMode and NormalMode * - multi-character mapping *not* completed in InsertMode and NormalMode * - "nmap zx gg" and type 'zt' * - "imap jj <ESC>" and type 'jk' * - display pending character in InsertMode * - and delete pending character when mapping completed * - don't move cursor when not completing a multi-character mapping while inside parentheses * - "for(int j=0)" when 'j' is part of a mapping ("imap jj <ESC>") * - (Eclipse moves the cursor on me in its "Smart Insert" mode with auto-closing parentheses) * - single-character mapping in InsertMode (perform mapping but don't display pending character) */ private boolean handleKey0(final KeyStroke key) { if (currentMode != null) { final KeyMap map = currentMode.resolveKeyMap(keyMapProvider); if (map != null) { final boolean inMapping = keyStrokeTranslator.processKeyStroke(map, key); if (inMapping) { final Queue<RemappedKeyStroke> resultingKeyStrokes = keyStrokeTranslator.resultingKeyStrokes(); //if we're in a mapping in InsertMode, display the pending characters //(we'll delete them if the user completes the mapping) if(currentMode.getName() == InsertMode.NAME) { //display pending character if(resultingKeyStrokes.isEmpty()) { return currentMode.handleKey(key); } //there are resulting key strokes, //mapping exited either successfully or unsuccessfully else if(keyStrokeTranslator.numUnconsumedKeys() > 0) { if(keyStrokeTranslator.didMappingSucceed()) { //delete all the pending characters we had displayed for(int i=0; i < keyStrokeTranslator.numUnconsumedKeys(); i++) { currentMode.handleKey(new RemappedKeyStroke(new SimpleKeyStroke(SpecialKey.BACKSPACE), false)); } } else { //we've already displayed all but this most recent key return currentMode.handleKey(key); } } //else, mapping is only one character long (no pending characters to remove) } //play all resulting key strokes while (!resultingKeyStrokes.isEmpty()) { final RemappedKeyStroke next = resultingKeyStrokes.poll(); if (next.isRecursive()) { handleKey(next); } else { currentMode.handleKey(next); } } return true; } } return currentMode.handleKey(key); } return false; } @Override public void onChangeEnabled(final boolean enabled) { if (enabled) { // switch mode for set-up/tear-down changeModeSafely(NormalMode.NAME, InsertMode.DONT_MOVE_CURSOR); } else { changeModeSafely(InsertMode.NAME, InsertMode.DONT_MOVE_CURSOR, InsertMode.DONT_LOCK_HISTORY); userInterfaceService.setEditorMode(UserInterfaceService.VRAPPER_DISABLED); } } @Override public void rememberLastActiveSelection() { registerManager.setLastActiveSelection(PositionlessSelection.getInstance(this)); } @Override public TextObject getLastActiveSelection() { return registerManager.getLastActiveSelection(); } @Override public String getCurrentModeName() { return currentMode != null ? currentMode.getName() : null; } }
true
true
public boolean sourceConfigurationFile(final String filename) { final File homeDir = new File(System.getProperty("user.home")); final File config = new File(homeDir, filename); if(config.exists()) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(config)); String line; final CommandLineParser parser = new CommandLineParser(this); String trimmed; while((line = reader.readLine()) != null) { //*** skip over everything in a .vimrc file that we don't support ***// trimmed = line.trim().toLowerCase(); //ignore comments and key mappings we don't support if(trimmed.equals("") || trimmed.startsWith("\"") || trimmed.startsWith("let") || trimmed.contains("<leader>") || trimmed.contains("<silent>")) { continue; } if(trimmed.startsWith("if")) { //skip all conditional statements while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endif")) { break; } } continue; //skip "endif" line } if(trimmed.startsWith("func")) { //skip all function declarations while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endfunc")) { break; } } continue; //skip "endfunction" line } if(trimmed.startsWith("try")) { //skip all try declarations while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endtry")) { break; } } continue; //skip "endtry" line } //attempt to parse this line parser.parseAndExecute(null, line.trim()); } } catch (final FileNotFoundException e) { // ignore } catch (final IOException e) { e.printStackTrace(); } finally { if(reader != null) { try { reader.close(); } catch (final IOException e) { e.printStackTrace(); } } } return true; } else { return false; } }
public boolean sourceConfigurationFile(final String filename) { final File homeDir = new File(System.getProperty("user.home")); final File config = new File(homeDir, filename); if(config.exists()) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(config)); String line; final CommandLineParser parser = new CommandLineParser(this); String trimmed; while((line = reader.readLine()) != null) { //*** skip over everything in a .vimrc file that we don't support ***// trimmed = line.trim().toLowerCase(); //ignore comments and key mappings we don't support if(trimmed.equals("") || trimmed.startsWith("\"") || trimmed.startsWith("let") || trimmed.contains("<leader>") || trimmed.contains("<silent>")) { continue; } if(trimmed.startsWith("if")) { //skip all conditional statements while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endif")) { break; } } continue; //skip "endif" line } if(trimmed.startsWith("func")) { //skip all function declarations while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endfunc")) { break; } } continue; //skip "endfunction" line } if(trimmed.startsWith("try")) { //skip all try declarations while((line = reader.readLine()) != null) { if(line.trim().toLowerCase().startsWith("endtry")) { break; } } continue; //skip "endtry" line } if(trimmed.startsWith(":")) { //leading ':' is optional, skip it if it exists line = line.substring(line.indexOf(':') +1); } //attempt to parse this line parser.parseAndExecute(null, line.trim()); } } catch (final FileNotFoundException e) { // ignore } catch (final IOException e) { e.printStackTrace(); } finally { if(reader != null) { try { reader.close(); } catch (final IOException e) { e.printStackTrace(); } } } return true; } else { return false; } }
diff --git a/src/java/org/xhtmlrenderer/pdf/DocumentSplitter.java b/src/java/org/xhtmlrenderer/pdf/DocumentSplitter.java index c6af0d1e..814d84b3 100644 --- a/src/java/org/xhtmlrenderer/pdf/DocumentSplitter.java +++ b/src/java/org/xhtmlrenderer/pdf/DocumentSplitter.java @@ -1,300 +1,300 @@ /* * {{{ header & license * Copyright (c) 2007 Wisconsin Court System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * }}} */ package org.xhtmlrenderer.pdf; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class DocumentSplitter implements ContentHandler { private static final String HEAD_ELEMENT_NAME = "head"; private List _processingInstructions = new LinkedList(); private SAXEventRecorder _head = new SAXEventRecorder(); private boolean _inHead = false; private int _depth = 0; private boolean _needNewNSScope = false; private NamespaceScope _currentNSScope = new NamespaceScope(); private boolean _needNSScopePop; private Locator _locator; private TransformerHandler _handler; private boolean _inDocument = false; private List _documents = new LinkedList(); private boolean _replayedHead = false; public void characters(char[] ch, int start, int length) throws SAXException { if (_inHead) { _head.characters(ch, start, length); } else if (_inDocument) { _handler.characters(ch, start, length); } } public void endDocument() throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { if (_inHead) { _head.endPrefixMapping(prefix); } else if (_inDocument) { _handler.endPrefixMapping(prefix); } else { _needNSScopePop = true; } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (_inHead) { _head.ignorableWhitespace(ch, start, length); } else if (_inDocument) { _handler.ignorableWhitespace(ch, start, length); } } public void processingInstruction(String target, String data) throws SAXException { _processingInstructions.add(new ProcessingInstruction(target, data)); } public void setDocumentLocator(Locator locator) { _locator = locator; } public void skippedEntity(String name) throws SAXException { if (_inHead) { _head.skippedEntity(name); } else if (_inDocument) { _handler.skippedEntity(name); } } public void startDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (_inHead) { _head.startElement(uri, localName, qName, atts); } else if (_inDocument) { if (_depth == 2 && ! _replayedHead) { - if (qName.equals(HEAD_ELEMENT_NAME)) { + if (HEAD_ELEMENT_NAME.equalsIgnoreCase(qName)) { _handler.startElement(uri, localName, qName, atts); _head.replay(_handler); } else { _handler.startElement("", HEAD_ELEMENT_NAME, HEAD_ELEMENT_NAME, new AttributesImpl()); _head.replay(_handler); _handler.endElement("", HEAD_ELEMENT_NAME, HEAD_ELEMENT_NAME); _handler.startElement(uri, localName, qName, atts); } _replayedHead = true; } else { _handler.startElement(uri, localName, qName, atts); } } else { if (_needNewNSScope) { _needNewNSScope = false; _currentNSScope = new NamespaceScope(_currentNSScope); } if (_depth == 1) { - if (HEAD_ELEMENT_NAME.equals(qName)) { + if (HEAD_ELEMENT_NAME.equalsIgnoreCase(qName)) { _inHead = true; _currentNSScope.replay(_head, true); } else { try { _inDocument = true; _replayedHead = false; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); Document doc = factory.newDocumentBuilder().newDocument(); _documents.add(doc); _handler = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerHandler(); _handler.setResult(new DOMResult(doc)); _handler.startDocument(); _handler.setDocumentLocator(_locator); for (Iterator i = _processingInstructions.iterator(); i.hasNext(); ) { ProcessingInstruction pI = (ProcessingInstruction)i.next(); _handler.processingInstruction(pI.getTarget(), pI.getData()); } _currentNSScope.replay(_handler, true); _handler.startElement(uri, localName, qName, atts); } catch (ParserConfigurationException e) { throw new SAXException(e.getMessage(), e); } catch (TransformerConfigurationException e) { throw new SAXException(e.getMessage(), e); } } } } _depth++; } public void endElement(String uri, String localName, String qName) throws SAXException { _depth--; if (_needNSScopePop) { _needNSScopePop = false; _currentNSScope = _currentNSScope.getParent(); } if (_inHead) { if (_depth == 1) { _currentNSScope.replay(_head, false); _inHead = false; } else { _head.endElement(uri, localName, qName); } } else if (_inDocument) { if (_depth == 1) { _currentNSScope.replay(_handler, false); _handler.endElement(uri, localName, qName); _handler.endDocument(); _inDocument = false; } else { _handler.endElement(uri, localName, qName); } } } public void startPrefixMapping(String prefix, String uri) throws SAXException { if (_inHead) { _head.startPrefixMapping(prefix, uri); } else if (_inDocument) { _handler.startPrefixMapping(prefix, uri); } else { _needNewNSScope = true; _currentNSScope.addNamespace(new Namespace(prefix, uri)); } } public List getDocuments() { return _documents; } private static final class Namespace { private String _prefix; private String _uri; public Namespace(String prefix, String uri) { _prefix = prefix; _uri = uri; } public String getPrefix() { return _prefix; } public String getUri() { return _uri; } } private static final class NamespaceScope { private NamespaceScope _parent; private List _namespaces = new LinkedList(); public NamespaceScope() { } public NamespaceScope(NamespaceScope parent) { _parent = parent; } public void addNamespace(Namespace namespace) { _namespaces.add(namespace); } public void replay(ContentHandler contentHandler, boolean start) throws SAXException { replay(contentHandler, new HashSet(), start); } private void replay(ContentHandler contentHandler, Set seen, boolean start) throws SAXException { for (Iterator i = _namespaces.iterator(); i.hasNext(); ) { Namespace ns = (Namespace)i.next(); if (! seen.contains(ns.getPrefix())) { seen.add(ns.getPrefix()); if (start) { contentHandler.startPrefixMapping(ns.getPrefix(), ns.getUri()); } else { contentHandler.endPrefixMapping(ns.getPrefix()); } } } if (_parent != null) { _parent.replay(contentHandler, seen, start); } } public NamespaceScope getParent() { return _parent; } } private static class ProcessingInstruction { private String _target; private String _data; public ProcessingInstruction(String target, String data) { _target = target; _data = data; } public String getData() { return _data; } public String getTarget() { return _target; } } }
false
true
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (_inHead) { _head.startElement(uri, localName, qName, atts); } else if (_inDocument) { if (_depth == 2 && ! _replayedHead) { if (qName.equals(HEAD_ELEMENT_NAME)) { _handler.startElement(uri, localName, qName, atts); _head.replay(_handler); } else { _handler.startElement("", HEAD_ELEMENT_NAME, HEAD_ELEMENT_NAME, new AttributesImpl()); _head.replay(_handler); _handler.endElement("", HEAD_ELEMENT_NAME, HEAD_ELEMENT_NAME); _handler.startElement(uri, localName, qName, atts); } _replayedHead = true; } else { _handler.startElement(uri, localName, qName, atts); } } else { if (_needNewNSScope) { _needNewNSScope = false; _currentNSScope = new NamespaceScope(_currentNSScope); } if (_depth == 1) { if (HEAD_ELEMENT_NAME.equals(qName)) { _inHead = true; _currentNSScope.replay(_head, true); } else { try { _inDocument = true; _replayedHead = false; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); Document doc = factory.newDocumentBuilder().newDocument(); _documents.add(doc); _handler = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerHandler(); _handler.setResult(new DOMResult(doc)); _handler.startDocument(); _handler.setDocumentLocator(_locator); for (Iterator i = _processingInstructions.iterator(); i.hasNext(); ) { ProcessingInstruction pI = (ProcessingInstruction)i.next(); _handler.processingInstruction(pI.getTarget(), pI.getData()); } _currentNSScope.replay(_handler, true); _handler.startElement(uri, localName, qName, atts); } catch (ParserConfigurationException e) { throw new SAXException(e.getMessage(), e); } catch (TransformerConfigurationException e) { throw new SAXException(e.getMessage(), e); } } } } _depth++; }
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (_inHead) { _head.startElement(uri, localName, qName, atts); } else if (_inDocument) { if (_depth == 2 && ! _replayedHead) { if (HEAD_ELEMENT_NAME.equalsIgnoreCase(qName)) { _handler.startElement(uri, localName, qName, atts); _head.replay(_handler); } else { _handler.startElement("", HEAD_ELEMENT_NAME, HEAD_ELEMENT_NAME, new AttributesImpl()); _head.replay(_handler); _handler.endElement("", HEAD_ELEMENT_NAME, HEAD_ELEMENT_NAME); _handler.startElement(uri, localName, qName, atts); } _replayedHead = true; } else { _handler.startElement(uri, localName, qName, atts); } } else { if (_needNewNSScope) { _needNewNSScope = false; _currentNSScope = new NamespaceScope(_currentNSScope); } if (_depth == 1) { if (HEAD_ELEMENT_NAME.equalsIgnoreCase(qName)) { _inHead = true; _currentNSScope.replay(_head, true); } else { try { _inDocument = true; _replayedHead = false; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); Document doc = factory.newDocumentBuilder().newDocument(); _documents.add(doc); _handler = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerHandler(); _handler.setResult(new DOMResult(doc)); _handler.startDocument(); _handler.setDocumentLocator(_locator); for (Iterator i = _processingInstructions.iterator(); i.hasNext(); ) { ProcessingInstruction pI = (ProcessingInstruction)i.next(); _handler.processingInstruction(pI.getTarget(), pI.getData()); } _currentNSScope.replay(_handler, true); _handler.startElement(uri, localName, qName, atts); } catch (ParserConfigurationException e) { throw new SAXException(e.getMessage(), e); } catch (TransformerConfigurationException e) { throw new SAXException(e.getMessage(), e); } } } } _depth++; }
diff --git a/persistence-plugin/src/test/java/org/jboss/seam/forge/persistence/test/plugins/NewEntityPluginTest.java b/persistence-plugin/src/test/java/org/jboss/seam/forge/persistence/test/plugins/NewEntityPluginTest.java index 5f45dfe3..85043897 100644 --- a/persistence-plugin/src/test/java/org/jboss/seam/forge/persistence/test/plugins/NewEntityPluginTest.java +++ b/persistence-plugin/src/test/java/org/jboss/seam/forge/persistence/test/plugins/NewEntityPluginTest.java @@ -1,90 +1,91 @@ package org.jboss.seam.forge.persistence.test.plugins; /* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import javax.persistence.Entity; import org.jboss.arquillian.junit.Arquillian; import org.jboss.seam.forge.parser.java.JavaClass; import org.jboss.seam.forge.persistence.PersistenceFacet; import org.jboss.seam.forge.persistence.test.plugins.util.AbstractJPATest; import org.jboss.seam.forge.project.Project; import org.jboss.seam.forge.project.facets.JavaSourceFacet; import org.jboss.seam.forge.project.util.Packages; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> */ @RunWith(Arquillian.class) public class NewEntityPluginTest extends AbstractJPATest { @Test public void testNewEntity() throws Exception { Project project = getProject(); String entityName = "Goofy"; queueInputLines(""); getShell().execute("new-entity --named " + entityName); String pkg = project.getFacet(PersistenceFacet.class).getEntityPackage() + "." + entityName; String path = Packages.toFileSyntax(pkg) + ".java"; JavaClass javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(path).getJavaSource(); assertFalse(javaClass.hasSyntaxErrors()); javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(javaClass).getJavaSource(); assertTrue(javaClass.hasAnnotation(Entity.class)); assertFalse(javaClass.hasSyntaxErrors()); + assertTrue(javaClass.hasImport(Entity.class)); assertTrue(javaClass.hasField("id")); assertTrue(javaClass.hasField("version")); } @Test public void testNewEntityCorrectsInvalidInput() throws Exception { Project project = getProject(); JavaClass javaClass = generateEntity(project); queueInputLines("gamesWon"); getShell().execute("new-field int --fieldName int"); queueInputLines("gamesLost"); getShell().execute("new-field int --fieldName #$%#"); javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(javaClass).getJavaSource(); assertTrue(javaClass.hasAnnotation(Entity.class)); assertTrue(javaClass.hasImport(Entity.class)); assertTrue(javaClass.hasField("gamesWon")); assertTrue(javaClass.hasField("gamesLost")); assertFalse(javaClass.hasSyntaxErrors()); } }
true
true
public void testNewEntity() throws Exception { Project project = getProject(); String entityName = "Goofy"; queueInputLines(""); getShell().execute("new-entity --named " + entityName); String pkg = project.getFacet(PersistenceFacet.class).getEntityPackage() + "." + entityName; String path = Packages.toFileSyntax(pkg) + ".java"; JavaClass javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(path).getJavaSource(); assertFalse(javaClass.hasSyntaxErrors()); javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(javaClass).getJavaSource(); assertTrue(javaClass.hasAnnotation(Entity.class)); assertFalse(javaClass.hasSyntaxErrors()); assertTrue(javaClass.hasField("id")); assertTrue(javaClass.hasField("version")); }
public void testNewEntity() throws Exception { Project project = getProject(); String entityName = "Goofy"; queueInputLines(""); getShell().execute("new-entity --named " + entityName); String pkg = project.getFacet(PersistenceFacet.class).getEntityPackage() + "." + entityName; String path = Packages.toFileSyntax(pkg) + ".java"; JavaClass javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(path).getJavaSource(); assertFalse(javaClass.hasSyntaxErrors()); javaClass = (JavaClass) project.getFacet(JavaSourceFacet.class).getJavaResource(javaClass).getJavaSource(); assertTrue(javaClass.hasAnnotation(Entity.class)); assertFalse(javaClass.hasSyntaxErrors()); assertTrue(javaClass.hasImport(Entity.class)); assertTrue(javaClass.hasField("id")); assertTrue(javaClass.hasField("version")); }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/OutgoingInvitationProcess.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/OutgoingInvitationProcess.java index 267224232..0fea8e10d 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/OutgoingInvitationProcess.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/invitation/internal/OutgoingInvitationProcess.java @@ -1,362 +1,364 @@ /* * DPP - Serious Distributed Pair Programming * (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006 * (c) Riad Djemili - 2006 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package de.fu_berlin.inf.dpp.invitation.internal; import java.io.File; import java.io.InputStream; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.ui.actions.WorkspaceModifyOperation; import de.fu_berlin.inf.dpp.FileList; import de.fu_berlin.inf.dpp.Saros; import de.fu_berlin.inf.dpp.User; import de.fu_berlin.inf.dpp.invitation.IOutgoingInvitationProcess; import de.fu_berlin.inf.dpp.net.ITransmitter; import de.fu_berlin.inf.dpp.net.JID; import de.fu_berlin.inf.dpp.net.internal.DataTransferManager; import de.fu_berlin.inf.dpp.observables.InvitationProcessObservable; import de.fu_berlin.inf.dpp.project.ISharedProject; import de.fu_berlin.inf.dpp.util.FileZipper; import de.fu_berlin.inf.dpp.util.Util; import de.fu_berlin.inf.dpp.util.VersionManager; /** * An outgoing invitation process. * * TODO FIXME The whole invitation procedure needs to be completely redone, * because it can cause race conditions. In particular cancellation is not * possible at arbitrary times (something like an CANCEL_ACK is needed) * * TODO Use {@link WorkspaceModifyOperation}s to wrap the whole invitation * process, so that background activities such as autoBuilding do not interfere * with the InvitationProcess * * @author rdjemili */ public class OutgoingInvitationProcess extends InvitationProcess implements IOutgoingInvitationProcess { protected final static Logger log = Logger .getLogger(OutgoingInvitationProcess.class); /* Dependencies */ protected Saros saros; protected DataTransferManager dataTransferManager; protected ISharedProject sharedProject; /* Fields */ protected FileList remoteFileList; protected FileList localFileList; protected List<IPath> toSend; /** size of project archive file */ protected final long fileSize = 100; /** size of current transfered part of archive file. */ protected long transferedFileSize = 0; protected SubMonitor monitor; protected VersionManager versionManager; public OutgoingInvitationProcess(Saros saros, ITransmitter transmitter, DataTransferManager dataTransferManager, JID to, ISharedProject sharedProject, String description, IInvitationUI inviteUI, int colorID, FileList localFileList, SubMonitor monitor, InvitationProcessObservable invitationProcesses, VersionManager versionManager) { super(transmitter, to, description, colorID, null, invitationProcesses); this.localFileList = localFileList; this.invitationUI = inviteUI; this.saros = saros; this.sharedProject = sharedProject; this.dataTransferManager = dataTransferManager; this.versionManager = versionManager; this.monitor = monitor; this.monitor.beginTask("Performing Invitation", 100); setState(State.INITIALIZED); } public void start() { setState(State.INVITATION_SENT); transmitter.sendInviteMessage(sharedProject, peer, description, colorID, versionManager.getVersion()); this.monitor.worked(5); } public void startSynchronization() { assertState(State.GUEST_FILELIST_SENT); setState(State.SYNCHRONIZING); try { this.toSend = new LinkedList<IPath>(); this.toSend.addAll(this.remoteFileList.getAddedPaths()); this.toSend.addAll(this.remoteFileList.getAlteredPaths()); monitor.subTask("Sending Archive..."); sendArchive(monitor.newChild(70)); monitor.subTask("Waiting for Peer to Join"); if (!blockUntilJoinReceived(monitor.newChild(5))) { cancel(null, false); } } catch (RuntimeException e) { cancel("An internal error occurred while starting to synchronize: " + e.toString(), false); } } /* * (non-Javadoc) * * @see de.fu_berlin.inf.dpp.InvitationProcess */ public void invitationAccepted(JID from) { assertState(State.INVITATION_SENT); SubMonitor pmAccept = this.monitor.newChild(15); this.monitor.subTask("Sending Filelist"); pmAccept.beginTask("Invitation Accepted", 100); // HACK add resource specifier to jid if (this.peer.equals(from)) { this.peer = from; } try { // Wait for Jingle before we send the file list... this.transmitter.awaitJingleManager(this.peer); pmAccept.worked(30); // Could have been canceled in between: if (this.state == State.CANCELED) return; setState(State.HOST_FILELIST_SENT); this.transmitter.sendFileList(this.peer, this.localFileList, pmAccept.newChild(70)); // Could have been canceled in between: if (this.state == State.CANCELED) return; } catch (Exception e) { failed(e); } } public void fileListReceived(JID from, FileList fileList) { assertState(State.HOST_FILELIST_SENT); this.remoteFileList = fileList; setState(State.GUEST_FILELIST_SENT); // Run asynchronously Util.runSafeAsync("OutgoingInvitationProcess-synchronisation-", log, new Runnable() { public void run() { startSynchronization(); } }); } /** * {@inheritDoc} */ public void joinReceived(JID from) { // HACK Necessary because an empty list of files // to send causes a Race condition otherwise... blockUntil(State.SYNCHRONIZING_DONE, EnumSet.of( State.GUEST_FILELIST_SENT, State.SYNCHRONIZING)); assertState(State.SYNCHRONIZING_DONE); this.sharedProject.addUser(new User(sharedProject, from, colorID)); setState(State.DONE); this.monitor.done(); // TODO Find a more reliable way to remove InvitationProcess this.invitationProcesses.removeInvitationProcess(this); this.transmitter.sendUserListTo(from, this.sharedProject .getParticipants()); } /** * Block until the given state 'until' has been reached, but allow only the * given states as valid in the meantime. * * This method cancels if this InvitationProcess is in an invalid state. * * Returns false if the given state 'until' was not reached, but * * a.) an invalid state was reached * * b.) the cancel state was reached */ protected boolean blockUntil(State until, EnumSet<State> validStates) { while (this.state != until) { if (!validStates.contains(this.state)) { cancel("Unexpected state(" + this.state + ")", false); return false; } if (getState() == State.CANCELED) { return false; } try { Thread.sleep(100); } catch (InterruptedException e) { log.error("Code not designed to be interruptable", e); Thread.currentThread().interrupt(); return false; } } return true; } /* * (non-Javadoc) * * @see de.fu_berlin.inf.dpp.InvitationProcess */ public void resourceReceived(JID from, IPath path, InputStream in) { failState(); } /** * Send all files contained in {@link #toSend} as an archive file to the * peer of this invitation process. */ protected void sendArchive(SubMonitor monitor) { monitor.beginTask("Sending as archive", 100); File archive = null; try { if (getState() == State.CANCELED) { this.toSend.clear(); return; } if (this.toSend.size() == 0) { setState(State.SYNCHRONIZING_DONE); return; } - archive = File.createTempFile(getPeer().getName(), ".zip"); + // FIX #2836964: Prefix string too short + archive = File.createTempFile("SarosSyncArchive-" + + getPeer().getName(), ".zip"); monitor.subTask("Zipping archive"); FileZipper.createProjectZipArchive(this.toSend, archive, this.sharedProject.getProject(), monitor.newChild(30)); monitor.subTask("Sending archive"); transmitter.sendProjectArchive(this.peer, this.sharedProject .getProject(), archive, monitor.newChild(70)); if (getState() == State.SYNCHRONIZING) { setState(State.SYNCHRONIZING_DONE); } } catch (Exception e) { failed(e); } finally { // Delete Archive if (archive != null && !archive.delete()) { log.warn("Could not delete archive: " + archive.getAbsolutePath()); } monitor.done(); } } /** * Blocks until the join message has been received or the user canceled. * * @param subMonitor * * @return <code>true</code> if the join message has been received. * <code>false</code> if the user chose to cancel */ private boolean blockUntilJoinReceived(SubMonitor subMonitor) { subMonitor.beginTask("Waiting for Peer to Join", 1000); try { while (this.state != State.DONE) { if (getState() == State.CANCELED) { return false; } try { Thread.sleep(100); // Grow but never finish monitor... subMonitor.setWorkRemaining(1000); subMonitor.worked(1); } catch (InterruptedException e) { log.error("Code not designed to be interruptable", e); Thread.currentThread().interrupt(); return false; } } return true; } finally { subMonitor.done(); } } public String getProjectName() { return this.sharedProject.getProject().getName(); } @Override public void cancel(String errorMsg, boolean replicated) { super.cancel(errorMsg, replicated); if (!this.monitor.isCanceled()) this.monitor.setCanceled(true); sharedProject.returnColor(this.colorID); } }
true
true
protected void sendArchive(SubMonitor monitor) { monitor.beginTask("Sending as archive", 100); File archive = null; try { if (getState() == State.CANCELED) { this.toSend.clear(); return; } if (this.toSend.size() == 0) { setState(State.SYNCHRONIZING_DONE); return; } archive = File.createTempFile(getPeer().getName(), ".zip"); monitor.subTask("Zipping archive"); FileZipper.createProjectZipArchive(this.toSend, archive, this.sharedProject.getProject(), monitor.newChild(30)); monitor.subTask("Sending archive"); transmitter.sendProjectArchive(this.peer, this.sharedProject .getProject(), archive, monitor.newChild(70)); if (getState() == State.SYNCHRONIZING) { setState(State.SYNCHRONIZING_DONE); } } catch (Exception e) { failed(e); } finally { // Delete Archive if (archive != null && !archive.delete()) { log.warn("Could not delete archive: " + archive.getAbsolutePath()); } monitor.done(); } }
protected void sendArchive(SubMonitor monitor) { monitor.beginTask("Sending as archive", 100); File archive = null; try { if (getState() == State.CANCELED) { this.toSend.clear(); return; } if (this.toSend.size() == 0) { setState(State.SYNCHRONIZING_DONE); return; } // FIX #2836964: Prefix string too short archive = File.createTempFile("SarosSyncArchive-" + getPeer().getName(), ".zip"); monitor.subTask("Zipping archive"); FileZipper.createProjectZipArchive(this.toSend, archive, this.sharedProject.getProject(), monitor.newChild(30)); monitor.subTask("Sending archive"); transmitter.sendProjectArchive(this.peer, this.sharedProject .getProject(), archive, monitor.newChild(70)); if (getState() == State.SYNCHRONIZING) { setState(State.SYNCHRONIZING_DONE); } } catch (Exception e) { failed(e); } finally { // Delete Archive if (archive != null && !archive.delete()) { log.warn("Could not delete archive: " + archive.getAbsolutePath()); } monitor.done(); } }
diff --git a/src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java b/src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java index 3723154..2798f0b 100644 --- a/src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java +++ b/src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java @@ -1,2208 +1,2211 @@ /* // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // Copyright (C) 2007-2011 Julian Hyde // All Rights Reserved. // You must accept the terms of that agreement to use this software. */ package org.olap4j.driver.xmla; import org.olap4j.*; import static org.olap4j.driver.xmla.XmlaOlap4jUtil.*; import org.olap4j.driver.xmla.proxy.*; import org.olap4j.impl.*; import org.olap4j.mdx.ParseTreeWriter; import org.olap4j.mdx.SelectNode; import org.olap4j.mdx.parser.*; import org.olap4j.mdx.parser.impl.DefaultMdxParserImpl; import org.olap4j.metadata.*; import org.w3c.dom.*; import org.xml.sax.SAXException; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.sql.*; import java.util.*; import java.util.Map.*; import java.util.regex.*; /** * Implementation of {@link org.olap4j.OlapConnection} * for XML/A providers. * * <p>This class has sub-classes which implement JDBC 3.0 and JDBC 4.0 APIs; * it is instantiated using {@link Factory#newConnection}.</p> * * @author jhyde * @version $Id$ * @since May 23, 2007 */ abstract class XmlaOlap4jConnection implements OlapConnection { /** * Handler for errors. */ final XmlaHelper helper = new XmlaHelper(); /** * <p>Current schema. */ private XmlaOlap4jSchema olap4jSchema; final XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData; private static final String CONNECT_STRING_PREFIX = "jdbc:xmla:"; final XmlaOlap4jDriver driver; final Factory factory; final XmlaOlap4jProxy proxy; private boolean closed = false; /** * URL of the HTTP server to which to send XML requests. */ final URL serverUrl; private Locale locale; /** * Name of the current catalog to which this connection is bound to, * as specified by the server. */ private String nativeCatalogName; /** * Name of the catalog to which the user wishes to bind * this connection. This value can be set through the JDBC URL * or via {@link XmlaOlap4jConnection#setCatalog(String)} */ private String catalogName; /** * Name of the role that this connection impersonates. */ private String roleName; /** * Provider name. */ private String providerName; /** * Name of the database to which the user wishes to bind * this connection. This value can be set through the JDBC URL * or via {@link XmlaOlap4jConnection#setCatalog(String)} */ private String databaseName; /** * Holds the database name as specified by the server. Necessary because * some servers (such as Mondrian) return both the provider * name and the database name in their response. * * <p>It's this value that we use inside queries, and not the JDBC * query value. */ private String nativeDatabaseName; private boolean autoCommit; private boolean readOnly; /** * This is a private property used for development only. * Enabling it makes the connection print out all queries * to {@link System#out} */ private static final boolean DEBUG = false; /** * Name of the "DATA_SOURCE_NAME" column returned from * {@link org.olap4j.OlapDatabaseMetaData#getDatasources()}. */ private static final String DATA_SOURCE_NAME = "DATA_SOURCE_NAME"; /** * Name of the "PROVIDER_NAME" column returned from * {@link org.olap4j.OlapDatabaseMetaData#getDatasources()}. */ private static final String PROVIDER_NAME = "PROVIDER_NAME"; /** * Creates an Olap4j connection an XML/A provider. * * <p>This method is intentionally package-protected. The public API * uses the traditional JDBC {@link java.sql.DriverManager}. * See {@link org.olap4j.driver.xmla.XmlaOlap4jDriver} for more details. * * <p>Note that this constructor should make zero non-trivial calls, which * could cause deadlocks due to java.sql.DriverManager synchronization * issues. * * @pre acceptsURL(url) * * @param factory Factory * @param driver Driver * @param proxy Proxy object which receives XML requests * @param url Connect-string URL * @param info Additional properties * @throws java.sql.SQLException if there is an error */ XmlaOlap4jConnection( Factory factory, XmlaOlap4jDriver driver, XmlaOlap4jProxy proxy, String url, Properties info) throws SQLException { if (!acceptsURL(url)) { // This is not a URL we can handle. // DriverManager should not have invoked us. throw new AssertionError( "does not start with '" + CONNECT_STRING_PREFIX + "'"); } this.factory = factory; this.driver = driver; this.proxy = proxy; Map<String, String> map = parseConnectString(url, info); this.providerName = map.get(XmlaOlap4jDriver.Property.Provider.name()); this.databaseName = map.get(XmlaOlap4jDriver.Property.Database.name()); this.catalogName = map.get(XmlaOlap4jDriver.Property.Catalog.name()); // Set URL of HTTP server. String serverUrl = map.get(XmlaOlap4jDriver.Property.Server.name()); if (serverUrl == null) { throw getHelper().createException( "Connection property '" + XmlaOlap4jDriver.Property.Server.name() + "' must be specified"); } // Basic authentication. Make sure the credentials passed as standard // JDBC parameters override any credentials already included in the URL // as part of the standard URL scheme. if (map.containsKey("user") && map.containsKey("password")) { serverUrl = serverUrl.replaceFirst( ":\\/\\/([^@]*@){0,1}", "://" + map.get("user") + ":" + map.get("password") + "@"); } // Initialize the SOAP cache if needed initSoapCache(map); try { this.serverUrl = new URL(serverUrl); } catch (MalformedURLException e) { throw getHelper().createException( "Error while creating connection", e); } this.olap4jDatabaseMetaData = factory.newDatabaseMetaData(this); } /** * Returns the error-handler * @return Error-handler */ private XmlaHelper getHelper() { return helper; } /** * Initializes a cache object and configures it if cache * parameters were specified in the jdbc url. * * @param map The parameters from the jdbc url. * @throws OlapException Thrown when there is an error encountered * while creating the cache. */ private void initSoapCache(Map<String, String> map) throws OlapException { // Test if a SOAP cache class was defined if (map.containsKey(XmlaOlap4jDriver.Property.Cache.name() .toUpperCase())) { // Create a properties object to pass to the proxy // so it can configure it's cache Map<String, String> props = new HashMap<String, String>(); // Iterate over map entries to find those related to // the cache config for (Entry<String, String> entry : map.entrySet()) { // Check if the current entry relates to cache config. if (entry.getKey().startsWith( XmlaOlap4jDriver.Property.Cache.name().toUpperCase() + ".")) { props.put(entry.getKey().substring( XmlaOlap4jDriver.Property.Cache.name() .length() + 1), entry.getValue()); } } // Init the cache ((XmlaOlap4jCachedProxy) this.proxy).setCache(map, props); } } static Map<String, String> parseConnectString(String url, Properties info) { String x = url.substring(CONNECT_STRING_PREFIX.length()); Map<String, String> map = ConnectStringParser.parseConnectString(x); for (Map.Entry<String, String> entry : toMap(info).entrySet()) { map.put(entry.getKey(), entry.getValue()); } return map; } static boolean acceptsURL(String url) { return url.startsWith(CONNECT_STRING_PREFIX); } public void setDatabase(String databaseName) throws OlapException { this.databaseName = databaseName; this.nativeCatalogName = null; } public String getDatabase() throws OlapException { // If we already know it, return it. if (this.nativeDatabaseName != null) { return this.nativeDatabaseName; } ResultSet rSet = null; try { // We need to query for it rSet = this.olap4jDatabaseMetaData.getDatabases(); // Check if the user requested a particular one. if (this.databaseName != null || this.providerName != null) { // We iterate through the databases while (rSet.next()) { // Get current values String currentDatasource = rSet.getString(DATA_SOURCE_NAME); String currentProvider = rSet.getString(PROVIDER_NAME); // If database and provider match, we got it. // If database matches but no provider is specified, we // got it. // If provider matches but no database specified, we // consider it good. if (currentDatasource.equals(this.databaseName) && currentProvider.equals(this.providerName) || currentDatasource.equals(this.databaseName) && this.providerName == null || currentProvider.equals(this.providerName) && this.databaseName == null) { // Got it this.nativeDatabaseName = currentDatasource; break; } } } else { // Use first if (rSet.first()) { this.nativeDatabaseName = rSet.getString(DATA_SOURCE_NAME); } } // Throws exception to the client. Tells that there are // no database corresponding to the search criteria. if (this.nativeDatabaseName == null) { throw getHelper().createException( "No database could be found on the server."); } return this.nativeDatabaseName; } catch (OlapException e) { throw e; } catch (SQLException e) { throw getHelper().createException( "An exception occured while trying to resolve the database name.", e); } finally { try { if (rSet != null) { rSet.close(); } } catch (SQLException e) { // ignore } } } public OlapStatement createStatement() { return new XmlaOlap4jStatement(this); } public PreparedStatement prepareStatement(String sql) throws SQLException { throw new UnsupportedOperationException(); } public CallableStatement prepareCall(String sql) throws SQLException { throw new UnsupportedOperationException(); } public String nativeSQL(String sql) throws SQLException { throw new UnsupportedOperationException(); } public void setAutoCommit(boolean autoCommit) throws SQLException { this.autoCommit = autoCommit; } public boolean getAutoCommit() throws SQLException { return autoCommit; } public void commit() throws SQLException { throw new UnsupportedOperationException(); } public void rollback() throws SQLException { throw new UnsupportedOperationException(); } public void close() throws SQLException { closed = true; } public boolean isClosed() throws SQLException { return closed; } public OlapDatabaseMetaData getMetaData() { return olap4jDatabaseMetaData; } public NamedList<Catalog> getCatalogs() { return Olap4jUtil.cast(olap4jDatabaseMetaData.getCatalogObjects()); } public void setReadOnly(boolean readOnly) throws SQLException { this.readOnly = readOnly; } public boolean isReadOnly() throws SQLException { return readOnly; } public void setCatalog(String catalog) throws OlapException { this.catalogName = catalog; this.nativeCatalogName = null; } public String getCatalog() throws OlapException { if (this.nativeCatalogName == null) { if (catalogName != null) { this.nativeCatalogName = catalogName; } else if (olap4jDatabaseMetaData.getOlapCatalogs().size() == 0) { throw new OlapException( "There is no catalog available to query against."); } else { this.nativeCatalogName = olap4jDatabaseMetaData.getOlapCatalogs().get(0).getName(); } } return nativeCatalogName; } public void setTransactionIsolation(int level) throws SQLException { throw new UnsupportedOperationException(); } public int getTransactionIsolation() throws SQLException { return TRANSACTION_NONE; } public SQLWarning getWarnings() throws SQLException { throw new UnsupportedOperationException(); } public void clearWarnings() throws SQLException { // this driver does not support warnings, so nothing to do } public Statement createStatement( int resultSetType, int resultSetConcurrency) throws SQLException { throw new UnsupportedOperationException(); } public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency) throws SQLException { throw new UnsupportedOperationException(); } public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency) throws SQLException { throw new UnsupportedOperationException(); } public Map<String, Class<?>> getTypeMap() throws SQLException { throw new UnsupportedOperationException(); } public void setTypeMap(Map<String, Class<?>> map) throws SQLException { throw new UnsupportedOperationException(); } public void setHoldability(int holdability) throws SQLException { throw new UnsupportedOperationException(); } public int getHoldability() throws SQLException { throw new UnsupportedOperationException(); } public Savepoint setSavepoint() throws SQLException { throw new UnsupportedOperationException(); } public Savepoint setSavepoint(String name) throws SQLException { throw new UnsupportedOperationException(); } public void rollback(Savepoint savepoint) throws SQLException { throw new UnsupportedOperationException(); } public void releaseSavepoint(Savepoint savepoint) throws SQLException { throw new UnsupportedOperationException(); } public Statement createStatement( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { throw new UnsupportedOperationException(); } public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { throw new UnsupportedOperationException(); } public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { throw new UnsupportedOperationException(); } public PreparedStatement prepareStatement( String sql, int autoGeneratedKeys) throws SQLException { throw new UnsupportedOperationException(); } public PreparedStatement prepareStatement( String sql, int columnIndexes[]) throws SQLException { throw new UnsupportedOperationException(); } public PreparedStatement prepareStatement( String sql, String columnNames[]) throws SQLException { throw new UnsupportedOperationException(); } // implement Wrapper public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return iface.cast(this); } throw getHelper().createException("does not implement '" + iface + "'"); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } // implement OlapConnection public PreparedOlapStatement prepareOlapStatement( String mdx) throws OlapException { return factory.newPreparedStatement(mdx, this); } public MdxParserFactory getParserFactory() { return new MdxParserFactory() { public MdxParser createMdxParser(OlapConnection connection) { return new DefaultMdxParserImpl(); } public MdxValidator createMdxValidator(OlapConnection connection) { return new XmlaOlap4jMdxValidator(connection); } }; } @Deprecated /* * This function must either be removed and the tests adapted or * be made package private. */ public synchronized org.olap4j.metadata.Schema getSchema() throws OlapException { // initializes the olap4jSchema if necessary if (this.olap4jSchema == null) { final XmlaOlap4jCatalog catalog = this.olap4jDatabaseMetaData.getCatalogObjects().get( getCatalog()); this.olap4jSchema = catalog.schemas.get(0); } return olap4jSchema; } public static Map<String, String> toMap(final Properties properties) { return new AbstractMap<String, String>() { public Set<Entry<String, String>> entrySet() { return Olap4jUtil.cast(properties.entrySet()); } }; } /** * Returns the URL which was used to create this connection. * * @return URL */ String getURL() { throw Olap4jUtil.needToImplement(this); } public void setLocale(Locale locale) { if (locale == null) { throw new IllegalArgumentException("locale must not be null"); } this.locale = locale; } public Locale getLocale() { if (locale == null) { return Locale.getDefault(); } return locale; } public void setRoleName(String roleName) throws OlapException { this.roleName = roleName; } public String getRoleName() { return roleName; } public List<String> getAvailableRoleNames() { // List of available roles is not known. Could potentially add an XMLA // call to populate this list if useful to a client. return null; } public Scenario createScenario() { throw new UnsupportedOperationException(); } public void setScenario(Scenario scenario) { throw new UnsupportedOperationException(); } public Scenario getScenario() { throw new UnsupportedOperationException(); } <T extends Named> void populateList( List<T> list, Context context, MetadataRequest metadataRequest, Handler<T> handler, Object[] restrictions) throws OlapException { String request = generateRequest(context, metadataRequest, restrictions); Element root = executeMetadataRequest(request); for (Element o : childElements(root)) { if (o.getLocalName().equals("row")) { handler.handle(o, context, list); } } handler.sortList(list); } /** * Executes an XMLA metadata request and returns the root element of the * response. * * @param request XMLA request string * @return Root element of the response * @throws OlapException on error */ Element executeMetadataRequest(String request) throws OlapException { byte[] bytes; if (DEBUG) { System.out.println("********************************************"); System.out.println("** SENDING REQUEST :"); System.out.println(request); } try { bytes = proxy.get(serverUrl, request); } catch (IOException e) { /* * FIXME This type of exception should not reach this point. * It was maintained because some other proxy implementations * exists out there that still throw an IOException arround. * This was a bad design which we will fix at some point but not * before the 1.0 release. */ throw getHelper().createException(e); } catch (XmlaOlap4jProxyException e) { throw getHelper().createException( "This connection encountered an exception while executing a query.", e); } Document doc; try { doc = parse(bytes); } catch (IOException e) { throw getHelper().createException( "error discovering metadata", e); } catch (SAXException e) { throw getHelper().createException( "error discovering metadata", e); } // <SOAP-ENV:Envelope> // <SOAP-ENV:Header/> // <SOAP-ENV:Body> // <xmla:DiscoverResponse> // <xmla:return> // <root> // (see below) // </root> // <xmla:return> // </xmla:DiscoverResponse> // </SOAP-ENV:Body> // </SOAP-ENV:Envelope> final Element envelope = doc.getDocumentElement(); if (DEBUG) { System.out.println("** SERVER RESPONSE :"); System.out.println(XmlaOlap4jUtil.toString(doc, true)); } assert envelope.getLocalName().equals("Envelope"); assert envelope.getNamespaceURI().equals(SOAP_NS); Element body = findChild(envelope, SOAP_NS, "Body"); Element fault = findChild(body, SOAP_NS, "Fault"); if (fault != null) { /* <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Client.00HSBC01</faultcode> <faultstring>XMLA connection datasource not found</faultstring> <faultactor>Mondrian</faultactor> <detail> <XA:error xmlns:XA="http://mondrian.sourceforge.net"> <code>00HSBC01</code> <desc>The Mondrian XML: Mondrian Error:Internal error: no catalog named 'LOCALDB'</desc> </XA:error> </detail> </SOAP-ENV:Fault> */ // TODO: log doc to logfile throw getHelper().createException( "XMLA provider gave exception: " + XmlaOlap4jUtil.prettyPrint(fault) + "\n" + "Request was:\n" + request); } Element discoverResponse = findChild(body, XMLA_NS, "DiscoverResponse"); Element returnElement = findChild(discoverResponse, XMLA_NS, "return"); return findChild(returnElement, ROWSET_NS, "root"); } /** * Generates a metadata request. * * <p>The list of restrictions must have even length. Even elements must * be a string (the name of the restriction); odd elements must be either * a string (the value of the restriction) or a list of strings (multiple * values of the restriction) * * @param context Context * @param metadataRequest Metadata request * @param restrictions List of restrictions * @return XMLA SOAP request as a string. * * @throws OlapException when the query depends on a datasource name but * the one specified doesn't exist at the url, or there are no default * datasource (should use the first one) */ public String generateRequest( Context context, MetadataRequest metadataRequest, Object[] restrictions) throws OlapException { final String content = "Data"; final String encoding = proxy.getEncodingCharsetName(); final StringBuilder buf = new StringBuilder( "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n" + "<SOAP-ENV:Envelope\n" + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <SOAP-ENV:Body>\n" + " <Discover xmlns=\"urn:schemas-microsoft-com:xml-analysis\"\n" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <RequestType>"); buf.append(metadataRequest.name()); buf.append( "</RequestType>\n" + " <Restrictions>\n" + " <RestrictionList>\n"); String restrictedCatalogName = null; if (restrictions.length > 0) { if (restrictions.length % 2 != 0) { throw new IllegalArgumentException(); } for (int i = 0; i < restrictions.length; i += 2) { final String restriction = (String) restrictions[i]; final Object o = restrictions[i + 1]; if (o instanceof String) { buf.append("<").append(restriction).append(">"); final String value = (String) o; xmlEncode(buf, value); buf.append("</").append(restriction).append(">"); // To remind ourselves to generate a <Catalog> restriction // if the request supports it. if (restriction.equals("CATALOG_NAME")) { restrictedCatalogName = value; } } else { //noinspection unchecked List<String> valueList = (List<String>) o; for (String value : valueList) { buf.append("<").append(restriction).append(">"); xmlEncode(buf, value); buf.append("</").append(restriction).append(">"); } } } } buf.append( " </RestrictionList>\n" + " </Restrictions>\n" + " <Properties>\n" + " <PropertyList>\n"); // Add the datasource node only if this request requires it. if (metadataRequest.requiresDatasourceName()) { buf.append(" <DataSourceInfo>"); xmlEncode(buf, context.olap4jConnection.getDatabase()); buf.append("</DataSourceInfo>\n"); } String requestCatalogName = null; if (restrictedCatalogName != null && restrictedCatalogName.length() > 0) { requestCatalogName = restrictedCatalogName; } // If the request requires catalog name, and one wasn't specified in the - // restrictions, use the connection's current schema. (Note: What XMLA - // calls a catalog, JDBC calls a schema.) - if (context.olap4jSchema != null) { - requestCatalogName = context.olap4jSchema.getName(); + // restrictions, use the connection's current catalog. + if (context.olap4jCatalog != null) { + requestCatalogName = context.olap4jCatalog.getName(); } if (requestCatalogName == null && metadataRequest.requiresCatalogName()) { - requestCatalogName = context.olap4jConnection.getSchema().getName(); + List<Catalog> catalogs = + context.olap4jConnection.getMetaData().getOlapCatalogs(); + if (catalogs.size() > 0) { + requestCatalogName = catalogs.get(0).getName(); + } } // Add the catalog node only if this request has specified it as a // restriction. // // For low-level objects like cube, the restriction is optional; you can // specify null to not restrict, "" to match cubes whose catalog name is // empty, or a string (not interpreted as a wild card). (See // OlapDatabaseMetaData.getCubes API doc for more details.) We assume // that the request provides the restriction only if it is valid. // // For high level objects like data source and catalog, the catalog // restriction does not make sense. if (requestCatalogName != null && metadataRequest.allowsCatalogName()) { if (getMetaData().getOlapCatalogs() .get(requestCatalogName) == null) { throw new OlapException( "No catalog named " + requestCatalogName + " exist on the server."); } buf.append(" <Catalog>"); xmlEncode(buf, requestCatalogName); buf.append("</Catalog>\n"); } buf.append(" <Content>"); xmlEncode(buf, content); buf.append( "</Content>\n" + " </PropertyList>\n" + " </Properties>\n" + " </Discover>\n" + "</SOAP-ENV:Body>\n" + "</SOAP-ENV:Envelope>"); return buf.toString(); } /** * Encodes a string for use in an XML CDATA section. * * @param value Value to be xml encoded * @param buf Buffer to append to */ private static void xmlEncode(StringBuilder buf, String value) { final int n = value.length(); for (int i = 0; i < n; ++i) { char c = value.charAt(i); switch (c) { case '&': buf.append("&amp;"); break; case '<': buf.append("&lt;"); break; case '>': buf.append("&gt;"); break; case '"': buf.append("&quot;"); break; case '\'': buf.append("&apos;"); break; default: buf.append(c); } } } // ~ inner classes -------------------------------------------------------- static class CatalogHandler extends HandlerImpl<XmlaOlap4jCatalog> { public void handle( Element row, Context context, List<XmlaOlap4jCatalog> list) { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <DESCRIPTION>No description available</DESCRIPTION> <ROLES>California manager,No HR Cube</ROLES> </row> */ String catalogName = XmlaOlap4jUtil.stringElement(row, "CATALOG_NAME"); // Unused: DESCRIPTION, ROLES list.add( new XmlaOlap4jCatalog( context.olap4jDatabaseMetaData, catalogName)); } } static class CubeHandler extends HandlerImpl<XmlaOlap4jCube> { public void handle( Element row, Context context, List<XmlaOlap4jCube> list) throws OlapException { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>HR</CUBE_NAME> <CUBE_TYPE>CUBE</CUBE_TYPE> <IS_DRILLTHROUGH_ENABLED>true</IS_DRILLTHROUGH_ENABLED> <IS_WRITE_ENABLED>false</IS_WRITE_ENABLED> <IS_LINKABLE>false</IS_LINKABLE> <IS_SQL_ENABLED>false</IS_SQL_ENABLED> <DESCRIPTION>FoodMart Schema - HR Cube</DESCRIPTION> </row> */ // Unused: CATALOG_NAME, SCHEMA_NAME, CUBE_TYPE, // IS_DRILLTHROUGH_ENABLED, IS_WRITE_ENABLED, IS_LINKABLE, // IS_SQL_ENABLED String cubeName = stringElement(row, "CUBE_NAME"); String description = stringElement(row, "DESCRIPTION"); list.add( new XmlaOlap4jCube( context.olap4jSchema, cubeName, description)); } } static class DimensionHandler extends HandlerImpl<XmlaOlap4jDimension> { private final XmlaOlap4jCube cubeForCallback; public DimensionHandler(XmlaOlap4jCube dimensionsByUname) { this.cubeForCallback = dimensionsByUname; } public void handle( Element row, Context context, List<XmlaOlap4jDimension> list) { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>HR</CUBE_NAME> <DIMENSION_NAME>Department</DIMENSION_NAME> <DIMENSION_UNIQUE_NAME>[Department]</DIMENSION_UNIQUE_NAME> <DIMENSION_CAPTION>Department</DIMENSION_CAPTION> <DIMENSION_ORDINAL>6</DIMENSION_ORDINAL> <DIMENSION_TYPE>3</DIMENSION_TYPE> <DIMENSION_CARDINALITY>13</DIMENSION_CARDINALITY> <DEFAULT_HIERARCHY>[Department]</DEFAULT_HIERARCHY> <DESCRIPTION>HR Cube - Department Dimension</DESCRIPTION> <IS_VIRTUAL>false</IS_VIRTUAL> <IS_READWRITE>false</IS_READWRITE> <DIMENSION_UNIQUE_SETTINGS>0</DIMENSION_UNIQUE_SETTINGS> <DIMENSION_IS_VISIBLE>true</DIMENSION_IS_VISIBLE> </row> */ final String dimensionName = stringElement(row, "DIMENSION_NAME"); final String dimensionUniqueName = stringElement(row, "DIMENSION_UNIQUE_NAME"); final String dimensionCaption = stringElement(row, "DIMENSION_CAPTION"); final String description = stringElement(row, "DESCRIPTION"); final int dimensionType = integerElement(row, "DIMENSION_TYPE"); final Dimension.Type type = Dimension.Type.getDictionary().forOrdinal(dimensionType); final String defaultHierarchyUniqueName = stringElement(row, "DEFAULT_HIERARCHY"); final Integer dimensionOrdinal = integerElement(row, "DIMENSION_ORDINAL"); XmlaOlap4jDimension dimension = new XmlaOlap4jDimension( context.olap4jCube, dimensionUniqueName, dimensionName, dimensionCaption, description, type, defaultHierarchyUniqueName, dimensionOrdinal == null ? 0 : dimensionOrdinal); list.add(dimension); if (dimensionOrdinal != null) { Collections.sort( list, new Comparator<XmlaOlap4jDimension> () { public int compare( XmlaOlap4jDimension d1, XmlaOlap4jDimension d2) { if (d1.getOrdinal() == d2.getOrdinal()) { return 0; } else if (d1.getOrdinal() > d2.getOrdinal()) { return 1; } else { return -1; } } }); } this.cubeForCallback.dimensionsByUname.put( dimension.getUniqueName(), dimension); } } static class HierarchyHandler extends HandlerImpl<XmlaOlap4jHierarchy> { private final XmlaOlap4jCube cubeForCallback; public HierarchyHandler(XmlaOlap4jCube cubeForCallback) { this.cubeForCallback = cubeForCallback; } public void handle( Element row, Context context, List<XmlaOlap4jHierarchy> list) throws OlapException { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>Sales</CUBE_NAME> <DIMENSION_UNIQUE_NAME>[Customers]</DIMENSION_UNIQUE_NAME> <HIERARCHY_NAME>Customers</HIERARCHY_NAME> <HIERARCHY_UNIQUE_NAME>[Customers]</HIERARCHY_UNIQUE_NAME> <HIERARCHY_CAPTION>Customers</HIERARCHY_CAPTION> <DIMENSION_TYPE>3</DIMENSION_TYPE> <HIERARCHY_CARDINALITY>10407</HIERARCHY_CARDINALITY> <DEFAULT_MEMBER>[Customers].[All Customers]</DEFAULT_MEMBER> <ALL_MEMBER>[Customers].[All Customers]</ALL_MEMBER> <DESCRIPTION>Sales Cube - Customers Hierarchy</DESCRIPTION> <STRUCTURE>0</STRUCTURE> <IS_VIRTUAL>false</IS_VIRTUAL> <IS_READWRITE>false</IS_READWRITE> <DIMENSION_UNIQUE_SETTINGS>0</DIMENSION_UNIQUE_SETTINGS> <DIMENSION_IS_VISIBLE>true</DIMENSION_IS_VISIBLE> <HIERARCHY_ORDINAL>9</HIERARCHY_ORDINAL> <DIMENSION_IS_SHARED>true</DIMENSION_IS_SHARED> <PARENT_CHILD>false</PARENT_CHILD> </row> */ final String hierarchyUniqueName = stringElement(row, "HIERARCHY_UNIQUE_NAME"); // SAP BW doesn't return a HIERARCHY_NAME attribute, // so try to use the unique name instead final String hierarchyName = stringElement(row, "HIERARCHY_NAME") == null ? (hierarchyUniqueName != null ? hierarchyUniqueName.replaceAll("^\\[", "") .replaceAll("\\]$", "") : null) : stringElement(row, "HIERARCHY_NAME"); final String hierarchyCaption = stringElement(row, "HIERARCHY_CAPTION"); final String description = stringElement(row, "DESCRIPTION"); final String allMember = stringElement(row, "ALL_MEMBER"); final String defaultMemberUniqueName = stringElement(row, "DEFAULT_MEMBER"); XmlaOlap4jHierarchy hierarchy = new XmlaOlap4jHierarchy( context.getDimension(row), hierarchyUniqueName, hierarchyName, hierarchyCaption, description, allMember != null, defaultMemberUniqueName); list.add(hierarchy); cubeForCallback.hierarchiesByUname.put( hierarchy.getUniqueName(), hierarchy); } } static class LevelHandler extends HandlerImpl<XmlaOlap4jLevel> { public static final int MDLEVEL_TYPE_CALCULATED = 0x0002; private final XmlaOlap4jCube cubeForCallback; public LevelHandler(XmlaOlap4jCube cubeForCallback) { this.cubeForCallback = cubeForCallback; } public void handle( Element row, Context context, List<XmlaOlap4jLevel> list) { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>Sales</CUBE_NAME> <DIMENSION_UNIQUE_NAME>[Customers]</DIMENSION_UNIQUE_NAME> <HIERARCHY_UNIQUE_NAME>[Customers]</HIERARCHY_UNIQUE_NAME> <LEVEL_NAME>(All)</LEVEL_NAME> <LEVEL_UNIQUE_NAME>[Customers].[(All)]</LEVEL_UNIQUE_NAME> <LEVEL_CAPTION>(All)</LEVEL_CAPTION> <LEVEL_NUMBER>0</LEVEL_NUMBER> <LEVEL_CARDINALITY>1</LEVEL_CARDINALITY> <LEVEL_TYPE>1</LEVEL_TYPE> <CUSTOM_ROLLUP_SETTINGS>0</CUSTOM_ROLLUP_SETTINGS> <LEVEL_UNIQUE_SETTINGS>3</LEVEL_UNIQUE_SETTINGS> <LEVEL_IS_VISIBLE>true</LEVEL_IS_VISIBLE> <DESCRIPTION>Sales Cube - Customers Hierarchy - (All) Level</DESCRIPTION> </row> */ final String levelUniqueName = stringElement(row, "LEVEL_UNIQUE_NAME"); // SAP BW doesn't return a HIERARCHY_NAME attribute, // so try to use the unique name instead final String levelName = stringElement(row, "LEVEL_NAME") == null ? (levelUniqueName != null ? levelUniqueName.replaceAll("^\\[", "") .replaceAll("\\]$", "") : null) : stringElement(row, "LEVEL_NAME"); final String levelCaption = stringElement(row, "LEVEL_CAPTION"); final String description = stringElement(row, "DESCRIPTION"); final int levelNumber = integerElement(row, "LEVEL_NUMBER"); final Integer levelTypeCode = integerElement(row, "LEVEL_TYPE"); final Level.Type levelType = Level.Type.getDictionary().forOrdinal(levelTypeCode); boolean calculated = (levelTypeCode & MDLEVEL_TYPE_CALCULATED) != 0; final int levelCardinality = integerElement(row, "LEVEL_CARDINALITY"); XmlaOlap4jLevel level = new XmlaOlap4jLevel( context.getHierarchy(row), levelUniqueName, levelName, levelCaption, description, levelNumber, levelType, calculated, levelCardinality); list.add(level); cubeForCallback.levelsByUname.put( level.getUniqueName(), level); } } static class MeasureHandler extends HandlerImpl<XmlaOlap4jMeasure> { public void handle( Element row, Context context, List<XmlaOlap4jMeasure> list) throws OlapException { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>Sales</CUBE_NAME> <MEASURE_NAME>Profit</MEASURE_NAME> <MEASURE_UNIQUE_NAME>[Measures].[Profit]</MEASURE_UNIQUE_NAME> <MEASURE_CAPTION>Profit</MEASURE_CAPTION> <MEASURE_AGGREGATOR>127</MEASURE_AGGREGATOR> <DATA_TYPE>130</DATA_TYPE> <MEASURE_IS_VISIBLE>true</MEASURE_IS_VISIBLE> <DESCRIPTION>Sales Cube - Profit Member</DESCRIPTION> </row> */ final String measureName = stringElement(row, "MEASURE_NAME"); final String measureUniqueName = stringElement(row, "MEASURE_UNIQUE_NAME"); final String measureCaption = stringElement(row, "MEASURE_CAPTION"); final String description = stringElement(row, "DESCRIPTION"); final Measure.Aggregator measureAggregator = Measure.Aggregator.getDictionary().forOrdinal( integerElement( row, "MEASURE_AGGREGATOR")); final Datatype datatype; Datatype ordinalDatatype = Datatype.getDictionary().forName( stringElement(row, "DATA_TYPE")); if (ordinalDatatype == null) { datatype = Datatype.getDictionary().forOrdinal( integerElement(row, "DATA_TYPE")); } else { datatype = ordinalDatatype; } final boolean measureIsVisible = booleanElement(row, "MEASURE_IS_VISIBLE"); final Member member = context.getCube(row).getMetadataReader() .lookupMemberByUniqueName( measureUniqueName); if (member == null) { throw new OlapException( "The server failed to resolve a member with the same unique name as a measure named " + measureUniqueName); } list.add( new XmlaOlap4jMeasure( (XmlaOlap4jLevel)member.getLevel(), measureUniqueName, measureName, measureCaption, description, null, measureAggregator, datatype, measureIsVisible, member.getOrdinal())); } public void sortList(List<XmlaOlap4jMeasure> list) { Collections.sort( list, new Comparator<XmlaOlap4jMeasure>() { public int compare( XmlaOlap4jMeasure o1, XmlaOlap4jMeasure o2) { return o1.getOrdinal() - o2.getOrdinal(); } } ); } } static class MemberHandler extends HandlerImpl<XmlaOlap4jMember> { /** * Collection of nodes to ignore because they represent standard * built-in properties of Members. */ private static final Set<String> EXCLUDED_PROPERTY_NAMES = new HashSet<String>( Arrays.asList( Property.StandardMemberProperty.CATALOG_NAME.name(), Property.StandardMemberProperty.CUBE_NAME.name(), Property.StandardMemberProperty.DIMENSION_UNIQUE_NAME .name(), Property.StandardMemberProperty.HIERARCHY_UNIQUE_NAME .name(), Property.StandardMemberProperty.LEVEL_UNIQUE_NAME.name(), Property.StandardMemberProperty.PARENT_LEVEL.name(), Property.StandardMemberProperty.PARENT_COUNT.name(), Property.StandardMemberProperty.MEMBER_KEY.name(), Property.StandardMemberProperty.IS_PLACEHOLDERMEMBER.name(), Property.StandardMemberProperty.IS_DATAMEMBER.name(), Property.StandardMemberProperty.LEVEL_NUMBER.name(), Property.StandardMemberProperty.MEMBER_ORDINAL.name(), Property.StandardMemberProperty.MEMBER_UNIQUE_NAME.name(), Property.StandardMemberProperty.MEMBER_NAME.name(), Property.StandardMemberProperty.PARENT_UNIQUE_NAME.name(), Property.StandardMemberProperty.MEMBER_TYPE.name(), Property.StandardMemberProperty.MEMBER_CAPTION.name(), Property.StandardMemberProperty.CHILDREN_CARDINALITY.name(), Property.StandardMemberProperty.DEPTH.name())); /** * Cached value returned by the {@link Member.Type#values} method, which * calls {@link Class#getEnumConstants()} and unfortunately clones an * array every time. */ private static final Member.Type[] MEMBER_TYPE_VALUES = Member.Type.values(); public void handle( Element row, Context context, List<XmlaOlap4jMember> list) { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>Sales</CUBE_NAME> <DIMENSION_UNIQUE_NAME>[Gender]</DIMENSION_UNIQUE_NAME> <HIERARCHY_UNIQUE_NAME>[Gender]</HIERARCHY_UNIQUE_NAME> <LEVEL_UNIQUE_NAME>[Gender].[Gender]</LEVEL_UNIQUE_NAME> <LEVEL_NUMBER>1</LEVEL_NUMBER> <MEMBER_ORDINAL>1</MEMBER_ORDINAL> <MEMBER_NAME>F</MEMBER_NAME> <MEMBER_UNIQUE_NAME>[Gender].[F]</MEMBER_UNIQUE_NAME> <MEMBER_TYPE>1</MEMBER_TYPE> <MEMBER_CAPTION>F</MEMBER_CAPTION> <CHILDREN_CARDINALITY>0</CHILDREN_CARDINALITY> <PARENT_LEVEL>0</PARENT_LEVEL> <PARENT_UNIQUE_NAME>[Gender].[All Gender]</PARENT_UNIQUE_NAME> <PARENT_COUNT>1</PARENT_COUNT> <DEPTH>1</DEPTH> <!-- mondrian-specific --> </row> */ if (false) { int levelNumber = integerElement( row, Property.StandardMemberProperty.LEVEL_NUMBER.name()); } int memberOrdinal = integerElement( row, Property.StandardMemberProperty.MEMBER_ORDINAL.name()); String memberUniqueName = stringElement( row, Property.StandardMemberProperty.MEMBER_UNIQUE_NAME.name()); String memberName = stringElement( row, Property.StandardMemberProperty.MEMBER_NAME.name()); String parentUniqueName = stringElement( row, Property.StandardMemberProperty.PARENT_UNIQUE_NAME.name()); Member.Type memberType = MEMBER_TYPE_VALUES[ integerElement( row, Property.StandardMemberProperty.MEMBER_TYPE.name())]; String memberCaption = stringElement( row, Property.StandardMemberProperty.MEMBER_CAPTION.name()); int childrenCardinality = integerElement( row, Property.StandardMemberProperty.CHILDREN_CARDINALITY .name()); // Gather member property values into a temporary map, so we can // create the member with all properties known. XmlaOlap4jMember // uses an ArrayMap for property values and it is not efficient to // add entries to the map one at a time. final XmlaOlap4jLevel level = context.getLevel(row); final Map<Property, Object> map = new HashMap<Property, Object>(); addUserDefinedDimensionProperties(row, level, map); // Usually members have the same depth as their level. (Ragged and // parent-child hierarchies are an exception.) Only store depth for // the unusual ones. final Integer depth = integerElement( row, Property.StandardMemberProperty.DEPTH.name()); if (depth != null && depth.intValue() != level.getDepth()) { map.put( Property.StandardMemberProperty.DEPTH, depth); } // If this member is a measure, we want to return an object that // implements the Measure interface to all API calls. But we also // need to retrieve the properties that occur in MDSCHEMA_MEMBERS // that are not available in MDSCHEMA_MEASURES, so we create a // member for internal use. XmlaOlap4jMember member = new XmlaOlap4jMember( level, memberUniqueName, memberName, memberCaption, "", parentUniqueName, memberType, childrenCardinality, memberOrdinal, map); list.add(member); } private void addUserDefinedDimensionProperties( Element row, XmlaOlap4jLevel level, Map<Property, Object> map) { NodeList nodes = row.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (EXCLUDED_PROPERTY_NAMES.contains(node.getLocalName())) { continue; } for (Property property : level.getProperties()) { if (property instanceof XmlaOlap4jProperty && property.getName().equalsIgnoreCase( node.getLocalName())) { map.put(property, node.getTextContent()); } } } } } static class NamedSetHandler extends HandlerImpl<XmlaOlap4jNamedSet> { public void handle( Element row, Context context, List<XmlaOlap4jNamedSet> list) { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>Warehouse</CUBE_NAME> <SET_NAME>[Top Sellers]</SET_NAME> <SCOPE>1</SCOPE> </row> */ final String setName = stringElement(row, "SET_NAME"); list.add( new XmlaOlap4jNamedSet( context.getCube(row), setName)); } } static class SchemaHandler extends HandlerImpl<XmlaOlap4jSchema> { public void handle( Element row, Context context, List<XmlaOlap4jSchema> list) throws OlapException { /* Example: <row> <CATALOG_NAME>LOCALDB</CATLAOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <SCHEMA_OWNER>dbo</SCHEMA_OWNER> </row> */ String schemaName = stringElement(row, "SCHEMA_NAME"); list.add( new XmlaOlap4jSchema( context.getCatalog(row), (schemaName == null) ? "" : schemaName)); } } static class CatalogSchemaHandler extends HandlerImpl<XmlaOlap4jSchema> { private String catalogName; public CatalogSchemaHandler(String catalogName) { super(); if (catalogName == null) { throw new RuntimeException( "The CatalogSchemaHandler handler requires a catalog " + "name."); } this.catalogName = catalogName; } public void handle( Element row, Context context, List<XmlaOlap4jSchema> list) throws OlapException { /* Example: <row> <CATALOG_NAME>CatalogName</CATLAOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <SCHEMA_OWNER>dbo</SCHEMA_OWNER> </row> */ // We are looking for a schema name from the cubes query restricted // on the catalog name. Some servers don't support nor include the // SCHEMA_NAME column in its response. If it's null, we convert it // to an empty string as to not cause problems later on. final String schemaName = stringElement(row, "SCHEMA_NAME"); final String catalogName = stringElement(row, "CATALOG_NAME"); final String schemaName2 = (schemaName == null) ? "" : schemaName; if (this.catalogName.equals(catalogName) && ((NamedList<XmlaOlap4jSchema>)list).get(schemaName2) == null) { list.add( new XmlaOlap4jSchema( context.getCatalog(row), schemaName2)); } } } static class PropertyHandler extends HandlerImpl<XmlaOlap4jProperty> { public void handle( Element row, Context context, List<XmlaOlap4jProperty> list) throws OlapException { /* Example: <row> <CATALOG_NAME>FoodMart</CATALOG_NAME> <SCHEMA_NAME>FoodMart</SCHEMA_NAME> <CUBE_NAME>HR</CUBE_NAME> <DIMENSION_UNIQUE_NAME>[Store]</DIMENSION_UNIQUE_NAME> <HIERARCHY_UNIQUE_NAME>[Store]</HIERARCHY_UNIQUE_NAME> <LEVEL_UNIQUE_NAME>[Store].[Store Name]</LEVEL_UNIQUE_NAME> <PROPERTY_NAME>Store Manager</PROPERTY_NAME> <PROPERTY_CAPTION>Store Manager</PROPERTY_CAPTION> <PROPERTY_TYPE>1</PROPERTY_TYPE> <DATA_TYPE>130</DATA_TYPE> <PROPERTY_CONTENT_TYPE>0</PROPERTY_CONTENT_TYPE> <DESCRIPTION>HR Cube - Store Hierarchy - Store Name Level - Store Manager Property</DESCRIPTION> </row> */ String description = stringElement(row, "DESCRIPTION"); String uniqueName = stringElement(row, "DESCRIPTION"); String caption = stringElement(row, "PROPERTY_CAPTION"); String name = stringElement(row, "PROPERTY_NAME"); Datatype datatype; Datatype ordinalDatatype = Datatype.getDictionary().forName( stringElement(row, "DATA_TYPE")); if (ordinalDatatype == null) { datatype = Datatype.getDictionary().forOrdinal( integerElement(row, "DATA_TYPE")); } else { datatype = ordinalDatatype; } final Integer contentTypeOrdinal = integerElement(row, "PROPERTY_CONTENT_TYPE"); Property.ContentType contentType = contentTypeOrdinal == null ? null : Property.ContentType.getDictionary().forOrdinal( contentTypeOrdinal); int propertyType = integerElement(row, "PROPERTY_TYPE"); Set<Property.TypeFlag> type = Property.TypeFlag.getDictionary().forMask(propertyType); list.add( new XmlaOlap4jProperty( uniqueName, name, caption, description, datatype, type, contentType)); } } /** * Callback for converting XMLA results into metadata elements. */ interface Handler<T extends Named> { /** * Converts an XML element from an XMLA result set into a metadata * element and appends it to a list of metadata elements. * * @param row XMLA element * * @param context Context (schema, cube, dimension, etc.) that the * request was executed in and that the element will belong to * * @param list List of metadata elements to append new metadata element * * @throws OlapException on error */ void handle( Element row, Context context, List<T> list) throws OlapException; /** * Sorts a list of metadata elements. * * <p>For most element types, the order returned by XMLA is correct, and * this method will no-op. * * @param list List of metadata elements */ void sortList(List<T> list); } static abstract class HandlerImpl<T extends Named> implements Handler<T> { public void sortList(List<T> list) { // do nothing - assume XMLA returned list in correct order } } static class Context { final XmlaOlap4jConnection olap4jConnection; final XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData; final XmlaOlap4jCatalog olap4jCatalog; final XmlaOlap4jSchema olap4jSchema; final XmlaOlap4jCube olap4jCube; final XmlaOlap4jDimension olap4jDimension; final XmlaOlap4jHierarchy olap4jHierarchy; final XmlaOlap4jLevel olap4jLevel; /** * Creates a Context. * * @param olap4jConnection Connection (must not be null) * @param olap4jDatabaseMetaData DatabaseMetaData (may be null) * @param olap4jCatalog Catalog (may be null if DatabaseMetaData is * null) * @param olap4jSchema Schema (may be null if Catalog is null) * @param olap4jCube Cube (may be null if Schema is null) * @param olap4jDimension Dimension (may be null if Cube is null) * @param olap4jHierarchy Hierarchy (may be null if Dimension is null) * @param olap4jLevel Level (may be null if Hierarchy is null) */ Context( XmlaOlap4jConnection olap4jConnection, XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData, XmlaOlap4jCatalog olap4jCatalog, XmlaOlap4jSchema olap4jSchema, XmlaOlap4jCube olap4jCube, XmlaOlap4jDimension olap4jDimension, XmlaOlap4jHierarchy olap4jHierarchy, XmlaOlap4jLevel olap4jLevel) { this.olap4jConnection = olap4jConnection; this.olap4jDatabaseMetaData = olap4jDatabaseMetaData; this.olap4jCatalog = olap4jCatalog; this.olap4jSchema = olap4jSchema; this.olap4jCube = olap4jCube; this.olap4jDimension = olap4jDimension; this.olap4jHierarchy = olap4jHierarchy; this.olap4jLevel = olap4jLevel; assert (olap4jDatabaseMetaData != null || olap4jCatalog == null) && (olap4jCatalog != null || olap4jSchema == null) && (olap4jSchema != null || olap4jCube == null) && (olap4jCube != null || olap4jDimension == null) && (olap4jDimension != null || olap4jHierarchy == null) && (olap4jHierarchy != null || olap4jLevel == null); } /** * Shorthand way to create a Context at Cube level or finer. * * @param olap4jCube Cube (must not be null) * @param olap4jDimension Dimension (may be null) * @param olap4jHierarchy Hierarchy (may be null if Dimension is null) * @param olap4jLevel Level (may be null if Hierarchy is null) */ Context( XmlaOlap4jCube olap4jCube, XmlaOlap4jDimension olap4jDimension, XmlaOlap4jHierarchy olap4jHierarchy, XmlaOlap4jLevel olap4jLevel) { this( olap4jCube.olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData .olap4jConnection, olap4jCube.olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData, olap4jCube.olap4jSchema.olap4jCatalog, olap4jCube.olap4jSchema, olap4jCube, olap4jDimension, olap4jHierarchy, olap4jLevel); } /** * Shorthand way to create a Context at Level level. * * @param olap4jLevel Level (must not be null) */ Context(XmlaOlap4jLevel olap4jLevel) { this( olap4jLevel.olap4jHierarchy.olap4jDimension.olap4jCube, olap4jLevel.olap4jHierarchy.olap4jDimension, olap4jLevel.olap4jHierarchy, olap4jLevel); } XmlaOlap4jHierarchy getHierarchy(Element row) { if (olap4jHierarchy != null) { return olap4jHierarchy; } final String hierarchyUniqueName = stringElement(row, "HIERARCHY_UNIQUE_NAME"); XmlaOlap4jHierarchy hierarchy = getCube(row).hierarchiesByUname.get(hierarchyUniqueName); if (hierarchy == null) { // Apparently, the code has requested a member that is // not queried for yet. We must force the initialization // of the dimension tree first. final String dimensionUniqueName = stringElement(row, "DIMENSION_UNIQUE_NAME"); String dimensionName = Olap4jUtil.parseUniqueName(dimensionUniqueName).get(0); XmlaOlap4jDimension dimension = getCube(row).dimensions.get(dimensionName); dimension.getHierarchies().size(); // Now we attempt to resolve again hierarchy = getCube(row).hierarchiesByUname.get(hierarchyUniqueName); } return hierarchy; } XmlaOlap4jCube getCube(Element row) { if (olap4jCube != null) { return olap4jCube; } throw new UnsupportedOperationException(); // todo: } XmlaOlap4jDimension getDimension(Element row) { if (olap4jDimension != null) { return olap4jDimension; } final String dimensionUniqueName = stringElement(row, "DIMENSION_UNIQUE_NAME"); XmlaOlap4jDimension dimension = getCube(row) .dimensionsByUname.get(dimensionUniqueName); // Apparently, the code has requested a member that is // not queried for yet. if (dimension == null) { final String dimensionName = stringElement(row, "DIMENSION_NAME"); return getCube(row).dimensions.get(dimensionName); } return dimension; } public XmlaOlap4jLevel getLevel(Element row) { if (olap4jLevel != null) { return olap4jLevel; } final String levelUniqueName = stringElement(row, "LEVEL_UNIQUE_NAME"); XmlaOlap4jLevel level = getCube(row).levelsByUname.get(levelUniqueName); if (level == null) { // Apparently, the code has requested a member that is // not queried for yet. We must force the initialization // of the dimension tree first. final String dimensionUniqueName = stringElement(row, "DIMENSION_UNIQUE_NAME"); String dimensionName = Olap4jUtil.parseUniqueName(dimensionUniqueName).get(0); XmlaOlap4jDimension dimension = getCube(row).dimensions.get(dimensionName); for (Hierarchy hierarchyInit : dimension.getHierarchies()) { hierarchyInit.getLevels().size(); } // Now we attempt to resolve again level = getCube(row).levelsByUname.get(levelUniqueName); } return level; } public XmlaOlap4jCatalog getCatalog(Element row) throws OlapException { if (olap4jCatalog != null) { return olap4jCatalog; } final String catalogName = stringElement(row, "CATALOG_NAME"); return (XmlaOlap4jCatalog) olap4jConnection.getCatalogs().get( catalogName); } } enum MetadataRequest { DISCOVER_DATASOURCES( new MetadataColumn("DataSourceName"), new MetadataColumn("DataSourceDescription"), new MetadataColumn("URL"), new MetadataColumn("DataSourceInfo"), new MetadataColumn("ProviderName"), new MetadataColumn("ProviderType"), new MetadataColumn("AuthenticationMode")), DISCOVER_SCHEMA_ROWSETS( new MetadataColumn("SchemaName"), new MetadataColumn("SchemaGuid"), new MetadataColumn("Restrictions"), new MetadataColumn("Description")), DISCOVER_ENUMERATORS( new MetadataColumn("EnumName"), new MetadataColumn("EnumDescription"), new MetadataColumn("EnumType"), new MetadataColumn("ElementName"), new MetadataColumn("ElementDescription"), new MetadataColumn("ElementValue")), DISCOVER_PROPERTIES( new MetadataColumn("PropertyName"), new MetadataColumn("PropertyDescription"), new MetadataColumn("PropertyType"), new MetadataColumn("PropertyAccessType"), new MetadataColumn("IsRequired"), new MetadataColumn("Value")), DISCOVER_KEYWORDS( new MetadataColumn("Keyword")), DISCOVER_LITERALS( new MetadataColumn("LiteralName"), new MetadataColumn("LiteralValue"), new MetadataColumn("LiteralInvalidChars"), new MetadataColumn("LiteralInvalidStartingChars"), new MetadataColumn("LiteralMaxLength")), DBSCHEMA_CATALOGS( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("ROLES"), new MetadataColumn("DATE_MODIFIED")), DBSCHEMA_COLUMNS( new MetadataColumn("TABLE_CATALOG"), new MetadataColumn("TABLE_SCHEMA"), new MetadataColumn("TABLE_NAME"), new MetadataColumn("COLUMN_NAME"), new MetadataColumn("ORDINAL_POSITION"), new MetadataColumn("COLUMN_HAS_DEFAULT"), new MetadataColumn("COLUMN_FLAGS"), new MetadataColumn("IS_NULLABLE"), new MetadataColumn("DATA_TYPE"), new MetadataColumn("CHARACTER_MAXIMUM_LENGTH"), new MetadataColumn("CHARACTER_OCTET_LENGTH"), new MetadataColumn("NUMERIC_PRECISION"), new MetadataColumn("NUMERIC_SCALE")), DBSCHEMA_PROVIDER_TYPES( new MetadataColumn("TYPE_NAME"), new MetadataColumn("DATA_TYPE"), new MetadataColumn("COLUMN_SIZE"), new MetadataColumn("LITERAL_PREFIX"), new MetadataColumn("LITERAL_SUFFIX"), new MetadataColumn("IS_NULLABLE"), new MetadataColumn("CASE_SENSITIVE"), new MetadataColumn("SEARCHABLE"), new MetadataColumn("UNSIGNED_ATTRIBUTE"), new MetadataColumn("FIXED_PREC_SCALE"), new MetadataColumn("AUTO_UNIQUE_VALUE"), new MetadataColumn("IS_LONG"), new MetadataColumn("BEST_MATCH")), DBSCHEMA_TABLES( new MetadataColumn("TABLE_CATALOG"), new MetadataColumn("TABLE_SCHEMA"), new MetadataColumn("TABLE_NAME"), new MetadataColumn("TABLE_TYPE"), new MetadataColumn("TABLE_GUID"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("TABLE_PROPID"), new MetadataColumn("DATE_CREATED"), new MetadataColumn("DATE_MODIFIED")), DBSCHEMA_TABLES_INFO( new MetadataColumn("TABLE_CATALOG"), new MetadataColumn("TABLE_SCHEMA"), new MetadataColumn("TABLE_NAME"), new MetadataColumn("TABLE_TYPE"), new MetadataColumn("TABLE_GUID"), new MetadataColumn("BOOKMARKS"), new MetadataColumn("BOOKMARK_TYPE"), new MetadataColumn("BOOKMARK_DATATYPE"), new MetadataColumn("BOOKMARK_MAXIMUM_LENGTH"), new MetadataColumn("BOOKMARK_INFORMATION"), new MetadataColumn("TABLE_VERSION"), new MetadataColumn("CARDINALITY"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("TABLE_PROPID")), DBSCHEMA_SCHEMATA( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("SCHEMA_OWNER")), MDSCHEMA_ACTIONS( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("ACTION_NAME"), new MetadataColumn("COORDINATE"), new MetadataColumn("COORDINATE_TYPE")), MDSCHEMA_CUBES( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("CUBE_TYPE"), new MetadataColumn("CUBE_GUID"), new MetadataColumn("CREATED_ON"), new MetadataColumn("LAST_SCHEMA_UPDATE"), new MetadataColumn("SCHEMA_UPDATED_BY"), new MetadataColumn("LAST_DATA_UPDATE"), new MetadataColumn("DATA_UPDATED_BY"), new MetadataColumn("IS_DRILLTHROUGH_ENABLED"), new MetadataColumn("IS_WRITE_ENABLED"), new MetadataColumn("IS_LINKABLE"), new MetadataColumn("IS_SQL_ENABLED"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("CUBE_CAPTION"), new MetadataColumn("BASE_CUBE_NAME")), MDSCHEMA_DIMENSIONS( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("DIMENSION_NAME"), new MetadataColumn("DIMENSION_UNIQUE_NAME"), new MetadataColumn("DIMENSION_GUID"), new MetadataColumn("DIMENSION_CAPTION"), new MetadataColumn("DIMENSION_ORDINAL"), new MetadataColumn("DIMENSION_TYPE"), new MetadataColumn("DIMENSION_CARDINALITY"), new MetadataColumn("DEFAULT_HIERARCHY"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("IS_VIRTUAL"), new MetadataColumn("IS_READWRITE"), new MetadataColumn("DIMENSION_UNIQUE_SETTINGS"), new MetadataColumn("DIMENSION_MASTER_UNIQUE_NAME"), new MetadataColumn("DIMENSION_IS_VISIBLE")), MDSCHEMA_FUNCTIONS( new MetadataColumn("FUNCTION_NAME"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("PARAMETER_LIST"), new MetadataColumn("RETURN_TYPE"), new MetadataColumn("ORIGIN"), new MetadataColumn("INTERFACE_NAME"), new MetadataColumn("LIBRARY_NAME"), new MetadataColumn("CAPTION")), MDSCHEMA_HIERARCHIES( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("DIMENSION_UNIQUE_NAME"), new MetadataColumn("HIERARCHY_NAME"), new MetadataColumn("HIERARCHY_UNIQUE_NAME"), new MetadataColumn("HIERARCHY_GUID"), new MetadataColumn("HIERARCHY_CAPTION"), new MetadataColumn("DIMENSION_TYPE"), new MetadataColumn("HIERARCHY_CARDINALITY"), new MetadataColumn("DEFAULT_MEMBER"), new MetadataColumn("ALL_MEMBER"), new MetadataColumn("DESCRIPTION"), new MetadataColumn("STRUCTURE"), new MetadataColumn("IS_VIRTUAL"), new MetadataColumn("IS_READWRITE"), new MetadataColumn("DIMENSION_UNIQUE_SETTINGS"), new MetadataColumn("DIMENSION_IS_VISIBLE"), new MetadataColumn("HIERARCHY_ORDINAL"), new MetadataColumn("DIMENSION_IS_SHARED"), new MetadataColumn("PARENT_CHILD")), MDSCHEMA_LEVELS( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("DIMENSION_UNIQUE_NAME"), new MetadataColumn("HIERARCHY_UNIQUE_NAME"), new MetadataColumn("LEVEL_NAME"), new MetadataColumn("LEVEL_UNIQUE_NAME"), new MetadataColumn("LEVEL_GUID"), new MetadataColumn("LEVEL_CAPTION"), new MetadataColumn("LEVEL_NUMBER"), new MetadataColumn("LEVEL_CARDINALITY"), new MetadataColumn("LEVEL_TYPE"), new MetadataColumn("CUSTOM_ROLLUP_SETTINGS"), new MetadataColumn("LEVEL_UNIQUE_SETTINGS"), new MetadataColumn("LEVEL_IS_VISIBLE"), new MetadataColumn("DESCRIPTION")), MDSCHEMA_MEASURES( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("MEASURE_NAME"), new MetadataColumn("MEASURE_UNIQUE_NAME"), new MetadataColumn("MEASURE_CAPTION"), new MetadataColumn("MEASURE_GUID"), new MetadataColumn("MEASURE_AGGREGATOR"), new MetadataColumn("DATA_TYPE"), new MetadataColumn("MEASURE_IS_VISIBLE"), new MetadataColumn("LEVELS_LIST"), new MetadataColumn("DESCRIPTION")), MDSCHEMA_MEMBERS( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("DIMENSION_UNIQUE_NAME"), new MetadataColumn("HIERARCHY_UNIQUE_NAME"), new MetadataColumn("LEVEL_UNIQUE_NAME"), new MetadataColumn("LEVEL_NUMBER"), new MetadataColumn("MEMBER_ORDINAL"), new MetadataColumn("MEMBER_NAME"), new MetadataColumn("MEMBER_UNIQUE_NAME"), new MetadataColumn("MEMBER_TYPE"), new MetadataColumn("MEMBER_GUID"), new MetadataColumn("MEMBER_CAPTION"), new MetadataColumn("CHILDREN_CARDINALITY"), new MetadataColumn("PARENT_LEVEL"), new MetadataColumn("PARENT_UNIQUE_NAME"), new MetadataColumn("PARENT_COUNT"), new MetadataColumn("TREE_OP"), new MetadataColumn("DEPTH")), MDSCHEMA_PROPERTIES( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("DIMENSION_UNIQUE_NAME"), new MetadataColumn("HIERARCHY_UNIQUE_NAME"), new MetadataColumn("LEVEL_UNIQUE_NAME"), new MetadataColumn("MEMBER_UNIQUE_NAME"), new MetadataColumn("PROPERTY_NAME"), new MetadataColumn("PROPERTY_CAPTION"), new MetadataColumn("PROPERTY_TYPE"), new MetadataColumn("DATA_TYPE"), new MetadataColumn("PROPERTY_CONTENT_TYPE"), new MetadataColumn("DESCRIPTION")), MDSCHEMA_SETS( new MetadataColumn("CATALOG_NAME"), new MetadataColumn("SCHEMA_NAME"), new MetadataColumn("CUBE_NAME"), new MetadataColumn("SET_NAME"), new MetadataColumn("SCOPE")); final List<MetadataColumn> columns; final Map<String, MetadataColumn> columnsByName; /** * Creates a MetadataRequest. * * @param columns Columns */ MetadataRequest(MetadataColumn... columns) { if (name().equals("DBSCHEMA_CATALOGS")) { // DatabaseMetaData.getCatalogs() is defined by JDBC not XMLA, // so has just one column. Ignore the 4 columns from XMLA. columns = new MetadataColumn[] { new MetadataColumn("CATALOG_NAME", "TABLE_CAT") }; } else if (name().equals("DBSCHEMA_SCHEMATA")) { // DatabaseMetaData.getCatalogs() is defined by JDBC not XMLA, // so has just one column. Ignore the 4 columns from XMLA. columns = new MetadataColumn[] { new MetadataColumn("SCHEMA_NAME", "TABLE_SCHEM"), new MetadataColumn("CATALOG_NAME", "TABLE_CAT") }; } this.columns = UnmodifiableArrayList.asCopyOf(columns); final Map<String, MetadataColumn> map = new HashMap<String, MetadataColumn>(); for (MetadataColumn column : columns) { map.put(column.name, column); } this.columnsByName = Collections.unmodifiableMap(map); } /** * Returns whether this request requires a * {@code &lt;DatasourceName&gt;} element. * * @return whether this request requires a DatasourceName element */ public boolean requiresDatasourceName() { return this != DISCOVER_DATASOURCES; } /** * Returns whether this request requires a * {@code &lt;CatalogName&gt;} element. * * @return whether this request requires a CatalogName element */ public boolean requiresCatalogName() { // If we don't specifiy CatalogName in the properties of an // MDSCHEMA_FUNCTIONS request, Mondrian's XMLA provider will give // us the whole set of functions multiplied by the number of // catalogs. JDBC (and Mondrian) assumes that functions belong to a // catalog whereas XMLA (and SSAS) assume that functions belong to // the database. Always specifying a catalog is the easiest way to // reconcile them. return this == MDSCHEMA_FUNCTIONS; } /** * Returns whether this request allows a * {@code &lt;CatalogName&gt;} element in the properties section of the * request. Even for requests that allow it, it is usually optional. * * @return whether this request allows a CatalogName element */ public boolean allowsCatalogName() { return true; } /** * Returns the column with a given name, or null if there is no such * column. * * @param name Column name * @return Column, or null if not found */ public MetadataColumn getColumn(String name) { return columnsByName.get(name); } } private static final Pattern LOWERCASE_PATTERN = Pattern.compile(".*[a-z].*"); static class MetadataColumn { final String name; final String xmlaName; MetadataColumn(String xmlaName, String name) { this.xmlaName = xmlaName; this.name = name; } MetadataColumn(String xmlaName) { this.xmlaName = xmlaName; String name = xmlaName; if (LOWERCASE_PATTERN.matcher(name).matches()) { name = Olap4jUtil.camelToUpper(name); } // VALUE is a SQL reserved word if (name.equals("VALUE")) { name = "PROPERTY_VALUE"; } this.name = name; } } private static class XmlaOlap4jMdxValidator implements MdxValidator { private final OlapConnection connection; XmlaOlap4jMdxValidator(OlapConnection connection) { this.connection = connection; } public SelectNode validateSelect( SelectNode selectNode) throws OlapException { StringWriter sw = new StringWriter(); selectNode.unparse(new ParseTreeWriter(sw)); String mdx = sw.toString(); final XmlaOlap4jConnection olap4jConnection = (XmlaOlap4jConnection) connection; return selectNode; } } } // End XmlaOlap4jConnection.java
false
true
public String generateRequest( Context context, MetadataRequest metadataRequest, Object[] restrictions) throws OlapException { final String content = "Data"; final String encoding = proxy.getEncodingCharsetName(); final StringBuilder buf = new StringBuilder( "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n" + "<SOAP-ENV:Envelope\n" + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <SOAP-ENV:Body>\n" + " <Discover xmlns=\"urn:schemas-microsoft-com:xml-analysis\"\n" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <RequestType>"); buf.append(metadataRequest.name()); buf.append( "</RequestType>\n" + " <Restrictions>\n" + " <RestrictionList>\n"); String restrictedCatalogName = null; if (restrictions.length > 0) { if (restrictions.length % 2 != 0) { throw new IllegalArgumentException(); } for (int i = 0; i < restrictions.length; i += 2) { final String restriction = (String) restrictions[i]; final Object o = restrictions[i + 1]; if (o instanceof String) { buf.append("<").append(restriction).append(">"); final String value = (String) o; xmlEncode(buf, value); buf.append("</").append(restriction).append(">"); // To remind ourselves to generate a <Catalog> restriction // if the request supports it. if (restriction.equals("CATALOG_NAME")) { restrictedCatalogName = value; } } else { //noinspection unchecked List<String> valueList = (List<String>) o; for (String value : valueList) { buf.append("<").append(restriction).append(">"); xmlEncode(buf, value); buf.append("</").append(restriction).append(">"); } } } } buf.append( " </RestrictionList>\n" + " </Restrictions>\n" + " <Properties>\n" + " <PropertyList>\n"); // Add the datasource node only if this request requires it. if (metadataRequest.requiresDatasourceName()) { buf.append(" <DataSourceInfo>"); xmlEncode(buf, context.olap4jConnection.getDatabase()); buf.append("</DataSourceInfo>\n"); } String requestCatalogName = null; if (restrictedCatalogName != null && restrictedCatalogName.length() > 0) { requestCatalogName = restrictedCatalogName; } // If the request requires catalog name, and one wasn't specified in the // restrictions, use the connection's current schema. (Note: What XMLA // calls a catalog, JDBC calls a schema.) if (context.olap4jSchema != null) { requestCatalogName = context.olap4jSchema.getName(); } if (requestCatalogName == null && metadataRequest.requiresCatalogName()) { requestCatalogName = context.olap4jConnection.getSchema().getName(); } // Add the catalog node only if this request has specified it as a // restriction. // // For low-level objects like cube, the restriction is optional; you can // specify null to not restrict, "" to match cubes whose catalog name is // empty, or a string (not interpreted as a wild card). (See // OlapDatabaseMetaData.getCubes API doc for more details.) We assume // that the request provides the restriction only if it is valid. // // For high level objects like data source and catalog, the catalog // restriction does not make sense. if (requestCatalogName != null && metadataRequest.allowsCatalogName()) { if (getMetaData().getOlapCatalogs() .get(requestCatalogName) == null) { throw new OlapException( "No catalog named " + requestCatalogName + " exist on the server."); } buf.append(" <Catalog>"); xmlEncode(buf, requestCatalogName); buf.append("</Catalog>\n"); } buf.append(" <Content>"); xmlEncode(buf, content); buf.append( "</Content>\n" + " </PropertyList>\n" + " </Properties>\n" + " </Discover>\n" + "</SOAP-ENV:Body>\n" + "</SOAP-ENV:Envelope>"); return buf.toString(); }
public String generateRequest( Context context, MetadataRequest metadataRequest, Object[] restrictions) throws OlapException { final String content = "Data"; final String encoding = proxy.getEncodingCharsetName(); final StringBuilder buf = new StringBuilder( "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n" + "<SOAP-ENV:Envelope\n" + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <SOAP-ENV:Body>\n" + " <Discover xmlns=\"urn:schemas-microsoft-com:xml-analysis\"\n" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" + " <RequestType>"); buf.append(metadataRequest.name()); buf.append( "</RequestType>\n" + " <Restrictions>\n" + " <RestrictionList>\n"); String restrictedCatalogName = null; if (restrictions.length > 0) { if (restrictions.length % 2 != 0) { throw new IllegalArgumentException(); } for (int i = 0; i < restrictions.length; i += 2) { final String restriction = (String) restrictions[i]; final Object o = restrictions[i + 1]; if (o instanceof String) { buf.append("<").append(restriction).append(">"); final String value = (String) o; xmlEncode(buf, value); buf.append("</").append(restriction).append(">"); // To remind ourselves to generate a <Catalog> restriction // if the request supports it. if (restriction.equals("CATALOG_NAME")) { restrictedCatalogName = value; } } else { //noinspection unchecked List<String> valueList = (List<String>) o; for (String value : valueList) { buf.append("<").append(restriction).append(">"); xmlEncode(buf, value); buf.append("</").append(restriction).append(">"); } } } } buf.append( " </RestrictionList>\n" + " </Restrictions>\n" + " <Properties>\n" + " <PropertyList>\n"); // Add the datasource node only if this request requires it. if (metadataRequest.requiresDatasourceName()) { buf.append(" <DataSourceInfo>"); xmlEncode(buf, context.olap4jConnection.getDatabase()); buf.append("</DataSourceInfo>\n"); } String requestCatalogName = null; if (restrictedCatalogName != null && restrictedCatalogName.length() > 0) { requestCatalogName = restrictedCatalogName; } // If the request requires catalog name, and one wasn't specified in the // restrictions, use the connection's current catalog. if (context.olap4jCatalog != null) { requestCatalogName = context.olap4jCatalog.getName(); } if (requestCatalogName == null && metadataRequest.requiresCatalogName()) { List<Catalog> catalogs = context.olap4jConnection.getMetaData().getOlapCatalogs(); if (catalogs.size() > 0) { requestCatalogName = catalogs.get(0).getName(); } } // Add the catalog node only if this request has specified it as a // restriction. // // For low-level objects like cube, the restriction is optional; you can // specify null to not restrict, "" to match cubes whose catalog name is // empty, or a string (not interpreted as a wild card). (See // OlapDatabaseMetaData.getCubes API doc for more details.) We assume // that the request provides the restriction only if it is valid. // // For high level objects like data source and catalog, the catalog // restriction does not make sense. if (requestCatalogName != null && metadataRequest.allowsCatalogName()) { if (getMetaData().getOlapCatalogs() .get(requestCatalogName) == null) { throw new OlapException( "No catalog named " + requestCatalogName + " exist on the server."); } buf.append(" <Catalog>"); xmlEncode(buf, requestCatalogName); buf.append("</Catalog>\n"); } buf.append(" <Content>"); xmlEncode(buf, content); buf.append( "</Content>\n" + " </PropertyList>\n" + " </Properties>\n" + " </Discover>\n" + "</SOAP-ENV:Body>\n" + "</SOAP-ENV:Envelope>"); return buf.toString(); }
diff --git a/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java b/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java index 9062786..6947bce 100644 --- a/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java +++ b/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java @@ -1,85 +1,85 @@ package me.heldplayer.ModeratorGui; import java.text.SimpleDateFormat; import me.heldplayer.ModeratorGui.tables.*; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class ReviewCommand implements CommandExecutor { private final ModeratorGui main; private final SimpleDateFormat dateFormat; public ReviewCommand(ModeratorGui plugin) { main = plugin; dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } @Override public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { if (args.length <= 0) { int rowCount = main.getDatabase().find(Lists.class).findRowCount(); - String[] results = new String[12]; + String[] results = new String[Math.min(2, Math.min(10, rowCount + 2))]; results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.RED + "Promote " + ChatColor.GREEN + "Demote"; - results[1] = ChatColor.GRAY + "Current time: " + dateFormat.format(Long.valueOf(System.currentTimeMillis())) + ChatColor.ITALIC + "All times are MM-dd-yyyy HH:mm:ss"; + results[1] = ChatColor.GRAY + "Current time: " + dateFormat.format(Long.valueOf(System.currentTimeMillis())) + ChatColor.ITALIC + " All times are MM-dd-yyyy HH:mm:ss"; int sideI = 2; for (int i = rowCount; i > Math.max(rowCount - 10, rowCount); i--) { Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique(); if (list == null) { continue; } int id = list.getReportId(); ReportType type = ReportType.getType(list.getType()); switch (type) { case ISSUE: Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + issue.getIssue(); break; case BAN: Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + ban.getBanned() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + ban.getReason(); break; case UNBAN: Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + unban.getUnbanned() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + unban.getReason(); break; case PROMOTE: Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + promote.getPromoted() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + promote.getReason(); break; case DEMOTE: Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + demote.getDemoted() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + demote.getReason(); break; default: results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened"; break; } sideI++; } sender.sendMessage(results); return true; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { if (args.length <= 0) { int rowCount = main.getDatabase().find(Lists.class).findRowCount(); String[] results = new String[12]; results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.RED + "Promote " + ChatColor.GREEN + "Demote"; results[1] = ChatColor.GRAY + "Current time: " + dateFormat.format(Long.valueOf(System.currentTimeMillis())) + ChatColor.ITALIC + "All times are MM-dd-yyyy HH:mm:ss"; int sideI = 2; for (int i = rowCount; i > Math.max(rowCount - 10, rowCount); i--) { Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique(); if (list == null) { continue; } int id = list.getReportId(); ReportType type = ReportType.getType(list.getType()); switch (type) { case ISSUE: Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + issue.getIssue(); break; case BAN: Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + ban.getBanned() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + ban.getReason(); break; case UNBAN: Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + unban.getUnbanned() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + unban.getReason(); break; case PROMOTE: Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + promote.getPromoted() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + promote.getReason(); break; case DEMOTE: Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + demote.getDemoted() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + demote.getReason(); break; default: results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened"; break; } sideI++; } sender.sendMessage(results); return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { if (args.length <= 0) { int rowCount = main.getDatabase().find(Lists.class).findRowCount(); String[] results = new String[Math.min(2, Math.min(10, rowCount + 2))]; results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.RED + "Promote " + ChatColor.GREEN + "Demote"; results[1] = ChatColor.GRAY + "Current time: " + dateFormat.format(Long.valueOf(System.currentTimeMillis())) + ChatColor.ITALIC + " All times are MM-dd-yyyy HH:mm:ss"; int sideI = 2; for (int i = rowCount; i > Math.max(rowCount - 10, rowCount); i--) { Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique(); if (list == null) { continue; } int id = list.getReportId(); ReportType type = ReportType.getType(list.getType()); switch (type) { case ISSUE: Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + issue.getIssue(); break; case BAN: Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + ban.getBanned() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + ban.getReason(); break; case UNBAN: Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + unban.getUnbanned() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + unban.getReason(); break; case PROMOTE: Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + promote.getPromoted() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + promote.getReason(); break; case DEMOTE: Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique(); results[sideI] = ChatColor.AQUA + demote.getDemoted() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.YELLOW + " at " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.YELLOW + ": " + ChatColor.AQUA + demote.getReason(); break; default: results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened"; break; } sideI++; } sender.sendMessage(results); return true; } return false; }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java index 0972ccc29..ab46cfd89 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java +++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java @@ -1,319 +1,323 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.core.axis2; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.soap.SOAPFactory; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.addressing.AddressingConstants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.OperationClient; import org.apache.axis2.client.Options; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceContext; import org.apache.axis2.context.ServiceGroupContext; import org.apache.axis2.description.AxisOperation; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.description.WSDL2Constants; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.SynapseConstants; import org.apache.synapse.endpoints.EndpointDefinition; import org.apache.synapse.util.MessageHelper; import javax.xml.namespace.QName; /** * This is a simple client that handles both in only and in out */ public class Axis2FlexibleMEPClient { private static final Log log = LogFactory.getLog(Axis2FlexibleMEPClient.class); /** * Based on the Axis2 client code. Sends the Axis2 Message context out and returns * the Axis2 message context for the response. * * Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and * 500 internal server error as possible responses. * * @param endpoint the endpoint being sent to, maybe null * @param synapseOutMessageContext the outgoing synapse message * @throws AxisFault on errors */ public static void send( EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault { boolean separateListener = false; boolean wsSecurityEnabled = false; String wsSecPolicyKey = null; String inboundWsSecPolicyKey = null; String outboundWsSecPolicyKey = null; boolean wsRMEnabled = false; String wsRMPolicyKey = null; boolean wsAddressingEnabled = false; String wsAddressingVersion = null; if (endpoint != null) { separateListener = endpoint.isUseSeparateListener(); wsSecurityEnabled = endpoint.isSecurityOn(); wsSecPolicyKey = endpoint.getWsSecPolicyKey(); inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey(); outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey(); wsRMEnabled = endpoint.isReliableMessagingOn(); wsRMPolicyKey = endpoint.getWsRMPolicyKey(); wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled; wsAddressingVersion = endpoint.getAddressingVersion(); } if (log.isDebugEnabled()) { log.debug( "Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + "] [rm = " + wsRMEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to " + synapseOutMessageContext.getTo() + "]"); } // save the original message context wihout altering it, so we can tie the response MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext(); // create a new MessageContext to be sent out as this should not corrupt the original // we need to create the response to the original message later on MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx); if (log.isDebugEnabled()) { log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]"); } // set all the details of the endpoint only to the cloned message context // so that we can use the original message context for resending through different endpoints if (endpoint != null) { if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); + axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, + org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); + axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, + org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(!axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx); } } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx); } } if (endpoint.isUseMTOM()) { axisOutMsgCtx.setDoingMTOM(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingMTOM(true); } else if (endpoint.isUseSwa()) { axisOutMsgCtx.setDoingSwA(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingSwA(true); } if (endpoint.getCharSetEncoding() != null) { axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding()); } if (endpoint.getAddress() != null) { axisOutMsgCtx.setTo(new EndpointReference(endpoint.getAddress())); } if (endpoint.isUseSeparateListener()) { axisOutMsgCtx.getOptions().setUseSeparateListener(true); } } if (wsAddressingEnabled) { if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE); } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE); } axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE); } else { axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); } ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext(); AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration(); AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled); ServiceGroupContext sgc = new ServiceGroupContext( axisCfgCtx, (AxisServiceGroup) anoymousService.getParent()); ServiceContext serviceCtx = sgc.getServiceContext(anoymousService); boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty( SynapseConstants.OUT_ONLY)) || WSDL2Constants.MEP_URI_IN_ONLY.equals( originalInMsgCtx.getOperationContext() .getAxisOperation().getMessageExchangePattern()); // get a reference to the DYNAMIC operation of the Anonymous Axis2 service AxisOperation axisAnonymousOperation = anoymousService.getOperation( outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION)); Options clientOptions = new Options(); clientOptions.setUseSeparateListener(separateListener); // if RM is requested, if (wsRMEnabled) { // if a WS-RM policy is specified, use it if (wsRMPolicyKey != null) { clientOptions.setProperty( SynapseConstants.SANDESHA_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsRMPolicyKey)); } MessageHelper.copyRMOptions(originalInMsgCtx, clientOptions); } // if security is enabled, if (wsSecurityEnabled) { // if a WS-Sec policy is specified, use it if (wsSecPolicyKey != null) { clientOptions.setProperty( SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey)); } else { if (inboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, inboundWsSecPolicyKey)); } if (outboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, outboundWsSecPolicyKey)); } } // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197 if (axisOutMsgCtx.getEnvelope().getHeader() == null) { SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory(); fac.createSOAPHeader(axisOutMsgCtx.getEnvelope()); } } OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions); mepClient.addMessageContext(axisOutMsgCtx); axisOutMsgCtx.setAxisMessage( axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set the SEND_TIMEOUT for transport sender if (endpoint != null && endpoint.getTimeoutDuration() > 0) { axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration()); } if (!outOnlyMessage) { // always set a callback as we decide if the send it blocking or non blocking within // the MEP client. This does not cause an overhead, as we simply create a 'holder' // object with a reference to the outgoing synapse message context // synapseOutMessageContext AsyncCallback callback = new AsyncCallback(synapseOutMessageContext); if (endpoint != null) { // set the timeout time and the timeout action to the callback, so that the // TimeoutHandler can detect timed out callbacks and take approprite action. callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration()); callback.setTimeOutAction(endpoint.getTimeoutAction()); } else { callback.setTimeOutOn(System.currentTimeMillis()); } mepClient.setCallback(callback); } // with the nio transport, this causes the listener not to write a 202 // Accepted response, as this implies that Synapse does not yet know if // a 202 or 200 response would be written back. originalInMsgCtx.getOperationContext().setProperty( org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP"); mepClient.execute(true); } private static MessageContext cloneForSend(MessageContext ori) throws AxisFault { MessageContext newMC = MessageHelper.clonePartially(ori); newMC.setEnvelope(ori.getEnvelope()); MessageHelper.removeAddressingHeaders(newMC); newMC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, ori.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)); return newMC; } }
false
true
public static void send( EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault { boolean separateListener = false; boolean wsSecurityEnabled = false; String wsSecPolicyKey = null; String inboundWsSecPolicyKey = null; String outboundWsSecPolicyKey = null; boolean wsRMEnabled = false; String wsRMPolicyKey = null; boolean wsAddressingEnabled = false; String wsAddressingVersion = null; if (endpoint != null) { separateListener = endpoint.isUseSeparateListener(); wsSecurityEnabled = endpoint.isSecurityOn(); wsSecPolicyKey = endpoint.getWsSecPolicyKey(); inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey(); outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey(); wsRMEnabled = endpoint.isReliableMessagingOn(); wsRMPolicyKey = endpoint.getWsRMPolicyKey(); wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled; wsAddressingVersion = endpoint.getAddressingVersion(); } if (log.isDebugEnabled()) { log.debug( "Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + "] [rm = " + wsRMEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to " + synapseOutMessageContext.getTo() + "]"); } // save the original message context wihout altering it, so we can tie the response MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext(); // create a new MessageContext to be sent out as this should not corrupt the original // we need to create the response to the original message later on MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx); if (log.isDebugEnabled()) { log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]"); } // set all the details of the endpoint only to the cloned message context // so that we can use the original message context for resending through different endpoints if (endpoint != null) { if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(!axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx); } } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx); } } if (endpoint.isUseMTOM()) { axisOutMsgCtx.setDoingMTOM(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingMTOM(true); } else if (endpoint.isUseSwa()) { axisOutMsgCtx.setDoingSwA(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingSwA(true); } if (endpoint.getCharSetEncoding() != null) { axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding()); } if (endpoint.getAddress() != null) { axisOutMsgCtx.setTo(new EndpointReference(endpoint.getAddress())); } if (endpoint.isUseSeparateListener()) { axisOutMsgCtx.getOptions().setUseSeparateListener(true); } } if (wsAddressingEnabled) { if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE); } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE); } axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE); } else { axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); } ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext(); AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration(); AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled); ServiceGroupContext sgc = new ServiceGroupContext( axisCfgCtx, (AxisServiceGroup) anoymousService.getParent()); ServiceContext serviceCtx = sgc.getServiceContext(anoymousService); boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty( SynapseConstants.OUT_ONLY)) || WSDL2Constants.MEP_URI_IN_ONLY.equals( originalInMsgCtx.getOperationContext() .getAxisOperation().getMessageExchangePattern()); // get a reference to the DYNAMIC operation of the Anonymous Axis2 service AxisOperation axisAnonymousOperation = anoymousService.getOperation( outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION)); Options clientOptions = new Options(); clientOptions.setUseSeparateListener(separateListener); // if RM is requested, if (wsRMEnabled) { // if a WS-RM policy is specified, use it if (wsRMPolicyKey != null) { clientOptions.setProperty( SynapseConstants.SANDESHA_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsRMPolicyKey)); } MessageHelper.copyRMOptions(originalInMsgCtx, clientOptions); } // if security is enabled, if (wsSecurityEnabled) { // if a WS-Sec policy is specified, use it if (wsSecPolicyKey != null) { clientOptions.setProperty( SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey)); } else { if (inboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, inboundWsSecPolicyKey)); } if (outboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, outboundWsSecPolicyKey)); } } // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197 if (axisOutMsgCtx.getEnvelope().getHeader() == null) { SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory(); fac.createSOAPHeader(axisOutMsgCtx.getEnvelope()); } } OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions); mepClient.addMessageContext(axisOutMsgCtx); axisOutMsgCtx.setAxisMessage( axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set the SEND_TIMEOUT for transport sender if (endpoint != null && endpoint.getTimeoutDuration() > 0) { axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration()); } if (!outOnlyMessage) { // always set a callback as we decide if the send it blocking or non blocking within // the MEP client. This does not cause an overhead, as we simply create a 'holder' // object with a reference to the outgoing synapse message context // synapseOutMessageContext AsyncCallback callback = new AsyncCallback(synapseOutMessageContext); if (endpoint != null) { // set the timeout time and the timeout action to the callback, so that the // TimeoutHandler can detect timed out callbacks and take approprite action. callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration()); callback.setTimeOutAction(endpoint.getTimeoutAction()); } else { callback.setTimeOutOn(System.currentTimeMillis()); } mepClient.setCallback(callback); } // with the nio transport, this causes the listener not to write a 202 // Accepted response, as this implies that Synapse does not yet know if // a 202 or 200 response would be written back. originalInMsgCtx.getOperationContext().setProperty( org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP"); mepClient.execute(true); }
public static void send( EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault { boolean separateListener = false; boolean wsSecurityEnabled = false; String wsSecPolicyKey = null; String inboundWsSecPolicyKey = null; String outboundWsSecPolicyKey = null; boolean wsRMEnabled = false; String wsRMPolicyKey = null; boolean wsAddressingEnabled = false; String wsAddressingVersion = null; if (endpoint != null) { separateListener = endpoint.isUseSeparateListener(); wsSecurityEnabled = endpoint.isSecurityOn(); wsSecPolicyKey = endpoint.getWsSecPolicyKey(); inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey(); outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey(); wsRMEnabled = endpoint.isReliableMessagingOn(); wsRMPolicyKey = endpoint.getWsRMPolicyKey(); wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled; wsAddressingVersion = endpoint.getAddressingVersion(); } if (log.isDebugEnabled()) { log.debug( "Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + "] [rm = " + wsRMEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to " + synapseOutMessageContext.getTo() + "]"); } // save the original message context wihout altering it, so we can tie the response MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext(); // create a new MessageContext to be sent out as this should not corrupt the original // we need to create the response to the original message later on MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx); if (log.isDebugEnabled()) { log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]"); } // set all the details of the endpoint only to the cloned message context // so that we can use the original message context for resending through different endpoints if (endpoint != null) { if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(!axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx); } } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx); } } if (endpoint.isUseMTOM()) { axisOutMsgCtx.setDoingMTOM(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingMTOM(true); } else if (endpoint.isUseSwa()) { axisOutMsgCtx.setDoingSwA(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingSwA(true); } if (endpoint.getCharSetEncoding() != null) { axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding()); } if (endpoint.getAddress() != null) { axisOutMsgCtx.setTo(new EndpointReference(endpoint.getAddress())); } if (endpoint.isUseSeparateListener()) { axisOutMsgCtx.getOptions().setUseSeparateListener(true); } } if (wsAddressingEnabled) { if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE); } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE); } axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE); } else { axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); } ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext(); AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration(); AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled); ServiceGroupContext sgc = new ServiceGroupContext( axisCfgCtx, (AxisServiceGroup) anoymousService.getParent()); ServiceContext serviceCtx = sgc.getServiceContext(anoymousService); boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty( SynapseConstants.OUT_ONLY)) || WSDL2Constants.MEP_URI_IN_ONLY.equals( originalInMsgCtx.getOperationContext() .getAxisOperation().getMessageExchangePattern()); // get a reference to the DYNAMIC operation of the Anonymous Axis2 service AxisOperation axisAnonymousOperation = anoymousService.getOperation( outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION)); Options clientOptions = new Options(); clientOptions.setUseSeparateListener(separateListener); // if RM is requested, if (wsRMEnabled) { // if a WS-RM policy is specified, use it if (wsRMPolicyKey != null) { clientOptions.setProperty( SynapseConstants.SANDESHA_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsRMPolicyKey)); } MessageHelper.copyRMOptions(originalInMsgCtx, clientOptions); } // if security is enabled, if (wsSecurityEnabled) { // if a WS-Sec policy is specified, use it if (wsSecPolicyKey != null) { clientOptions.setProperty( SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey)); } else { if (inboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, inboundWsSecPolicyKey)); } if (outboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, outboundWsSecPolicyKey)); } } // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197 if (axisOutMsgCtx.getEnvelope().getHeader() == null) { SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory(); fac.createSOAPHeader(axisOutMsgCtx.getEnvelope()); } } OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions); mepClient.addMessageContext(axisOutMsgCtx); axisOutMsgCtx.setAxisMessage( axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set the SEND_TIMEOUT for transport sender if (endpoint != null && endpoint.getTimeoutDuration() > 0) { axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration()); } if (!outOnlyMessage) { // always set a callback as we decide if the send it blocking or non blocking within // the MEP client. This does not cause an overhead, as we simply create a 'holder' // object with a reference to the outgoing synapse message context // synapseOutMessageContext AsyncCallback callback = new AsyncCallback(synapseOutMessageContext); if (endpoint != null) { // set the timeout time and the timeout action to the callback, so that the // TimeoutHandler can detect timed out callbacks and take approprite action. callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration()); callback.setTimeOutAction(endpoint.getTimeoutAction()); } else { callback.setTimeOutOn(System.currentTimeMillis()); } mepClient.setCallback(callback); } // with the nio transport, this causes the listener not to write a 202 // Accepted response, as this implies that Synapse does not yet know if // a 202 or 200 response would be written back. originalInMsgCtx.getOperationContext().setProperty( org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP"); mepClient.execute(true); }
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/SummaryProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/SummaryProducer.java index 3fe3471f..fc7eecbd 100644 --- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/SummaryProducer.java +++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/SummaryProducer.java @@ -1,459 +1,460 @@ /****************************************************************************** * SummaryProducer.java - created by [email protected] on Nov 10, 2006 * * Copyright (c) 2007 Virginia Polytechnic Institute and State University * Licensed under the Educational Community License version 1.0 * * A copy of the Educational Community License has been included in this * distribution and is available at: http://www.opensource.org/licenses/ecl1.php * * Contributors: * Aaron Zeckoski ([email protected]) - primary * *****************************************************************************/ package org.sakaiproject.evaluation.tool.producers; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.sakaiproject.evaluation.beans.EvalBeanUtils; import org.sakaiproject.evaluation.constant.EvalConstants; import org.sakaiproject.evaluation.logic.EvalAuthoringService; import org.sakaiproject.evaluation.logic.EvalDeliveryService; import org.sakaiproject.evaluation.logic.EvalEvaluationService; import org.sakaiproject.evaluation.logic.EvalEvaluationSetupService; import org.sakaiproject.evaluation.logic.EvalSettings; import org.sakaiproject.evaluation.logic.externals.EvalExternalLogic; import org.sakaiproject.evaluation.logic.model.EvalGroup; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.EvalResponse; import org.sakaiproject.evaluation.tool.viewparams.EvalTakeViewParameters; import org.sakaiproject.evaluation.tool.viewparams.PreviewEvalParameters; import org.sakaiproject.evaluation.tool.viewparams.ReportParameters; import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIELBinding; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.decorators.UITooltipDecorator; import uk.org.ponder.rsf.flow.jsfnav.NavigationCase; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.DefaultView; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; /** * The summary producer rewrite * This creates a summary page for any user of the evaluation system and is the * starting page for anyone entering the system * * @author Aaron Zeckoski ([email protected]) */ public class SummaryProducer implements ViewComponentProducer, DefaultView, NavigationCaseReporter { private final int maxGroupsToDisplay = 5; public static final String VIEW_ID = "summary"; public String getViewID() { return VIEW_ID; } private EvalExternalLogic externalLogic; public void setExternalLogic(EvalExternalLogic externalLogic) { this.externalLogic = externalLogic; } private EvalAuthoringService authoringService; public void setAuthoringService(EvalAuthoringService authoringService) { this.authoringService = authoringService; } private EvalEvaluationService evaluationService; public void setEvaluationService(EvalEvaluationService evaluationService) { this.evaluationService = evaluationService; } private EvalEvaluationSetupService evaluationSetupService; public void setEvaluationSetupService(EvalEvaluationSetupService evaluationSetupService) { this.evaluationSetupService = evaluationSetupService; } private EvalDeliveryService deliveryService; public void setDeliveryService(EvalDeliveryService deliveryService) { this.deliveryService = deliveryService; } private EvalSettings settings; public void setSettings(EvalSettings settings) { this.settings = settings; } private EvalBeanUtils evalBeanUtils; public void setEvalBeanUtils(EvalBeanUtils evalBeanUtils) { this.evalBeanUtils = evalBeanUtils; } private Locale locale; public void setLocale(Locale locale) { this.locale = locale; } /* (non-Javadoc) * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker) */ public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = externalLogic.getCurrentUserId(); String currentGroup = externalLogic.getCurrentEvalGroup(); boolean userAdmin = externalLogic.isUserAdmin(currentUserId); boolean createTemplate = authoringService.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId); // use a date which is related to the current users locale DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-scales-link", UIMessage.make("controlscales.page.title"), new SimpleViewParameters(ControlScalesProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-items-link", UIMessage.make("controlitems.page.title"), new SimpleViewParameters(ControlItemsProducer.VIEW_ID)); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); UIMessage.make(tofill, "instructor-instructions", "summary.instructor.instruction"); } /* * Notification box listing box */ boolean userHasNotifications = false; if (userHasNotifications) { UIBranchContainer notificationsBC = UIBranchContainer.make(tofill, "notificationsBox:"); UIMessage.make(notificationsBC, "notifications-title","summary.notifications.title"); UIMessage.make(notificationsBC, "notifications-higher-level", "summary.eval.assigned.from.above"); // add other stuff } /* * for the evaluationSetupService taking box */ List<EvalEvaluation> evalsToTake = evaluationSetupService.getEvaluationsForUser(currentUserId, true, false); UIBranchContainer evalBC = UIBranchContainer.make(tofill, "evaluationsBox:"); if (evalsToTake.size() > 0) { // build an array of evaluation ids Long[] evalIds = new Long[evalsToTake.size()]; for (int i=0; i<evalsToTake.size(); i++) { evalIds[i] = ((EvalEvaluation) evalsToTake.get(i)).getId(); } // now fetch all the information we care about for these evaluationSetupService at once (for speed) Map<Long, List<EvalGroup>> evalGroups = evaluationService.getEvaluationGroups(evalIds, false); List<EvalResponse> evalResponses = deliveryService.getEvaluationResponses(currentUserId, evalIds, true); for (Iterator<EvalEvaluation> itEvals = evalsToTake.iterator(); itEvals.hasNext();) { EvalEvaluation eval = (EvalEvaluation) itEvals.next(); UIBranchContainer evalrow = UIBranchContainer.make(evalBC, "evaluationsList:", eval.getId().toString() ); UIOutput.make(evalrow, "evaluationTitleTitle", eval.getTitle() ); UIMessage.make(evalrow, "evaluationCourseEvalTitle", "summary.evaluations.courseeval.title" ); UIMessage.make(evalrow, "evaluationStartsTitle", "summary.evaluations.starts.title" ); UIMessage.make(evalrow, "evaluationEndsTitle", "summary.evaluations.ends.title" ); List<EvalGroup> groups = evalGroups.get(eval.getId()); for (int j=0; j<groups.size(); j++) { EvalGroup group = (EvalGroup) groups.get(j); if (EvalConstants.GROUP_TYPE_INVALID.equals(group.type)) { continue; // skip processing for invalid groups } //check that the user can take evaluationSetupService in this evalGroupId if (externalLogic.isUserAllowedInEvalGroup(currentUserId, EvalConstants.PERM_TAKE_EVALUATION, group.evalGroupId)) { String groupId = group.evalGroupId; String title = group.title; String status = "unknown.caps"; // find the object in the list matching the evalGroupId and evalId, // leave as null if not found -AZ EvalResponse response = null; for (int k=0; k<evalResponses.size(); k++) { EvalResponse er = (EvalResponse) evalResponses.get(k); if (groupId.equals(er.getEvalGroupId()) && eval.getId().equals(er.getEvaluation().getId())) { response = er; break; } } if (groupId.equals(currentGroup)) { // TODO - do something when the evalGroupId matches } UIBranchContainer evalcourserow = UIBranchContainer.make(evalrow, "evaluationsCourseList:", groupId ); // set status if (response != null && response.getEndTime() != null) { // there is a response for this eval/group if (eval.getModifyResponsesAllowed().booleanValue()) { // can modify responses so show the link still // take eval link when pending UIInternalLink.make(evalcourserow, "evaluationCourseLink", title, new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, eval.getId(), groupId, response.getId()) ); status = "summary.status.completed"; } else { // show title only when completed UIOutput.make(evalcourserow, "evaluationCourseTitle", title); status = "summary.status.completed"; } } else { // no response yet for this eval/group // take eval link when pending UIInternalLink.make(evalcourserow, "evaluationCourseLink", title, new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, eval.getId(), groupId) ); status = "summary.status.pending"; } UIMessage.make(evalcourserow, "evaluationCourseStatus", status ); // moved down here as requested by UI design UIOutput.make(evalcourserow, "evaluationStartDate", df.format(eval.getStartDate()) ); UIOutput.make(evalcourserow, "evaluationDueDate", df.format(eval.getDueDate()) ); } } } } else { UIMessage.make(tofill, "evaluationsNone", "summary.evaluations.none"); } /* * for the evaluations admin box */ Boolean instViewResults = (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); + if (instViewResults == null) { instViewResults = true; } // if configurable then we will assume some are probably shared List<EvalEvaluation> evals = evaluationSetupService.getVisibleEvaluationsForUser(currentUserId, true, instViewResults); /* * If the person is an admin, then just point new evals to existing object. * If the person is not an admin then only show owned evals + * not-owned evals that are available for viewing results. */ List<EvalEvaluation> newEvals; if (userAdmin) { newEvals = evals; } else { newEvals = new ArrayList<EvalEvaluation>(); int numEvals = evals.size(); Date currentDate = new Date(); for (int count = 0; count < numEvals; count++) { EvalEvaluation evaluation = (EvalEvaluation) evals.get(count); // Add the owned evals if (currentUserId.equals(evaluation.getOwner())) { newEvals.add(evaluation); } else { // From the not-owned evals show those // that are available for viewing results. if (currentDate.before(evaluation.getViewDate())) { // Do nothing } else { newEvals.add(evaluation); } } } } if (! newEvals.isEmpty()) { UIBranchContainer evalAdminBC = UIBranchContainer.make(tofill, "evalAdminBox:"); // Temporary fix for http://www.caret.cam.ac.uk/jira/browse/CTL-583 (need to send them to the eval control page eventually) -AZ if (beginEvaluation) { UIInternalLink.make(evalAdminBC, "evaladmin-title-link", UIMessage.make("summary.evaluations.admin"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID) ); } else { UIMessage.make(evalAdminBC, "evaladmin-title", "summary.evaluations.admin"); } UIForm evalAdminForm = UIForm.make(evalAdminBC , "evalAdminForm"); UIMessage.make(evalAdminForm, "evaladmin-header-title","summary.header.title"); UIMessage.make(evalAdminForm, "evaladmin-header-status", "summary.header.status"); UIMessage.make(evalAdminForm, "evaladmin-header-date", "summary.header.date"); for (Iterator<EvalEvaluation> iter = newEvals.iterator(); iter.hasNext();) { EvalEvaluation eval = (EvalEvaluation) iter.next(); UIBranchContainer evalrow = UIBranchContainer.make(evalAdminForm, "evalAdminList:", eval.getId().toString() ); Date date; String evalStatus = evaluationService.updateEvaluationState(eval.getId()); if (EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus)) { date = eval.getStartDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(evalStatus)) { date = eval.getStopDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_DUE.equals(evalStatus)) { date = eval.getDueDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus)) { date = eval.getViewDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { date = eval.getViewDate(); int responsesCount = deliveryService.countResponses(eval.getId(), null, true); int enrollmentsCount = evaluationService.countParticipantsForEval(eval.getId()); int responsesNeeded = evalBeanUtils.getResponsesNeededToViewForResponseRate(responsesCount, enrollmentsCount); if ( responsesNeeded == 0 ) { UIInternalLink.make(evalrow, "viewReportLink", UIMessage.make("viewreport.page.title"), new ReportParameters(ReportChooseGroupsProducer.VIEW_ID, eval.getId())); } else { UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus) .decorate( new UITooltipDecorator( UIMessage.make("controlevaluations.eval.report.awaiting.responses", new Object[] { responsesNeeded }) ) ); } } else { date = eval.getStartDate(); } /* * 1) if a evaluation is queued, title link go to EditSettings page with populated data * 2) if a evaluation is active, title link go to EditSettings page with populated data * but start date should be disabled * 3) if a evaluation is closed, title link go to previewEval page with populated data */ if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) || EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { UIInternalLink.make(evalrow, "evalAdminTitleLink_preview", eval.getTitle(), new PreviewEvalParameters(PreviewEvalProducer.VIEW_ID, eval.getId(), eval.getTemplate().getId())); } else { UICommand evalEditUIC = UICommand.make(evalrow, "evalAdminTitleLink_edit", eval.getTitle(), "#{evaluationBean.editEvalSettingAction}"); evalEditUIC.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", eval.getId())); } UIMessage.make(evalrow, "evalAdminDateLabel", "summary.label." + evalStatus); UIOutput.make(evalrow, "evalAdminDate", df.format(date)); } } /* * Site/Group listing box */ Boolean enableSitesBox = (Boolean) settings.get(EvalSettings.ENABLE_SUMMARY_SITES_BOX); if (enableSitesBox) { // only show this if we cannot find our location OR if the option is forced to on String NO_ITEMS = "no.list.items"; UIBranchContainer contextsBC = UIBranchContainer.make(tofill, "siteListingBox:"); UIMessage.make(contextsBC, "sitelisting-title", "summary.sitelisting.title"); UIMessage.make(contextsBC, "sitelisting-evaluated-text", "summary.sitelisting.evaluated"); List<EvalGroup> evaluatedContexts = externalLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_BE_EVALUATED); if (evaluatedContexts.size() > 0) { for (int i=0; i<evaluatedContexts.size(); i++) { if (i > maxGroupsToDisplay) { UIMessage.make(contextsBC, "evaluatedListNone", "summary.sitelisting.maxshown", new Object[] { new Integer(evaluatedContexts.size() - maxGroupsToDisplay) }); break; } UIBranchContainer evaluatedBC = UIBranchContainer.make(contextsBC, "evaluatedList:", i+""); EvalGroup c = (EvalGroup) evaluatedContexts.get(i); UIOutput.make(evaluatedBC, "evaluatedListTitle", c.title); } } else { UIMessage.make(contextsBC, "evaluatedListNone", NO_ITEMS ); } UIMessage.make(contextsBC, "sitelisting-evaluate-text", "summary.sitelisting.evaluate"); List<EvalGroup> evaluateContexts = externalLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_TAKE_EVALUATION); if (evaluateContexts.size() > 0) { for (int i=0; i<evaluateContexts.size(); i++) { if (i > maxGroupsToDisplay) { UIMessage.make(contextsBC, "evaluateListNone", "summary.sitelisting.maxshown", new Object[] { new Integer(evaluateContexts.size() - maxGroupsToDisplay) }); break; } UIBranchContainer evaluateBC = UIBranchContainer.make(contextsBC, "evaluateList:", i+""); EvalGroup c = (EvalGroup) evaluateContexts.get(i); UIOutput.make(evaluateBC, "evaluateListTitle", c.title); } } else { UIMessage.make(contextsBC, "evaluateListNone", NO_ITEMS ); } } /* * For the Evaluation tools box */ if (createTemplate || beginEvaluation) { UIBranchContainer toolsBC = UIBranchContainer.make(tofill, "toolsBox:"); UIMessage.make(toolsBC, "tools-title", "summary.tools.title"); if ( createTemplate ) { UIInternalLink.make(toolsBC, "createTemplateLink", UIMessage.make("createtemplate.page.title"), new TemplateViewParameters(ModifyTemplateProducer.VIEW_ID, null)); } if ( beginEvaluation ) { UIInternalLink.make(toolsBC, "beginEvaluationLink", UIMessage.make("starteval.page.title"), new TemplateViewParameters(EvaluationStartProducer.VIEW_ID, null)); } } } /* (non-Javadoc) * @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases() */ @SuppressWarnings("unchecked") public List reportNavigationCases() { List i = new ArrayList(); i.add(new NavigationCase(EvaluationSettingsProducer.VIEW_ID, new SimpleViewParameters( EvaluationSettingsProducer.VIEW_ID))); i.add(new NavigationCase(PreviewEvalProducer.VIEW_ID, new SimpleViewParameters( PreviewEvalProducer.VIEW_ID))); return i; } }
true
true
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = externalLogic.getCurrentUserId(); String currentGroup = externalLogic.getCurrentEvalGroup(); boolean userAdmin = externalLogic.isUserAdmin(currentUserId); boolean createTemplate = authoringService.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId); // use a date which is related to the current users locale DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-scales-link", UIMessage.make("controlscales.page.title"), new SimpleViewParameters(ControlScalesProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-items-link", UIMessage.make("controlitems.page.title"), new SimpleViewParameters(ControlItemsProducer.VIEW_ID)); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); UIMessage.make(tofill, "instructor-instructions", "summary.instructor.instruction"); } /* * Notification box listing box */ boolean userHasNotifications = false; if (userHasNotifications) { UIBranchContainer notificationsBC = UIBranchContainer.make(tofill, "notificationsBox:"); UIMessage.make(notificationsBC, "notifications-title","summary.notifications.title"); UIMessage.make(notificationsBC, "notifications-higher-level", "summary.eval.assigned.from.above"); // add other stuff } /* * for the evaluationSetupService taking box */ List<EvalEvaluation> evalsToTake = evaluationSetupService.getEvaluationsForUser(currentUserId, true, false); UIBranchContainer evalBC = UIBranchContainer.make(tofill, "evaluationsBox:"); if (evalsToTake.size() > 0) { // build an array of evaluation ids Long[] evalIds = new Long[evalsToTake.size()]; for (int i=0; i<evalsToTake.size(); i++) { evalIds[i] = ((EvalEvaluation) evalsToTake.get(i)).getId(); } // now fetch all the information we care about for these evaluationSetupService at once (for speed) Map<Long, List<EvalGroup>> evalGroups = evaluationService.getEvaluationGroups(evalIds, false); List<EvalResponse> evalResponses = deliveryService.getEvaluationResponses(currentUserId, evalIds, true); for (Iterator<EvalEvaluation> itEvals = evalsToTake.iterator(); itEvals.hasNext();) { EvalEvaluation eval = (EvalEvaluation) itEvals.next(); UIBranchContainer evalrow = UIBranchContainer.make(evalBC, "evaluationsList:", eval.getId().toString() ); UIOutput.make(evalrow, "evaluationTitleTitle", eval.getTitle() ); UIMessage.make(evalrow, "evaluationCourseEvalTitle", "summary.evaluations.courseeval.title" ); UIMessage.make(evalrow, "evaluationStartsTitle", "summary.evaluations.starts.title" ); UIMessage.make(evalrow, "evaluationEndsTitle", "summary.evaluations.ends.title" ); List<EvalGroup> groups = evalGroups.get(eval.getId()); for (int j=0; j<groups.size(); j++) { EvalGroup group = (EvalGroup) groups.get(j); if (EvalConstants.GROUP_TYPE_INVALID.equals(group.type)) { continue; // skip processing for invalid groups } //check that the user can take evaluationSetupService in this evalGroupId if (externalLogic.isUserAllowedInEvalGroup(currentUserId, EvalConstants.PERM_TAKE_EVALUATION, group.evalGroupId)) { String groupId = group.evalGroupId; String title = group.title; String status = "unknown.caps"; // find the object in the list matching the evalGroupId and evalId, // leave as null if not found -AZ EvalResponse response = null; for (int k=0; k<evalResponses.size(); k++) { EvalResponse er = (EvalResponse) evalResponses.get(k); if (groupId.equals(er.getEvalGroupId()) && eval.getId().equals(er.getEvaluation().getId())) { response = er; break; } } if (groupId.equals(currentGroup)) { // TODO - do something when the evalGroupId matches } UIBranchContainer evalcourserow = UIBranchContainer.make(evalrow, "evaluationsCourseList:", groupId ); // set status if (response != null && response.getEndTime() != null) { // there is a response for this eval/group if (eval.getModifyResponsesAllowed().booleanValue()) { // can modify responses so show the link still // take eval link when pending UIInternalLink.make(evalcourserow, "evaluationCourseLink", title, new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, eval.getId(), groupId, response.getId()) ); status = "summary.status.completed"; } else { // show title only when completed UIOutput.make(evalcourserow, "evaluationCourseTitle", title); status = "summary.status.completed"; } } else { // no response yet for this eval/group // take eval link when pending UIInternalLink.make(evalcourserow, "evaluationCourseLink", title, new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, eval.getId(), groupId) ); status = "summary.status.pending"; } UIMessage.make(evalcourserow, "evaluationCourseStatus", status ); // moved down here as requested by UI design UIOutput.make(evalcourserow, "evaluationStartDate", df.format(eval.getStartDate()) ); UIOutput.make(evalcourserow, "evaluationDueDate", df.format(eval.getDueDate()) ); } } } } else { UIMessage.make(tofill, "evaluationsNone", "summary.evaluations.none"); } /* * for the evaluations admin box */ Boolean instViewResults = (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); List<EvalEvaluation> evals = evaluationSetupService.getVisibleEvaluationsForUser(currentUserId, true, instViewResults); /* * If the person is an admin, then just point new evals to existing object. * If the person is not an admin then only show owned evals + * not-owned evals that are available for viewing results. */ List<EvalEvaluation> newEvals; if (userAdmin) { newEvals = evals; } else { newEvals = new ArrayList<EvalEvaluation>(); int numEvals = evals.size(); Date currentDate = new Date(); for (int count = 0; count < numEvals; count++) { EvalEvaluation evaluation = (EvalEvaluation) evals.get(count); // Add the owned evals if (currentUserId.equals(evaluation.getOwner())) { newEvals.add(evaluation); } else { // From the not-owned evals show those // that are available for viewing results. if (currentDate.before(evaluation.getViewDate())) { // Do nothing } else { newEvals.add(evaluation); } } } } if (! newEvals.isEmpty()) { UIBranchContainer evalAdminBC = UIBranchContainer.make(tofill, "evalAdminBox:"); // Temporary fix for http://www.caret.cam.ac.uk/jira/browse/CTL-583 (need to send them to the eval control page eventually) -AZ if (beginEvaluation) { UIInternalLink.make(evalAdminBC, "evaladmin-title-link", UIMessage.make("summary.evaluations.admin"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID) ); } else { UIMessage.make(evalAdminBC, "evaladmin-title", "summary.evaluations.admin"); } UIForm evalAdminForm = UIForm.make(evalAdminBC , "evalAdminForm"); UIMessage.make(evalAdminForm, "evaladmin-header-title","summary.header.title"); UIMessage.make(evalAdminForm, "evaladmin-header-status", "summary.header.status"); UIMessage.make(evalAdminForm, "evaladmin-header-date", "summary.header.date"); for (Iterator<EvalEvaluation> iter = newEvals.iterator(); iter.hasNext();) { EvalEvaluation eval = (EvalEvaluation) iter.next(); UIBranchContainer evalrow = UIBranchContainer.make(evalAdminForm, "evalAdminList:", eval.getId().toString() ); Date date; String evalStatus = evaluationService.updateEvaluationState(eval.getId()); if (EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus)) { date = eval.getStartDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(evalStatus)) { date = eval.getStopDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_DUE.equals(evalStatus)) { date = eval.getDueDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus)) { date = eval.getViewDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { date = eval.getViewDate(); int responsesCount = deliveryService.countResponses(eval.getId(), null, true); int enrollmentsCount = evaluationService.countParticipantsForEval(eval.getId()); int responsesNeeded = evalBeanUtils.getResponsesNeededToViewForResponseRate(responsesCount, enrollmentsCount); if ( responsesNeeded == 0 ) { UIInternalLink.make(evalrow, "viewReportLink", UIMessage.make("viewreport.page.title"), new ReportParameters(ReportChooseGroupsProducer.VIEW_ID, eval.getId())); } else { UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus) .decorate( new UITooltipDecorator( UIMessage.make("controlevaluations.eval.report.awaiting.responses", new Object[] { responsesNeeded }) ) ); } } else { date = eval.getStartDate(); } /* * 1) if a evaluation is queued, title link go to EditSettings page with populated data * 2) if a evaluation is active, title link go to EditSettings page with populated data * but start date should be disabled * 3) if a evaluation is closed, title link go to previewEval page with populated data */ if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) || EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { UIInternalLink.make(evalrow, "evalAdminTitleLink_preview", eval.getTitle(), new PreviewEvalParameters(PreviewEvalProducer.VIEW_ID, eval.getId(), eval.getTemplate().getId())); } else { UICommand evalEditUIC = UICommand.make(evalrow, "evalAdminTitleLink_edit", eval.getTitle(), "#{evaluationBean.editEvalSettingAction}"); evalEditUIC.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", eval.getId())); } UIMessage.make(evalrow, "evalAdminDateLabel", "summary.label." + evalStatus); UIOutput.make(evalrow, "evalAdminDate", df.format(date)); } } /* * Site/Group listing box */ Boolean enableSitesBox = (Boolean) settings.get(EvalSettings.ENABLE_SUMMARY_SITES_BOX); if (enableSitesBox) { // only show this if we cannot find our location OR if the option is forced to on String NO_ITEMS = "no.list.items"; UIBranchContainer contextsBC = UIBranchContainer.make(tofill, "siteListingBox:"); UIMessage.make(contextsBC, "sitelisting-title", "summary.sitelisting.title"); UIMessage.make(contextsBC, "sitelisting-evaluated-text", "summary.sitelisting.evaluated"); List<EvalGroup> evaluatedContexts = externalLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_BE_EVALUATED); if (evaluatedContexts.size() > 0) { for (int i=0; i<evaluatedContexts.size(); i++) { if (i > maxGroupsToDisplay) { UIMessage.make(contextsBC, "evaluatedListNone", "summary.sitelisting.maxshown", new Object[] { new Integer(evaluatedContexts.size() - maxGroupsToDisplay) }); break; } UIBranchContainer evaluatedBC = UIBranchContainer.make(contextsBC, "evaluatedList:", i+""); EvalGroup c = (EvalGroup) evaluatedContexts.get(i); UIOutput.make(evaluatedBC, "evaluatedListTitle", c.title); } } else { UIMessage.make(contextsBC, "evaluatedListNone", NO_ITEMS ); } UIMessage.make(contextsBC, "sitelisting-evaluate-text", "summary.sitelisting.evaluate"); List<EvalGroup> evaluateContexts = externalLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_TAKE_EVALUATION); if (evaluateContexts.size() > 0) { for (int i=0; i<evaluateContexts.size(); i++) { if (i > maxGroupsToDisplay) { UIMessage.make(contextsBC, "evaluateListNone", "summary.sitelisting.maxshown", new Object[] { new Integer(evaluateContexts.size() - maxGroupsToDisplay) }); break; } UIBranchContainer evaluateBC = UIBranchContainer.make(contextsBC, "evaluateList:", i+""); EvalGroup c = (EvalGroup) evaluateContexts.get(i); UIOutput.make(evaluateBC, "evaluateListTitle", c.title); } } else { UIMessage.make(contextsBC, "evaluateListNone", NO_ITEMS ); } } /* * For the Evaluation tools box */ if (createTemplate || beginEvaluation) { UIBranchContainer toolsBC = UIBranchContainer.make(tofill, "toolsBox:"); UIMessage.make(toolsBC, "tools-title", "summary.tools.title"); if ( createTemplate ) { UIInternalLink.make(toolsBC, "createTemplateLink", UIMessage.make("createtemplate.page.title"), new TemplateViewParameters(ModifyTemplateProducer.VIEW_ID, null)); } if ( beginEvaluation ) { UIInternalLink.make(toolsBC, "beginEvaluationLink", UIMessage.make("starteval.page.title"), new TemplateViewParameters(EvaluationStartProducer.VIEW_ID, null)); } } }
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = externalLogic.getCurrentUserId(); String currentGroup = externalLogic.getCurrentEvalGroup(); boolean userAdmin = externalLogic.isUserAdmin(currentUserId); boolean createTemplate = authoringService.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId); // use a date which is related to the current users locale DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-scales-link", UIMessage.make("controlscales.page.title"), new SimpleViewParameters(ControlScalesProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-items-link", UIMessage.make("controlitems.page.title"), new SimpleViewParameters(ControlItemsProducer.VIEW_ID)); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); UIMessage.make(tofill, "instructor-instructions", "summary.instructor.instruction"); } /* * Notification box listing box */ boolean userHasNotifications = false; if (userHasNotifications) { UIBranchContainer notificationsBC = UIBranchContainer.make(tofill, "notificationsBox:"); UIMessage.make(notificationsBC, "notifications-title","summary.notifications.title"); UIMessage.make(notificationsBC, "notifications-higher-level", "summary.eval.assigned.from.above"); // add other stuff } /* * for the evaluationSetupService taking box */ List<EvalEvaluation> evalsToTake = evaluationSetupService.getEvaluationsForUser(currentUserId, true, false); UIBranchContainer evalBC = UIBranchContainer.make(tofill, "evaluationsBox:"); if (evalsToTake.size() > 0) { // build an array of evaluation ids Long[] evalIds = new Long[evalsToTake.size()]; for (int i=0; i<evalsToTake.size(); i++) { evalIds[i] = ((EvalEvaluation) evalsToTake.get(i)).getId(); } // now fetch all the information we care about for these evaluationSetupService at once (for speed) Map<Long, List<EvalGroup>> evalGroups = evaluationService.getEvaluationGroups(evalIds, false); List<EvalResponse> evalResponses = deliveryService.getEvaluationResponses(currentUserId, evalIds, true); for (Iterator<EvalEvaluation> itEvals = evalsToTake.iterator(); itEvals.hasNext();) { EvalEvaluation eval = (EvalEvaluation) itEvals.next(); UIBranchContainer evalrow = UIBranchContainer.make(evalBC, "evaluationsList:", eval.getId().toString() ); UIOutput.make(evalrow, "evaluationTitleTitle", eval.getTitle() ); UIMessage.make(evalrow, "evaluationCourseEvalTitle", "summary.evaluations.courseeval.title" ); UIMessage.make(evalrow, "evaluationStartsTitle", "summary.evaluations.starts.title" ); UIMessage.make(evalrow, "evaluationEndsTitle", "summary.evaluations.ends.title" ); List<EvalGroup> groups = evalGroups.get(eval.getId()); for (int j=0; j<groups.size(); j++) { EvalGroup group = (EvalGroup) groups.get(j); if (EvalConstants.GROUP_TYPE_INVALID.equals(group.type)) { continue; // skip processing for invalid groups } //check that the user can take evaluationSetupService in this evalGroupId if (externalLogic.isUserAllowedInEvalGroup(currentUserId, EvalConstants.PERM_TAKE_EVALUATION, group.evalGroupId)) { String groupId = group.evalGroupId; String title = group.title; String status = "unknown.caps"; // find the object in the list matching the evalGroupId and evalId, // leave as null if not found -AZ EvalResponse response = null; for (int k=0; k<evalResponses.size(); k++) { EvalResponse er = (EvalResponse) evalResponses.get(k); if (groupId.equals(er.getEvalGroupId()) && eval.getId().equals(er.getEvaluation().getId())) { response = er; break; } } if (groupId.equals(currentGroup)) { // TODO - do something when the evalGroupId matches } UIBranchContainer evalcourserow = UIBranchContainer.make(evalrow, "evaluationsCourseList:", groupId ); // set status if (response != null && response.getEndTime() != null) { // there is a response for this eval/group if (eval.getModifyResponsesAllowed().booleanValue()) { // can modify responses so show the link still // take eval link when pending UIInternalLink.make(evalcourserow, "evaluationCourseLink", title, new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, eval.getId(), groupId, response.getId()) ); status = "summary.status.completed"; } else { // show title only when completed UIOutput.make(evalcourserow, "evaluationCourseTitle", title); status = "summary.status.completed"; } } else { // no response yet for this eval/group // take eval link when pending UIInternalLink.make(evalcourserow, "evaluationCourseLink", title, new EvalTakeViewParameters(TakeEvalProducer.VIEW_ID, eval.getId(), groupId) ); status = "summary.status.pending"; } UIMessage.make(evalcourserow, "evaluationCourseStatus", status ); // moved down here as requested by UI design UIOutput.make(evalcourserow, "evaluationStartDate", df.format(eval.getStartDate()) ); UIOutput.make(evalcourserow, "evaluationDueDate", df.format(eval.getDueDate()) ); } } } } else { UIMessage.make(tofill, "evaluationsNone", "summary.evaluations.none"); } /* * for the evaluations admin box */ Boolean instViewResults = (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS); if (instViewResults == null) { instViewResults = true; } // if configurable then we will assume some are probably shared List<EvalEvaluation> evals = evaluationSetupService.getVisibleEvaluationsForUser(currentUserId, true, instViewResults); /* * If the person is an admin, then just point new evals to existing object. * If the person is not an admin then only show owned evals + * not-owned evals that are available for viewing results. */ List<EvalEvaluation> newEvals; if (userAdmin) { newEvals = evals; } else { newEvals = new ArrayList<EvalEvaluation>(); int numEvals = evals.size(); Date currentDate = new Date(); for (int count = 0; count < numEvals; count++) { EvalEvaluation evaluation = (EvalEvaluation) evals.get(count); // Add the owned evals if (currentUserId.equals(evaluation.getOwner())) { newEvals.add(evaluation); } else { // From the not-owned evals show those // that are available for viewing results. if (currentDate.before(evaluation.getViewDate())) { // Do nothing } else { newEvals.add(evaluation); } } } } if (! newEvals.isEmpty()) { UIBranchContainer evalAdminBC = UIBranchContainer.make(tofill, "evalAdminBox:"); // Temporary fix for http://www.caret.cam.ac.uk/jira/browse/CTL-583 (need to send them to the eval control page eventually) -AZ if (beginEvaluation) { UIInternalLink.make(evalAdminBC, "evaladmin-title-link", UIMessage.make("summary.evaluations.admin"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID) ); } else { UIMessage.make(evalAdminBC, "evaladmin-title", "summary.evaluations.admin"); } UIForm evalAdminForm = UIForm.make(evalAdminBC , "evalAdminForm"); UIMessage.make(evalAdminForm, "evaladmin-header-title","summary.header.title"); UIMessage.make(evalAdminForm, "evaladmin-header-status", "summary.header.status"); UIMessage.make(evalAdminForm, "evaladmin-header-date", "summary.header.date"); for (Iterator<EvalEvaluation> iter = newEvals.iterator(); iter.hasNext();) { EvalEvaluation eval = (EvalEvaluation) iter.next(); UIBranchContainer evalrow = UIBranchContainer.make(evalAdminForm, "evalAdminList:", eval.getId().toString() ); Date date; String evalStatus = evaluationService.updateEvaluationState(eval.getId()); if (EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus)) { date = eval.getStartDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(evalStatus)) { date = eval.getStopDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_DUE.equals(evalStatus)) { date = eval.getDueDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus)) { date = eval.getViewDate(); UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus); } else if (EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { date = eval.getViewDate(); int responsesCount = deliveryService.countResponses(eval.getId(), null, true); int enrollmentsCount = evaluationService.countParticipantsForEval(eval.getId()); int responsesNeeded = evalBeanUtils.getResponsesNeededToViewForResponseRate(responsesCount, enrollmentsCount); if ( responsesNeeded == 0 ) { UIInternalLink.make(evalrow, "viewReportLink", UIMessage.make("viewreport.page.title"), new ReportParameters(ReportChooseGroupsProducer.VIEW_ID, eval.getId())); } else { UIMessage.make(evalrow, "evalAdminStatus", "summary.status." + evalStatus) .decorate( new UITooltipDecorator( UIMessage.make("controlevaluations.eval.report.awaiting.responses", new Object[] { responsesNeeded }) ) ); } } else { date = eval.getStartDate(); } /* * 1) if a evaluation is queued, title link go to EditSettings page with populated data * 2) if a evaluation is active, title link go to EditSettings page with populated data * but start date should be disabled * 3) if a evaluation is closed, title link go to previewEval page with populated data */ if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) || EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus)) { UIInternalLink.make(evalrow, "evalAdminTitleLink_preview", eval.getTitle(), new PreviewEvalParameters(PreviewEvalProducer.VIEW_ID, eval.getId(), eval.getTemplate().getId())); } else { UICommand evalEditUIC = UICommand.make(evalrow, "evalAdminTitleLink_edit", eval.getTitle(), "#{evaluationBean.editEvalSettingAction}"); evalEditUIC.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", eval.getId())); } UIMessage.make(evalrow, "evalAdminDateLabel", "summary.label." + evalStatus); UIOutput.make(evalrow, "evalAdminDate", df.format(date)); } } /* * Site/Group listing box */ Boolean enableSitesBox = (Boolean) settings.get(EvalSettings.ENABLE_SUMMARY_SITES_BOX); if (enableSitesBox) { // only show this if we cannot find our location OR if the option is forced to on String NO_ITEMS = "no.list.items"; UIBranchContainer contextsBC = UIBranchContainer.make(tofill, "siteListingBox:"); UIMessage.make(contextsBC, "sitelisting-title", "summary.sitelisting.title"); UIMessage.make(contextsBC, "sitelisting-evaluated-text", "summary.sitelisting.evaluated"); List<EvalGroup> evaluatedContexts = externalLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_BE_EVALUATED); if (evaluatedContexts.size() > 0) { for (int i=0; i<evaluatedContexts.size(); i++) { if (i > maxGroupsToDisplay) { UIMessage.make(contextsBC, "evaluatedListNone", "summary.sitelisting.maxshown", new Object[] { new Integer(evaluatedContexts.size() - maxGroupsToDisplay) }); break; } UIBranchContainer evaluatedBC = UIBranchContainer.make(contextsBC, "evaluatedList:", i+""); EvalGroup c = (EvalGroup) evaluatedContexts.get(i); UIOutput.make(evaluatedBC, "evaluatedListTitle", c.title); } } else { UIMessage.make(contextsBC, "evaluatedListNone", NO_ITEMS ); } UIMessage.make(contextsBC, "sitelisting-evaluate-text", "summary.sitelisting.evaluate"); List<EvalGroup> evaluateContexts = externalLogic.getEvalGroupsForUser(currentUserId, EvalConstants.PERM_TAKE_EVALUATION); if (evaluateContexts.size() > 0) { for (int i=0; i<evaluateContexts.size(); i++) { if (i > maxGroupsToDisplay) { UIMessage.make(contextsBC, "evaluateListNone", "summary.sitelisting.maxshown", new Object[] { new Integer(evaluateContexts.size() - maxGroupsToDisplay) }); break; } UIBranchContainer evaluateBC = UIBranchContainer.make(contextsBC, "evaluateList:", i+""); EvalGroup c = (EvalGroup) evaluateContexts.get(i); UIOutput.make(evaluateBC, "evaluateListTitle", c.title); } } else { UIMessage.make(contextsBC, "evaluateListNone", NO_ITEMS ); } } /* * For the Evaluation tools box */ if (createTemplate || beginEvaluation) { UIBranchContainer toolsBC = UIBranchContainer.make(tofill, "toolsBox:"); UIMessage.make(toolsBC, "tools-title", "summary.tools.title"); if ( createTemplate ) { UIInternalLink.make(toolsBC, "createTemplateLink", UIMessage.make("createtemplate.page.title"), new TemplateViewParameters(ModifyTemplateProducer.VIEW_ID, null)); } if ( beginEvaluation ) { UIInternalLink.make(toolsBC, "beginEvaluationLink", UIMessage.make("starteval.page.title"), new TemplateViewParameters(EvaluationStartProducer.VIEW_ID, null)); } } }
diff --git a/src/java/is/idega/idegaweb/pheidippides/presentation/RegistrationRunnerChanger.java b/src/java/is/idega/idegaweb/pheidippides/presentation/RegistrationRunnerChanger.java index a13eab6..421c648 100644 --- a/src/java/is/idega/idegaweb/pheidippides/presentation/RegistrationRunnerChanger.java +++ b/src/java/is/idega/idegaweb/pheidippides/presentation/RegistrationRunnerChanger.java @@ -1,158 +1,157 @@ package is.idega.idegaweb.pheidippides.presentation; import is.idega.idegaweb.pheidippides.PheidippidesConstants; import is.idega.idegaweb.pheidippides.bean.PheidippidesBean; import is.idega.idegaweb.pheidippides.business.PheidippidesService; import is.idega.idegaweb.pheidippides.dao.PheidippidesDao; import is.idega.idegaweb.pheidippides.data.Registration; import is.idega.idegaweb.pheidippides.output.ReceiptWriter; import javax.faces.context.FacesContext; import org.springframework.beans.factory.annotation.Autowired; import com.idega.block.web2.business.JQuery; import com.idega.facelets.ui.FaceletComponent; import com.idega.idegaweb.IWBundle; import com.idega.presentation.IWBaseComponent; import com.idega.presentation.IWContext; import com.idega.user.data.User; import com.idega.util.CoreConstants; import com.idega.util.PresentationUtil; import com.idega.util.expression.ELUtil; public class RegistrationRunnerChanger extends IWBaseComponent { private static final String PARAMETER_REGISTRATION = "prm_registration_pk"; private static final String PARAMETER_SSN = "prm_ssn"; private static final String PARAMETER_EMAIL = "prm_email"; private static final String PARAMETER_PHONE = "prm_phone"; private static final String PARAMETER_ACTION = "prm_action"; private static final int ACTION_PHASE_ONE = 1; private static final int ACTION_SAVE = 2; @Autowired private PheidippidesService service; @Autowired private PheidippidesDao dao; @Autowired private JQuery jQuery; private IWBundle iwb; @Override protected void initializeComponent(FacesContext context) { IWContext iwc = IWContext.getIWContext(context); if (iwc.isLoggedOn()) { User user = iwc.getCurrentUser(); iwb = getBundle(context, getBundleIdentifier()); Long registrationPK = iwc.isParameterSet(PARAMETER_REGISTRATION) ? Long .parseLong(iwc.getParameter(PARAMETER_REGISTRATION)) : null; - Registration registration = dao.getRegistration(registrationPK); + Registration registration = getDao().getRegistration(registrationPK); //Display error here when trying to change registration for another user if (!registration.getUserUUID().equals(user.getUniqueId())) { return; } PresentationUtil.addJavaScriptSourceLineToHeader(iwc, getJQuery() .getBundleURIToJQueryLib()); PresentationUtil.addJavaScriptSourcesLinesToHeader( iwc, getJQuery().getBundleURISToValidation( iwc.getCurrentLocale().getLanguage())); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, CoreConstants.DWR_ENGINE_SCRIPT); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, CoreConstants.DWR_UTIL_SCRIPT); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, "/dwr/interface/PheidippidesService.js"); /* PresentationUtil .addJavaScriptSourceLineToHeader( iwc, iwb.getVirtualPathWithFileNameString("javascript/participantDistanceChanger.js"));*/ PresentationUtil .addStyleSheetToHeader( iwc, iwb.getVirtualPathWithFileNameString("style/pheidippides.css")); PheidippidesBean bean = getBeanInstance("pheidippidesBean"); bean.setLocale(iwc.getCurrentLocale()); bean.setRegistration(registration); bean.setEvent(registration.getRace().getEvent()); - bean.setDownloadWriter(ReceiptWriter.class); FaceletComponent facelet = (FaceletComponent) iwc.getApplication() .createComponent(FaceletComponent.COMPONENT_TYPE); switch (parseAction(iwc, registration)) { case ACTION_PHASE_ONE: facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/phaseOne.xhtml")); break; case ACTION_SAVE: String ssn = iwc.getParameter(PARAMETER_SSN); String email = iwc.getParameter(PARAMETER_EMAIL); String phone = iwc.getParameter(PARAMETER_PHONE); boolean couldChangeRunner = getService() .changeRegistrationRunner(registration, ssn, email, phone); if (couldChangeRunner) { facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/save.xhtml")); } else { facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/error.xhtml")); } break; } add(facelet); } } private int parseAction(IWContext iwc, Registration registration) { int action = iwc.isParameterSet(PARAMETER_ACTION) ? Integer .parseInt(iwc.getParameter(PARAMETER_ACTION)) : ACTION_PHASE_ONE; return action; } private String getBundleIdentifier() { return PheidippidesConstants.IW_BUNDLE_IDENTIFIER; } private PheidippidesService getService() { if (service == null) { ELUtil.getInstance().autowire(this); } return service; } private PheidippidesDao getDao() { if (dao == null) { ELUtil.getInstance().autowire(this); } return dao; } private JQuery getJQuery() { if (jQuery == null) { ELUtil.getInstance().autowire(this); } return jQuery; } }
false
true
protected void initializeComponent(FacesContext context) { IWContext iwc = IWContext.getIWContext(context); if (iwc.isLoggedOn()) { User user = iwc.getCurrentUser(); iwb = getBundle(context, getBundleIdentifier()); Long registrationPK = iwc.isParameterSet(PARAMETER_REGISTRATION) ? Long .parseLong(iwc.getParameter(PARAMETER_REGISTRATION)) : null; Registration registration = dao.getRegistration(registrationPK); //Display error here when trying to change registration for another user if (!registration.getUserUUID().equals(user.getUniqueId())) { return; } PresentationUtil.addJavaScriptSourceLineToHeader(iwc, getJQuery() .getBundleURIToJQueryLib()); PresentationUtil.addJavaScriptSourcesLinesToHeader( iwc, getJQuery().getBundleURISToValidation( iwc.getCurrentLocale().getLanguage())); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, CoreConstants.DWR_ENGINE_SCRIPT); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, CoreConstants.DWR_UTIL_SCRIPT); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, "/dwr/interface/PheidippidesService.js"); /* PresentationUtil .addJavaScriptSourceLineToHeader( iwc, iwb.getVirtualPathWithFileNameString("javascript/participantDistanceChanger.js"));*/ PresentationUtil .addStyleSheetToHeader( iwc, iwb.getVirtualPathWithFileNameString("style/pheidippides.css")); PheidippidesBean bean = getBeanInstance("pheidippidesBean"); bean.setLocale(iwc.getCurrentLocale()); bean.setRegistration(registration); bean.setEvent(registration.getRace().getEvent()); bean.setDownloadWriter(ReceiptWriter.class); FaceletComponent facelet = (FaceletComponent) iwc.getApplication() .createComponent(FaceletComponent.COMPONENT_TYPE); switch (parseAction(iwc, registration)) { case ACTION_PHASE_ONE: facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/phaseOne.xhtml")); break; case ACTION_SAVE: String ssn = iwc.getParameter(PARAMETER_SSN); String email = iwc.getParameter(PARAMETER_EMAIL); String phone = iwc.getParameter(PARAMETER_PHONE); boolean couldChangeRunner = getService() .changeRegistrationRunner(registration, ssn, email, phone); if (couldChangeRunner) { facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/save.xhtml")); } else { facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/error.xhtml")); } break; } add(facelet); } }
protected void initializeComponent(FacesContext context) { IWContext iwc = IWContext.getIWContext(context); if (iwc.isLoggedOn()) { User user = iwc.getCurrentUser(); iwb = getBundle(context, getBundleIdentifier()); Long registrationPK = iwc.isParameterSet(PARAMETER_REGISTRATION) ? Long .parseLong(iwc.getParameter(PARAMETER_REGISTRATION)) : null; Registration registration = getDao().getRegistration(registrationPK); //Display error here when trying to change registration for another user if (!registration.getUserUUID().equals(user.getUniqueId())) { return; } PresentationUtil.addJavaScriptSourceLineToHeader(iwc, getJQuery() .getBundleURIToJQueryLib()); PresentationUtil.addJavaScriptSourcesLinesToHeader( iwc, getJQuery().getBundleURISToValidation( iwc.getCurrentLocale().getLanguage())); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, CoreConstants.DWR_ENGINE_SCRIPT); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, CoreConstants.DWR_UTIL_SCRIPT); PresentationUtil.addJavaScriptSourceLineToHeader(iwc, "/dwr/interface/PheidippidesService.js"); /* PresentationUtil .addJavaScriptSourceLineToHeader( iwc, iwb.getVirtualPathWithFileNameString("javascript/participantDistanceChanger.js"));*/ PresentationUtil .addStyleSheetToHeader( iwc, iwb.getVirtualPathWithFileNameString("style/pheidippides.css")); PheidippidesBean bean = getBeanInstance("pheidippidesBean"); bean.setLocale(iwc.getCurrentLocale()); bean.setRegistration(registration); bean.setEvent(registration.getRace().getEvent()); FaceletComponent facelet = (FaceletComponent) iwc.getApplication() .createComponent(FaceletComponent.COMPONENT_TYPE); switch (parseAction(iwc, registration)) { case ACTION_PHASE_ONE: facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/phaseOne.xhtml")); break; case ACTION_SAVE: String ssn = iwc.getParameter(PARAMETER_SSN); String email = iwc.getParameter(PARAMETER_EMAIL); String phone = iwc.getParameter(PARAMETER_PHONE); boolean couldChangeRunner = getService() .changeRegistrationRunner(registration, ssn, email, phone); if (couldChangeRunner) { facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/save.xhtml")); } else { facelet.setFaceletURI(iwb .getFaceletURI("registrationRunnerChanger/error.xhtml")); } break; } add(facelet); } }
diff --git a/src/test/java/se/triad/kickass/exomizer/TestJNA.java b/src/test/java/se/triad/kickass/exomizer/TestJNA.java index 6db30a7..d0b9318 100644 --- a/src/test/java/se/triad/kickass/exomizer/TestJNA.java +++ b/src/test/java/se/triad/kickass/exomizer/TestJNA.java @@ -1,54 +1,54 @@ package se.triad.kickass.exomizer; import junit.framework.Assert; import net.magli143.exo.ExoLibrary; import net.magli143.exo.crunch_info; import net.magli143.exo.crunch_options; import net.magli143.exo.membuf; import org.testng.annotations.Test; import com.sun.jna.Memory; import com.sun.jna.Pointer; @Test public class TestJNA { @Test public void testCrunch() throws Exception { ExoLibrary exolib = ExoLibrary.INSTANCE; crunch_options options = new crunch_options(null, 65535,65535, 65535, 1, 0); crunch_info info = new crunch_info(); final String txt = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; membuf in = new membuf(); membuf crunched = new membuf(); membuf out = new membuf(); exolib.membuf_init(in); exolib.membuf_init(crunched); exolib.membuf_init(out); - Pointer m = new Memory(txt.length() + 1); + Pointer m = new Memory(txt.length()*2 + 1); m.setString(0, txt); exolib.membuf_append(in, m, txt.length()); exolib.crunch(in, crunched, options, info); System.out.printf("Crunched %d bytes to %d bytes, needed safety offset is %d\n", exolib.membuf_memlen(in), exolib.membuf_memlen(crunched), info.needed_safety_offset); exolib.decrunch(0, crunched, out); Assert.assertEquals(txt.length(), exolib.membuf_memlen(out)); Assert.assertEquals(txt, exolib.membuf_get(out).getString(0)); } }
true
true
public void testCrunch() throws Exception { ExoLibrary exolib = ExoLibrary.INSTANCE; crunch_options options = new crunch_options(null, 65535,65535, 65535, 1, 0); crunch_info info = new crunch_info(); final String txt = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; membuf in = new membuf(); membuf crunched = new membuf(); membuf out = new membuf(); exolib.membuf_init(in); exolib.membuf_init(crunched); exolib.membuf_init(out); Pointer m = new Memory(txt.length() + 1); m.setString(0, txt); exolib.membuf_append(in, m, txt.length()); exolib.crunch(in, crunched, options, info); System.out.printf("Crunched %d bytes to %d bytes, needed safety offset is %d\n", exolib.membuf_memlen(in), exolib.membuf_memlen(crunched), info.needed_safety_offset); exolib.decrunch(0, crunched, out); Assert.assertEquals(txt.length(), exolib.membuf_memlen(out)); Assert.assertEquals(txt, exolib.membuf_get(out).getString(0)); }
public void testCrunch() throws Exception { ExoLibrary exolib = ExoLibrary.INSTANCE; crunch_options options = new crunch_options(null, 65535,65535, 65535, 1, 0); crunch_info info = new crunch_info(); final String txt = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; membuf in = new membuf(); membuf crunched = new membuf(); membuf out = new membuf(); exolib.membuf_init(in); exolib.membuf_init(crunched); exolib.membuf_init(out); Pointer m = new Memory(txt.length()*2 + 1); m.setString(0, txt); exolib.membuf_append(in, m, txt.length()); exolib.crunch(in, crunched, options, info); System.out.printf("Crunched %d bytes to %d bytes, needed safety offset is %d\n", exolib.membuf_memlen(in), exolib.membuf_memlen(crunched), info.needed_safety_offset); exolib.decrunch(0, crunched, out); Assert.assertEquals(txt.length(), exolib.membuf_memlen(out)); Assert.assertEquals(txt, exolib.membuf_get(out).getString(0)); }
diff --git a/src/de/ueller/midlet/gps/GuiMapFeatures.java b/src/de/ueller/midlet/gps/GuiMapFeatures.java index d1670fe2..3370ec26 100644 --- a/src/de/ueller/midlet/gps/GuiMapFeatures.java +++ b/src/de/ueller/midlet/gps/GuiMapFeatures.java @@ -1,176 +1,176 @@ package de.ueller.midlet.gps; /* * GpsMid - Copyright (c) 2008 sk750 at users dot sourceforge dot net * See Copying */ import javax.microedition.lcdui.*; import de.ueller.gps.data.Configuration; import de.ueller.gps.data.Legend; import de.ueller.midlet.gps.data.ProjFactory; import de.enough.polish.util.Locale; public class GuiMapFeatures extends Form implements CommandListener { // Groups private ChoiceGroup elemsGroup; private String [] elems = new String[10]; private boolean[] selElems = new boolean[10]; private ChoiceGroup altInfosGroup; private String [] altInfos = new String[2]; private boolean[] selAltInfos = new boolean[2]; private ChoiceGroup rotationGroup; private String [] rotation = new String[2]; private ChoiceGroup modesGroup; private String [] modes = new String[3]; private boolean[] selModes = new boolean[3]; private TextField tfBaseScale; private ChoiceGroup otherGroup; private String [] other = new String[2]; private boolean[] selOther = new boolean[2]; private Gauge gaugeDetailBoost; private Gauge gaugeDetailBoostPOI; // commands private static final Command CMD_APPLY = new Command(Locale.get("guimapfeatures.Apply")/*Apply*/, Command.BACK, 1); private static final Command CMD_SAVE = new Command(Locale.get("guimapfeatures.Save")/*Save*/, Command.ITEM, 2); //private static final Command CMD_CANCEL = new Command(Locale.get("generic.Cancel")/*Cancel*/, Command.CANCEL, 3); // other private Trace parent; public GuiMapFeatures(Trace tr) { super(Locale.get("guimapfeatures.MapFeatures")/*Map features*/); this.parent = tr; try { // set choice texts and convert bits from render flag into selection states elems[0] = Locale.get("guimapfeatures.POIs")/*POIs*/; selElems[0]=Configuration.getCfgBitState(Configuration.CFGBIT_POIS); elems[1] = Locale.get("guimapfeatures.POIlabels")/*POI labels*/; selElems[1]=Configuration.getCfgBitState(Configuration.CFGBIT_POITEXTS); elems[2] = Locale.get("guimapfeatures.Waylabels")/*Way labels*/; selElems[2]=Configuration.getCfgBitState(Configuration.CFGBIT_WAYTEXTS); elems[3] = Locale.get("guimapfeatures.Onewayarrows")/*Oneway arrows*/; selElems[3]=Configuration.getCfgBitState(Configuration.CFGBIT_ONEWAY_ARROWS); elems[4] = Locale.get("guimapfeatures.Areas")/*Areas*/; selElems[4]=Configuration.getCfgBitState(Configuration.CFGBIT_AREAS); elems[5] = Locale.get("guimapfeatures.AreaLabels")/*Area labels*/; selElems[5]=Configuration.getCfgBitState(Configuration.CFGBIT_AREATEXTS); elems[6] = Locale.get("guimapfeatures.Buildings")/*Buildings*/; selElems[6]=Configuration.getCfgBitState(Configuration.CFGBIT_BUILDINGS); elems[7] = Locale.get("guimapfeatures.BuildingLabels")/*Building labels*/; selElems[7]=Configuration.getCfgBitState(Configuration.CFGBIT_BUILDING_LABELS); elems[8] = Locale.get("guimapfeatures.WaypointLabels")/*Waypoint labels*/; selElems[8]=Configuration.getCfgBitState(Configuration.CFGBIT_WPTTEXTS); elems[9] = Locale.get("guimapfeatures.PlaceLabels")/*Place labels (cities, etc.)*/; selElems[9]=Configuration.getCfgBitState(Configuration.CFGBIT_PLACETEXTS); elemsGroup = new ChoiceGroup(Locale.get("guimapfeatures.Elements")/*Elements*/, Choice.MULTIPLE, elems ,null); elemsGroup.setSelectedFlags(selElems); append(elemsGroup); altInfos[0] = Locale.get("guimapfeatures.LatLon")/*Lat/lon*/; selAltInfos[0]=Configuration.getCfgBitState(Configuration.CFGBIT_SHOWLATLON); altInfos[1] = Locale.get("guimapfeatures.TypeInformation")/*Type information*/; selAltInfos[1]=Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE); altInfosGroup = new ChoiceGroup(Locale.get("guimapfeatures.AlternativeInfo")/*Alternative info*/, Choice.MULTIPLE, altInfos ,null); altInfosGroup.setSelectedFlags(selAltInfos); append(altInfosGroup); - rotation = ProjFactory.name; + rotation = Configuration.projectionsString; rotationGroup = new ChoiceGroup(Locale.get("guimapfeatures.MapProjection")/*Map projection*/, Choice.EXCLUSIVE, rotation ,null); rotationGroup.setSelectedIndex((int) ProjFactory.getProj(), true); append(rotationGroup); modes[0] = Locale.get("guimapfeatures.FullScreen")/*Full screen*/; selModes[0]=Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN); modes[1] = Locale.get("guimapfeatures.AutoZoom")/*Auto zoom*/; selModes[1]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM); modes[2] = Locale.get("guimapfeatures.RenderAsStreets")/*Render as streets*/; selModes[2]=Configuration.getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE); modesGroup = new ChoiceGroup(Locale.get("guimapfeatures.Mode")/*Mode*/, Choice.MULTIPLE, modes ,null); modesGroup.setSelectedFlags(selModes); append(modesGroup); tfBaseScale = new TextField(Locale.get("guimapfeatures.BaseZoomLevel")/*Base Zoom Level (23 = default)*/, Integer.toString(Configuration.getBaseScale()), 6, TextField.DECIMAL); append(tfBaseScale); other[0] = Locale.get("guimapfeatures.SaveMapPosition")/*Save map position on exit for next start*/; selOther[0]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_MAPPOS); other[1] = Locale.get("guimapfeatures.SaveDestinationPosition")/*Save destination position for next start*/; selOther[1]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS); otherGroup = new ChoiceGroup(Locale.get("guimapfeatures.Other")/*Other*/, Choice.MULTIPLE, other, null); otherGroup.setSelectedFlags(selOther); append(otherGroup); gaugeDetailBoost = new Gauge(Locale.get("guimapfeatures.ZoomingWaysEarlier")/*Zooming: show ways earlier*/, true, 3, 0); append(gaugeDetailBoost); gaugeDetailBoost.setValue(Configuration.getDetailBoost()); gaugeDetailBoostPOI = new Gauge(Locale.get("guimapfeatures.ZoomingPoisEarlier")/*Zooming: show POIs earlier*/, true, 3, 0); append(gaugeDetailBoostPOI); gaugeDetailBoostPOI.setValue(Configuration.getDetailBoostPOI()); addCommand(CMD_APPLY); addCommand(CMD_SAVE); //addCommand(CMD_CANCEL); // Set up this Displayable to listen to command events setCommandListener(this); } catch (Exception e) { e.printStackTrace(); } } public void commandAction(Command c, Displayable d) { if (c == CMD_APPLY || c == CMD_SAVE) { // determine if changes should be written to recordstore boolean setAsDefault = (c == CMD_SAVE); // convert boolean array with selection states for renderOpts // to one flag with corresponding bits set elemsGroup.getSelectedFlags(selElems); Configuration.setCfgBitState(Configuration.CFGBIT_POIS, selElems[0], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_POITEXTS, selElems[1], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_WAYTEXTS, selElems[2], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_ONEWAY_ARROWS, selElems[3], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_AREAS, selElems[4], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_AREATEXTS, selElems[5], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_BUILDINGS, selElems[6], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_BUILDING_LABELS, selElems[7], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_WPTTEXTS, selElems[8], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_PLACETEXTS, selElems[9], setAsDefault); altInfosGroup.getSelectedFlags(selAltInfos); Configuration.setCfgBitState(Configuration.CFGBIT_SHOWLATLON, selAltInfos[0], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE, selAltInfos[1], setAsDefault); byte t = (byte) rotationGroup.getSelectedIndex(); ProjFactory.setProj(t); if (setAsDefault) { Configuration.setProjTypeDefault(t); } modesGroup.getSelectedFlags(selModes); Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, selModes[0], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_AUTOZOOM, selModes[1], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_STREETRENDERMODE, selModes[2], setAsDefault); float oldRealBaseScale = Configuration.getRealBaseScale(); Configuration.setBaseScale( (int) (Float.parseFloat(tfBaseScale.getString())) ); if (oldRealBaseScale != Configuration.getRealBaseScale()) { Legend.reReadLegend(); Trace.getInstance().scale = Configuration.getRealBaseScale(); } otherGroup.getSelectedFlags(selOther); Configuration.setCfgBitState(Configuration.CFGBIT_AUTOSAVE_MAPPOS, selOther[0], setAsDefault); Configuration.setCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS, selOther[1], setAsDefault); Configuration.setDetailBoost(gaugeDetailBoost.getValue(), setAsDefault); Configuration.setDetailBoostPOI(gaugeDetailBoostPOI.getValue(), setAsDefault); parent.show(); return; } } public void show() { GpsMid.getInstance().show(this); } }
true
true
public GuiMapFeatures(Trace tr) { super(Locale.get("guimapfeatures.MapFeatures")/*Map features*/); this.parent = tr; try { // set choice texts and convert bits from render flag into selection states elems[0] = Locale.get("guimapfeatures.POIs")/*POIs*/; selElems[0]=Configuration.getCfgBitState(Configuration.CFGBIT_POIS); elems[1] = Locale.get("guimapfeatures.POIlabels")/*POI labels*/; selElems[1]=Configuration.getCfgBitState(Configuration.CFGBIT_POITEXTS); elems[2] = Locale.get("guimapfeatures.Waylabels")/*Way labels*/; selElems[2]=Configuration.getCfgBitState(Configuration.CFGBIT_WAYTEXTS); elems[3] = Locale.get("guimapfeatures.Onewayarrows")/*Oneway arrows*/; selElems[3]=Configuration.getCfgBitState(Configuration.CFGBIT_ONEWAY_ARROWS); elems[4] = Locale.get("guimapfeatures.Areas")/*Areas*/; selElems[4]=Configuration.getCfgBitState(Configuration.CFGBIT_AREAS); elems[5] = Locale.get("guimapfeatures.AreaLabels")/*Area labels*/; selElems[5]=Configuration.getCfgBitState(Configuration.CFGBIT_AREATEXTS); elems[6] = Locale.get("guimapfeatures.Buildings")/*Buildings*/; selElems[6]=Configuration.getCfgBitState(Configuration.CFGBIT_BUILDINGS); elems[7] = Locale.get("guimapfeatures.BuildingLabels")/*Building labels*/; selElems[7]=Configuration.getCfgBitState(Configuration.CFGBIT_BUILDING_LABELS); elems[8] = Locale.get("guimapfeatures.WaypointLabels")/*Waypoint labels*/; selElems[8]=Configuration.getCfgBitState(Configuration.CFGBIT_WPTTEXTS); elems[9] = Locale.get("guimapfeatures.PlaceLabels")/*Place labels (cities, etc.)*/; selElems[9]=Configuration.getCfgBitState(Configuration.CFGBIT_PLACETEXTS); elemsGroup = new ChoiceGroup(Locale.get("guimapfeatures.Elements")/*Elements*/, Choice.MULTIPLE, elems ,null); elemsGroup.setSelectedFlags(selElems); append(elemsGroup); altInfos[0] = Locale.get("guimapfeatures.LatLon")/*Lat/lon*/; selAltInfos[0]=Configuration.getCfgBitState(Configuration.CFGBIT_SHOWLATLON); altInfos[1] = Locale.get("guimapfeatures.TypeInformation")/*Type information*/; selAltInfos[1]=Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE); altInfosGroup = new ChoiceGroup(Locale.get("guimapfeatures.AlternativeInfo")/*Alternative info*/, Choice.MULTIPLE, altInfos ,null); altInfosGroup.setSelectedFlags(selAltInfos); append(altInfosGroup); rotation = ProjFactory.name; rotationGroup = new ChoiceGroup(Locale.get("guimapfeatures.MapProjection")/*Map projection*/, Choice.EXCLUSIVE, rotation ,null); rotationGroup.setSelectedIndex((int) ProjFactory.getProj(), true); append(rotationGroup); modes[0] = Locale.get("guimapfeatures.FullScreen")/*Full screen*/; selModes[0]=Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN); modes[1] = Locale.get("guimapfeatures.AutoZoom")/*Auto zoom*/; selModes[1]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM); modes[2] = Locale.get("guimapfeatures.RenderAsStreets")/*Render as streets*/; selModes[2]=Configuration.getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE); modesGroup = new ChoiceGroup(Locale.get("guimapfeatures.Mode")/*Mode*/, Choice.MULTIPLE, modes ,null); modesGroup.setSelectedFlags(selModes); append(modesGroup); tfBaseScale = new TextField(Locale.get("guimapfeatures.BaseZoomLevel")/*Base Zoom Level (23 = default)*/, Integer.toString(Configuration.getBaseScale()), 6, TextField.DECIMAL); append(tfBaseScale); other[0] = Locale.get("guimapfeatures.SaveMapPosition")/*Save map position on exit for next start*/; selOther[0]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_MAPPOS); other[1] = Locale.get("guimapfeatures.SaveDestinationPosition")/*Save destination position for next start*/; selOther[1]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS); otherGroup = new ChoiceGroup(Locale.get("guimapfeatures.Other")/*Other*/, Choice.MULTIPLE, other, null); otherGroup.setSelectedFlags(selOther); append(otherGroup); gaugeDetailBoost = new Gauge(Locale.get("guimapfeatures.ZoomingWaysEarlier")/*Zooming: show ways earlier*/, true, 3, 0); append(gaugeDetailBoost); gaugeDetailBoost.setValue(Configuration.getDetailBoost()); gaugeDetailBoostPOI = new Gauge(Locale.get("guimapfeatures.ZoomingPoisEarlier")/*Zooming: show POIs earlier*/, true, 3, 0); append(gaugeDetailBoostPOI); gaugeDetailBoostPOI.setValue(Configuration.getDetailBoostPOI()); addCommand(CMD_APPLY); addCommand(CMD_SAVE); //addCommand(CMD_CANCEL); // Set up this Displayable to listen to command events setCommandListener(this); } catch (Exception e) { e.printStackTrace(); } }
public GuiMapFeatures(Trace tr) { super(Locale.get("guimapfeatures.MapFeatures")/*Map features*/); this.parent = tr; try { // set choice texts and convert bits from render flag into selection states elems[0] = Locale.get("guimapfeatures.POIs")/*POIs*/; selElems[0]=Configuration.getCfgBitState(Configuration.CFGBIT_POIS); elems[1] = Locale.get("guimapfeatures.POIlabels")/*POI labels*/; selElems[1]=Configuration.getCfgBitState(Configuration.CFGBIT_POITEXTS); elems[2] = Locale.get("guimapfeatures.Waylabels")/*Way labels*/; selElems[2]=Configuration.getCfgBitState(Configuration.CFGBIT_WAYTEXTS); elems[3] = Locale.get("guimapfeatures.Onewayarrows")/*Oneway arrows*/; selElems[3]=Configuration.getCfgBitState(Configuration.CFGBIT_ONEWAY_ARROWS); elems[4] = Locale.get("guimapfeatures.Areas")/*Areas*/; selElems[4]=Configuration.getCfgBitState(Configuration.CFGBIT_AREAS); elems[5] = Locale.get("guimapfeatures.AreaLabels")/*Area labels*/; selElems[5]=Configuration.getCfgBitState(Configuration.CFGBIT_AREATEXTS); elems[6] = Locale.get("guimapfeatures.Buildings")/*Buildings*/; selElems[6]=Configuration.getCfgBitState(Configuration.CFGBIT_BUILDINGS); elems[7] = Locale.get("guimapfeatures.BuildingLabels")/*Building labels*/; selElems[7]=Configuration.getCfgBitState(Configuration.CFGBIT_BUILDING_LABELS); elems[8] = Locale.get("guimapfeatures.WaypointLabels")/*Waypoint labels*/; selElems[8]=Configuration.getCfgBitState(Configuration.CFGBIT_WPTTEXTS); elems[9] = Locale.get("guimapfeatures.PlaceLabels")/*Place labels (cities, etc.)*/; selElems[9]=Configuration.getCfgBitState(Configuration.CFGBIT_PLACETEXTS); elemsGroup = new ChoiceGroup(Locale.get("guimapfeatures.Elements")/*Elements*/, Choice.MULTIPLE, elems ,null); elemsGroup.setSelectedFlags(selElems); append(elemsGroup); altInfos[0] = Locale.get("guimapfeatures.LatLon")/*Lat/lon*/; selAltInfos[0]=Configuration.getCfgBitState(Configuration.CFGBIT_SHOWLATLON); altInfos[1] = Locale.get("guimapfeatures.TypeInformation")/*Type information*/; selAltInfos[1]=Configuration.getCfgBitState(Configuration.CFGBIT_SHOWWAYPOITYPE); altInfosGroup = new ChoiceGroup(Locale.get("guimapfeatures.AlternativeInfo")/*Alternative info*/, Choice.MULTIPLE, altInfos ,null); altInfosGroup.setSelectedFlags(selAltInfos); append(altInfosGroup); rotation = Configuration.projectionsString; rotationGroup = new ChoiceGroup(Locale.get("guimapfeatures.MapProjection")/*Map projection*/, Choice.EXCLUSIVE, rotation ,null); rotationGroup.setSelectedIndex((int) ProjFactory.getProj(), true); append(rotationGroup); modes[0] = Locale.get("guimapfeatures.FullScreen")/*Full screen*/; selModes[0]=Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN); modes[1] = Locale.get("guimapfeatures.AutoZoom")/*Auto zoom*/; selModes[1]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM); modes[2] = Locale.get("guimapfeatures.RenderAsStreets")/*Render as streets*/; selModes[2]=Configuration.getCfgBitState(Configuration.CFGBIT_STREETRENDERMODE); modesGroup = new ChoiceGroup(Locale.get("guimapfeatures.Mode")/*Mode*/, Choice.MULTIPLE, modes ,null); modesGroup.setSelectedFlags(selModes); append(modesGroup); tfBaseScale = new TextField(Locale.get("guimapfeatures.BaseZoomLevel")/*Base Zoom Level (23 = default)*/, Integer.toString(Configuration.getBaseScale()), 6, TextField.DECIMAL); append(tfBaseScale); other[0] = Locale.get("guimapfeatures.SaveMapPosition")/*Save map position on exit for next start*/; selOther[0]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_MAPPOS); other[1] = Locale.get("guimapfeatures.SaveDestinationPosition")/*Save destination position for next start*/; selOther[1]=Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS); otherGroup = new ChoiceGroup(Locale.get("guimapfeatures.Other")/*Other*/, Choice.MULTIPLE, other, null); otherGroup.setSelectedFlags(selOther); append(otherGroup); gaugeDetailBoost = new Gauge(Locale.get("guimapfeatures.ZoomingWaysEarlier")/*Zooming: show ways earlier*/, true, 3, 0); append(gaugeDetailBoost); gaugeDetailBoost.setValue(Configuration.getDetailBoost()); gaugeDetailBoostPOI = new Gauge(Locale.get("guimapfeatures.ZoomingPoisEarlier")/*Zooming: show POIs earlier*/, true, 3, 0); append(gaugeDetailBoostPOI); gaugeDetailBoostPOI.setValue(Configuration.getDetailBoostPOI()); addCommand(CMD_APPLY); addCommand(CMD_SAVE); //addCommand(CMD_CANCEL); // Set up this Displayable to listen to command events setCommandListener(this); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/WarpgateFlagListener.java b/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/WarpgateFlagListener.java index e4d2f593..482593f1 100644 --- a/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/WarpgateFlagListener.java +++ b/NCuboid/src/main/java/fr/ribesg/bukkit/ncuboid/listeners/flag/WarpgateFlagListener.java @@ -1,37 +1,38 @@ /*************************************************************************** * Project file: NPlugins - NCuboid - WarpgateFlagListener.java * * Full Class name: fr.ribesg.bukkit.ncuboid.listeners.flag.WarpgateFlagListener * * * Copyright (c) 2013 Ribesg - www.ribesg.fr * * This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt * * Please contact me at ribesg[at]yahoo.fr if you improve this file! * ***************************************************************************/ package fr.ribesg.bukkit.ncuboid.listeners.flag; import fr.ribesg.bukkit.ncuboid.NCuboid; import fr.ribesg.bukkit.ncuboid.beans.Flag; import fr.ribesg.bukkit.ncuboid.beans.FlagAtt; import fr.ribesg.bukkit.ncuboid.events.extensions.ExtendedPlayerMoveEvent; import fr.ribesg.bukkit.ncuboid.listeners.AbstractListener; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; public class WarpgateFlagListener extends AbstractListener { public WarpgateFlagListener(final NCuboid instance) { super(instance); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerMoveBlock(final ExtendedPlayerMoveEvent ext) { final PlayerMoveEvent event = (PlayerMoveEvent) ext.getBaseEvent(); if (!ext.isCustomCancelled()) { if (ext.getToRegion() != null && ext.getToRegion().getFlag(Flag.WARPGATE)) { event.getPlayer().teleport(ext.getToRegion().getLocFlagAtt(FlagAtt.EXTERNAL_POINT)); + ext.setCustomCancelled(true); event.setCancelled(true); } } } }
true
true
public void onPlayerMoveBlock(final ExtendedPlayerMoveEvent ext) { final PlayerMoveEvent event = (PlayerMoveEvent) ext.getBaseEvent(); if (!ext.isCustomCancelled()) { if (ext.getToRegion() != null && ext.getToRegion().getFlag(Flag.WARPGATE)) { event.getPlayer().teleport(ext.getToRegion().getLocFlagAtt(FlagAtt.EXTERNAL_POINT)); event.setCancelled(true); } } }
public void onPlayerMoveBlock(final ExtendedPlayerMoveEvent ext) { final PlayerMoveEvent event = (PlayerMoveEvent) ext.getBaseEvent(); if (!ext.isCustomCancelled()) { if (ext.getToRegion() != null && ext.getToRegion().getFlag(Flag.WARPGATE)) { event.getPlayer().teleport(ext.getToRegion().getLocFlagAtt(FlagAtt.EXTERNAL_POINT)); ext.setCustomCancelled(true); event.setCancelled(true); } } }
diff --git a/src/main/java/com/laytonsmith/aliasengine/AliasCore.java b/src/main/java/com/laytonsmith/aliasengine/AliasCore.java index c709f303..5c14f4a2 100644 --- a/src/main/java/com/laytonsmith/aliasengine/AliasCore.java +++ b/src/main/java/com/laytonsmith/aliasengine/AliasCore.java @@ -1,345 +1,345 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.laytonsmith.aliasengine; import com.laytonsmith.aliasengine.functions.exceptions.ConfigCompileException; import com.laytonsmith.aliasengine.functions.exceptions.ConfigRuntimeException; import com.laytonsmith.PureUtilities.Preferences; import com.laytonsmith.aliasengine.functions.IncludeCache; import com.sk89q.bukkit.migration.PermissionsResolverManager; import com.sk89q.commandhelper.CommandHelperPlugin; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * This class contains all the handling code. It only deals with built-in Java Objects, * so that if the Minecraft API Hook changes, porting the code will only require changing * the API specific portions, not this core file. * @author Layton */ public class AliasCore { private File aliasConfig; private File prefFile; //AliasConfig config; List<Script> scripts; static final Logger logger = Logger.getLogger("Minecraft"); private Set<String> echoCommand = new HashSet<String>(); private PermissionsResolverManager perms; public static CommandHelperPlugin parent; /** * This constructor accepts the configuration settings for the plugin, and ensures * that the manager uses these settings. * @param allowCustomAliases Whether or not to allow users to add their own personal aliases * @param maxCustomAliases How many aliases a player is allowed to have. -1 is unlimited. * @param maxCommands How many commands an alias may contain. Since aliases can be used like a * macro, this can help prevent command spamming. */ public AliasCore(File aliasConfig, File prefFile, PermissionsResolverManager perms, CommandHelperPlugin parent) throws ConfigCompileException { this.aliasConfig = aliasConfig; this.prefFile = prefFile; this.perms = perms; this.parent = parent; reload(); } /** * This is the workhorse function. It takes a given command, then converts it * into the actual command(s). If the command maps to a defined alias, it will * run the specified alias. It will search through the * global list of aliases, as well as the aliases defined for that specific player. * This function doesn't handle the /alias command however. * @param command * @return */ public boolean alias(String command, final CommandSender player, ArrayList<Script> playerCommands) { if (scripts == null) { throw new ConfigRuntimeException("Cannot run alias commands, no config file is loaded", 0, null); } boolean match = false; try { //catch RuntimeException //If player is null, we are running the test harness, so don't //actually add the player to the array. if (player != null && player instanceof Player && echoCommand.contains(((Player) player).getName())) { //we are running one of the expanded commands, so exit with false return false; } //Global aliases override personal ones, so check the list first //a = config.getRunnableAliases(command, player); for (Script s : scripts) { try { if (s.match(command)) { this.addPlayerReference(player); if ((Boolean) Static.getPreferences().getPreference("console-log-commands")) { Static.getLogger().log(Level.INFO, "CH: Running original command ----> " + command); if (player instanceof Player) { Static.getLogger().log(Level.INFO, "on player " + ((Player) player).getName()); } else { Static.getLogger().log(Level.INFO, "from a CommandSender"); } } try { s.run(s.getVariables(command), player, new MScriptComplete() { public void done(String output) { try { if (output != null) { if (!output.trim().equals("") && output.trim().startsWith("/")) { if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { if (player instanceof Player) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) player).getName() + ": " + output.trim()); } else { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + output.trim()); } } //Sometimes bukkit works with one version of this, sometimes with the other. performCommand would be prefered, but //chat works more often, because chat actually triggers a CommandPreprocessEvent, unlike performCommand. if (player instanceof Player) { ((Player) player).chat(output.trim()); } else { - Static.getServer().dispatchCommand(player, output.trim()); + Static.getServer().dispatchCommand(player, output.trim().substring(1)); } //player.performCommand(output.trim().substring(1)); } } } catch (Throwable e) { System.err.println(e.getMessage()); player.sendMessage(ChatColor.RED + e.getMessage()); } finally { Static.getAliasCore().removePlayerReference(player); } } }); } catch (/*ConfigRuntimeException*/Throwable e) { System.err.println("An unexpected exception occured: " + e.getClass().getSimpleName()); player.sendMessage("An unexpected exception occured: " + ChatColor.RED + e.getClass().getSimpleName()); e.printStackTrace(); } finally { Static.getAliasCore().removePlayerReference(player); } match = true; break; } } catch (Exception e) { System.err.println("An unexpected exception occured inside the command " + s.toString()); e.printStackTrace(); } } if (player instanceof Player) { if (match == false && playerCommands != null) { //if we are still looking, look in the aliases for this player for (Script ac : playerCommands) { //RunnableAlias b = ac.getRunnableAliases(command, player); try { ac.compile(); if (ac.match(command)) { Static.getAliasCore().addPlayerReference(player); try { ac.run(ac.getVariables(command), player, new MScriptComplete() { public void done(String output) { if (output != null) { if (!output.trim().equals("") && output.trim().startsWith("/")) { if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player)player).getName() + ": " + output.trim()); } ((Player)player).chat(output.trim()); } } Static.getAliasCore().removePlayerReference(player); } }); } catch (/*ConfigRuntimeException*/Throwable e) { System.err.println(e.getMessage()); player.sendMessage(ChatColor.RED + e.getMessage()); Static.getAliasCore().removePlayerReference(player); } match = true; } } catch (Exception e) { ((Player)player).chat("An exception occured while trying to compile/run your alias: " + e.getMessage()); } } } } } catch (Throwable e) { throw new InternalException("An error occured in the CommandHelper plugin: " + e.getMessage() + Arrays.asList(e.getStackTrace())); } return match; } /** * Loads the global alias file in from */ public final boolean reload() throws ConfigCompileException { boolean is_loaded = false; try { IncludeCache.clearCache(); //Clear the include cache, so it re-pulls files if (!aliasConfig.exists()) { aliasConfig.getParentFile().mkdirs(); aliasConfig.createNewFile(); try { file_put_contents(aliasConfig, getStringResource(AliasCore.class.getResourceAsStream("/samp_config.txt")), "o"); } catch (Exception e) { logger.log(Level.WARNING, "CommandHelper: Could not write sample config file"); } } Preferences prefs = Static.getPreferences(); prefs.init(prefFile); String alias_config = file_get_contents(aliasConfig.getAbsolutePath()); //get the file again //config = new AliasConfig(alias_config, null, perms); scripts = MScriptCompiler.preprocess(MScriptCompiler.lex(alias_config, aliasConfig)); for (Script s : scripts) { try { s.compile(); s.checkAmbiguous((ArrayList<Script>) scripts); } catch (ConfigCompileException e) { logger.log(Level.SEVERE, "[CommandHelper]: " + e.toString() + "\nCompilation will continue."); } } int errors = 0; for (Script s : scripts) { if (s.compilerError) { errors++; } } if (errors > 0) { System.out.println("[CommandHelper]: " + (scripts.size() - errors) + " alias(es) defined, with " + errors + " aliases with compile errors."); } else { System.out.println("[CommandHelper]: " + scripts.size() + " alias(es) defined."); } is_loaded = true; } catch (ConfigCompileException ex) { logger.log(Level.SEVERE, "CommandHelper: " + ex.toString()); } catch (IOException ex) { logger.log(Level.SEVERE, "CommandHelper: Path to config file is not correct/accessable. Please" + " check the location and try loading the plugin again."); } catch (Throwable t) { t.printStackTrace(); } return is_loaded; } // public ArrayList<AliasConfig> parse_user_config(ArrayList<String> config, User u) throws ConfigCompileException { // if (config == null) { // return null; // } // ArrayList<AliasConfig> alac = new ArrayList<AliasConfig>(); // for (int i = 0; i < config.size(); i++) { // alac.add(new AliasConfig(config.get(i), u, perms)); // } // return alac; // } /** * Returns the contents of a file as a string. Accepts the file location * as a string. * @param file_location * @return the contents of the file as a string * @throws Exception if the file cannot be found */ public static String file_get_contents(String file_location) throws IOException { BufferedReader in = new BufferedReader(new FileReader(file_location)); String ret = ""; String str; while ((str = in.readLine()) != null) { ret += str + "\n"; } in.close(); return ret; } /** * This function writes the contents of a string to a file. * @param file_location the location of the file on the disk * @param contents the string to be written to the file * @param mode the mode in which to write the file: <br /> * <ul> * <li>"o" - overwrite the file if it exists, without asking</li> * <li>"a" - append to the file if it exists, without asking</li> * <li>"c" - cancel the operation if the file exists, without asking</li> * </ul> * @return true if the file was written, false if it wasn't. Throws an exception * if the file could not be created, or if the mode is not valid. * @throws Exception if the file could not be created */ public static boolean file_put_contents(File file_location, String contents, String mode) throws Exception { BufferedWriter out = null; File f = file_location; if (f.exists()) { //do different things depending on our mode if (mode.equalsIgnoreCase("o")) { out = new BufferedWriter(new FileWriter(file_location)); } else if (mode.equalsIgnoreCase("a")) { out = new BufferedWriter(new FileWriter(file_location, true)); } else if (mode.equalsIgnoreCase("c")) { return false; } else { throw new RuntimeException("Undefined mode in file_put_contents: " + mode); } } else { out = new BufferedWriter(new FileWriter(file_location)); } //At this point, we are assured that the file is open, and ready to be written in //from this point in the file. if (out != null) { out.write(contents); out.close(); return true; } else { return false; } } public static String getStringResource(InputStream is) throws IOException { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is)); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { if (is != null) { is.close(); } } return writer.toString(); } public void removePlayerReference(CommandSender p) { //If they're not a player, oh well. if (p instanceof Player) { echoCommand.remove(((Player) p).getName()); } } public void addPlayerReference(CommandSender p) { if (p instanceof Player) { echoCommand.add(((Player) p).getName()); } } }
true
true
public boolean alias(String command, final CommandSender player, ArrayList<Script> playerCommands) { if (scripts == null) { throw new ConfigRuntimeException("Cannot run alias commands, no config file is loaded", 0, null); } boolean match = false; try { //catch RuntimeException //If player is null, we are running the test harness, so don't //actually add the player to the array. if (player != null && player instanceof Player && echoCommand.contains(((Player) player).getName())) { //we are running one of the expanded commands, so exit with false return false; } //Global aliases override personal ones, so check the list first //a = config.getRunnableAliases(command, player); for (Script s : scripts) { try { if (s.match(command)) { this.addPlayerReference(player); if ((Boolean) Static.getPreferences().getPreference("console-log-commands")) { Static.getLogger().log(Level.INFO, "CH: Running original command ----> " + command); if (player instanceof Player) { Static.getLogger().log(Level.INFO, "on player " + ((Player) player).getName()); } else { Static.getLogger().log(Level.INFO, "from a CommandSender"); } } try { s.run(s.getVariables(command), player, new MScriptComplete() { public void done(String output) { try { if (output != null) { if (!output.trim().equals("") && output.trim().startsWith("/")) { if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { if (player instanceof Player) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) player).getName() + ": " + output.trim()); } else { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + output.trim()); } } //Sometimes bukkit works with one version of this, sometimes with the other. performCommand would be prefered, but //chat works more often, because chat actually triggers a CommandPreprocessEvent, unlike performCommand. if (player instanceof Player) { ((Player) player).chat(output.trim()); } else { Static.getServer().dispatchCommand(player, output.trim()); } //player.performCommand(output.trim().substring(1)); } } } catch (Throwable e) { System.err.println(e.getMessage()); player.sendMessage(ChatColor.RED + e.getMessage()); } finally { Static.getAliasCore().removePlayerReference(player); } } }); } catch (/*ConfigRuntimeException*/Throwable e) { System.err.println("An unexpected exception occured: " + e.getClass().getSimpleName()); player.sendMessage("An unexpected exception occured: " + ChatColor.RED + e.getClass().getSimpleName()); e.printStackTrace(); } finally { Static.getAliasCore().removePlayerReference(player); } match = true; break; } } catch (Exception e) { System.err.println("An unexpected exception occured inside the command " + s.toString()); e.printStackTrace(); } } if (player instanceof Player) { if (match == false && playerCommands != null) { //if we are still looking, look in the aliases for this player for (Script ac : playerCommands) { //RunnableAlias b = ac.getRunnableAliases(command, player); try { ac.compile(); if (ac.match(command)) { Static.getAliasCore().addPlayerReference(player); try { ac.run(ac.getVariables(command), player, new MScriptComplete() { public void done(String output) { if (output != null) { if (!output.trim().equals("") && output.trim().startsWith("/")) { if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player)player).getName() + ": " + output.trim()); } ((Player)player).chat(output.trim()); } } Static.getAliasCore().removePlayerReference(player); } }); } catch (/*ConfigRuntimeException*/Throwable e) { System.err.println(e.getMessage()); player.sendMessage(ChatColor.RED + e.getMessage()); Static.getAliasCore().removePlayerReference(player); } match = true; } } catch (Exception e) { ((Player)player).chat("An exception occured while trying to compile/run your alias: " + e.getMessage()); } } } } } catch (Throwable e) { throw new InternalException("An error occured in the CommandHelper plugin: " + e.getMessage() + Arrays.asList(e.getStackTrace())); } return match; }
public boolean alias(String command, final CommandSender player, ArrayList<Script> playerCommands) { if (scripts == null) { throw new ConfigRuntimeException("Cannot run alias commands, no config file is loaded", 0, null); } boolean match = false; try { //catch RuntimeException //If player is null, we are running the test harness, so don't //actually add the player to the array. if (player != null && player instanceof Player && echoCommand.contains(((Player) player).getName())) { //we are running one of the expanded commands, so exit with false return false; } //Global aliases override personal ones, so check the list first //a = config.getRunnableAliases(command, player); for (Script s : scripts) { try { if (s.match(command)) { this.addPlayerReference(player); if ((Boolean) Static.getPreferences().getPreference("console-log-commands")) { Static.getLogger().log(Level.INFO, "CH: Running original command ----> " + command); if (player instanceof Player) { Static.getLogger().log(Level.INFO, "on player " + ((Player) player).getName()); } else { Static.getLogger().log(Level.INFO, "from a CommandSender"); } } try { s.run(s.getVariables(command), player, new MScriptComplete() { public void done(String output) { try { if (output != null) { if (!output.trim().equals("") && output.trim().startsWith("/")) { if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { if (player instanceof Player) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player) player).getName() + ": " + output.trim()); } else { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + output.trim()); } } //Sometimes bukkit works with one version of this, sometimes with the other. performCommand would be prefered, but //chat works more often, because chat actually triggers a CommandPreprocessEvent, unlike performCommand. if (player instanceof Player) { ((Player) player).chat(output.trim()); } else { Static.getServer().dispatchCommand(player, output.trim().substring(1)); } //player.performCommand(output.trim().substring(1)); } } } catch (Throwable e) { System.err.println(e.getMessage()); player.sendMessage(ChatColor.RED + e.getMessage()); } finally { Static.getAliasCore().removePlayerReference(player); } } }); } catch (/*ConfigRuntimeException*/Throwable e) { System.err.println("An unexpected exception occured: " + e.getClass().getSimpleName()); player.sendMessage("An unexpected exception occured: " + ChatColor.RED + e.getClass().getSimpleName()); e.printStackTrace(); } finally { Static.getAliasCore().removePlayerReference(player); } match = true; break; } } catch (Exception e) { System.err.println("An unexpected exception occured inside the command " + s.toString()); e.printStackTrace(); } } if (player instanceof Player) { if (match == false && playerCommands != null) { //if we are still looking, look in the aliases for this player for (Script ac : playerCommands) { //RunnableAlias b = ac.getRunnableAliases(command, player); try { ac.compile(); if (ac.match(command)) { Static.getAliasCore().addPlayerReference(player); try { ac.run(ac.getVariables(command), player, new MScriptComplete() { public void done(String output) { if (output != null) { if (!output.trim().equals("") && output.trim().startsWith("/")) { if ((Boolean) Static.getPreferences().getPreference("debug-mode")) { Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((Player)player).getName() + ": " + output.trim()); } ((Player)player).chat(output.trim()); } } Static.getAliasCore().removePlayerReference(player); } }); } catch (/*ConfigRuntimeException*/Throwable e) { System.err.println(e.getMessage()); player.sendMessage(ChatColor.RED + e.getMessage()); Static.getAliasCore().removePlayerReference(player); } match = true; } } catch (Exception e) { ((Player)player).chat("An exception occured while trying to compile/run your alias: " + e.getMessage()); } } } } } catch (Throwable e) { throw new InternalException("An error occured in the CommandHelper plugin: " + e.getMessage() + Arrays.asList(e.getStackTrace())); } return match; }
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/JerichoParserWrapper.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/JerichoParserWrapper.java index 50b7f0fc8..ba723ddff 100644 --- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/JerichoParserWrapper.java +++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/JerichoParserWrapper.java @@ -1,155 +1,155 @@ /* * Autopsy Forensic Browser * * Copyright 2012 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.keywordsearch; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import org.sleuthkit.autopsy.coreutils.Logger; import net.htmlparser.jericho.Attributes; import net.htmlparser.jericho.Renderer; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.StartTag; import net.htmlparser.jericho.StartTagType; /** * Uses Jericho HTML Parser to create a Reader for output, consisting of * the text, comments, tag attributes, and other important information * found in the HTML. */ public class JerichoParserWrapper { private static final Logger logger = Logger.getLogger(JerichoParserWrapper.class.getName()); private InputStream in; private StringBuilder out; private Reader reader; JerichoParserWrapper(InputStream in) { this.in = in; } /** * Returns the reader, initialized in parse(), which will be * null if parse() is not called or if parse() throws an error. * @return Reader */ public Reader getReader() { return reader; } /** * Initialize the reader by parsing the InputStream, adding it to StringBuilder, * and creating a StringReader from it. */ public void parse() { out = new StringBuilder(); try { Source source = new Source(in); source.fullSequentialParse(); String text; StringBuilder scripts = new StringBuilder(); StringBuilder links = new StringBuilder(); StringBuilder images = new StringBuilder(); StringBuilder comments = new StringBuilder(); StringBuilder others = new StringBuilder(); int numScripts = 1; int numLinks = 1; int numImages = 1; int numComments = 1; int numOthers = 1; text = renderHTMLAsPlainText(source); // Get all the tags in the source List<StartTag> tags = source.getAllStartTags(); for(StartTag tag : tags) { if(tag.getName().equals("script")) { // If the <script> tag has attributes scripts.append(numScripts).append(") "); if(tag.getTagContent().length()>0) { scripts.append(tag.getTagContent()).append(" "); } // Get whats between the <script> .. </script> tags scripts.append(tag.getElement().getContent()).append("\n"); numScripts++; } else if(tag.getName().equals("a")) { links.append(numLinks).append(") "); links.append(tag.getTagContent()).append("\n"); numLinks++; } else if(tag.getName().equals("img")) { images.append(numImages).append(") "); images.append(tag.getTagContent()).append("\n"); numImages++; } else if(tag.getTagType().equals(StartTagType.COMMENT)) { comments.append(numComments).append(") "); comments.append(tag.getTagContent()).append("\n"); numComments++; } else { // Make sure it has an attribute Attributes atts = tag.getAttributes(); if (atts!=null && atts.length()>0) { others.append(numOthers).append(") "); others.append(tag.getName()).append(":"); others.append(tag.getTagContent()).append("\n"); numOthers++; } } } - out.append(text).append("\n"); + out.append(text).append("\n\n"); out.append("----------NONVISIBLE TEXT----------\n\n"); if(numScripts>1) { out.append("---Scripts---\n"); out.append(scripts.toString()).append("\n"); } if(numLinks>1) { out.append("---Links---\n"); out.append(links.toString()).append("\n"); } if(numImages>1) { out.append("---Images---\n"); out.append(images.toString()).append("\n"); } if(numComments>1) { out.append("---Comments---\n"); out.append(comments.toString()).append("\n"); } if(numOthers>1) { out.append("---Others---\n"); out.append(others.toString()).append("\n"); } // All done, now make it a reader reader = new StringReader(out.toString()); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to parse the HTML file", ex); } } // Extract text from the source, nicely formatted with whitespace and // newlines where appropriate. private String renderHTMLAsPlainText(Source source) { Renderer renderer = source.getRenderer(); renderer.setNewLine("\n"); renderer.setIncludeHyperlinkURLs(false); renderer.setDecorateFontStyles(false); renderer.setIncludeAlternateText(false); return renderer.toString(); } }
true
true
public void parse() { out = new StringBuilder(); try { Source source = new Source(in); source.fullSequentialParse(); String text; StringBuilder scripts = new StringBuilder(); StringBuilder links = new StringBuilder(); StringBuilder images = new StringBuilder(); StringBuilder comments = new StringBuilder(); StringBuilder others = new StringBuilder(); int numScripts = 1; int numLinks = 1; int numImages = 1; int numComments = 1; int numOthers = 1; text = renderHTMLAsPlainText(source); // Get all the tags in the source List<StartTag> tags = source.getAllStartTags(); for(StartTag tag : tags) { if(tag.getName().equals("script")) { // If the <script> tag has attributes scripts.append(numScripts).append(") "); if(tag.getTagContent().length()>0) { scripts.append(tag.getTagContent()).append(" "); } // Get whats between the <script> .. </script> tags scripts.append(tag.getElement().getContent()).append("\n"); numScripts++; } else if(tag.getName().equals("a")) { links.append(numLinks).append(") "); links.append(tag.getTagContent()).append("\n"); numLinks++; } else if(tag.getName().equals("img")) { images.append(numImages).append(") "); images.append(tag.getTagContent()).append("\n"); numImages++; } else if(tag.getTagType().equals(StartTagType.COMMENT)) { comments.append(numComments).append(") "); comments.append(tag.getTagContent()).append("\n"); numComments++; } else { // Make sure it has an attribute Attributes atts = tag.getAttributes(); if (atts!=null && atts.length()>0) { others.append(numOthers).append(") "); others.append(tag.getName()).append(":"); others.append(tag.getTagContent()).append("\n"); numOthers++; } } } out.append(text).append("\n"); out.append("----------NONVISIBLE TEXT----------\n\n"); if(numScripts>1) { out.append("---Scripts---\n"); out.append(scripts.toString()).append("\n"); } if(numLinks>1) { out.append("---Links---\n"); out.append(links.toString()).append("\n"); } if(numImages>1) { out.append("---Images---\n"); out.append(images.toString()).append("\n"); } if(numComments>1) { out.append("---Comments---\n"); out.append(comments.toString()).append("\n"); } if(numOthers>1) { out.append("---Others---\n"); out.append(others.toString()).append("\n"); } // All done, now make it a reader reader = new StringReader(out.toString()); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to parse the HTML file", ex); } }
public void parse() { out = new StringBuilder(); try { Source source = new Source(in); source.fullSequentialParse(); String text; StringBuilder scripts = new StringBuilder(); StringBuilder links = new StringBuilder(); StringBuilder images = new StringBuilder(); StringBuilder comments = new StringBuilder(); StringBuilder others = new StringBuilder(); int numScripts = 1; int numLinks = 1; int numImages = 1; int numComments = 1; int numOthers = 1; text = renderHTMLAsPlainText(source); // Get all the tags in the source List<StartTag> tags = source.getAllStartTags(); for(StartTag tag : tags) { if(tag.getName().equals("script")) { // If the <script> tag has attributes scripts.append(numScripts).append(") "); if(tag.getTagContent().length()>0) { scripts.append(tag.getTagContent()).append(" "); } // Get whats between the <script> .. </script> tags scripts.append(tag.getElement().getContent()).append("\n"); numScripts++; } else if(tag.getName().equals("a")) { links.append(numLinks).append(") "); links.append(tag.getTagContent()).append("\n"); numLinks++; } else if(tag.getName().equals("img")) { images.append(numImages).append(") "); images.append(tag.getTagContent()).append("\n"); numImages++; } else if(tag.getTagType().equals(StartTagType.COMMENT)) { comments.append(numComments).append(") "); comments.append(tag.getTagContent()).append("\n"); numComments++; } else { // Make sure it has an attribute Attributes atts = tag.getAttributes(); if (atts!=null && atts.length()>0) { others.append(numOthers).append(") "); others.append(tag.getName()).append(":"); others.append(tag.getTagContent()).append("\n"); numOthers++; } } } out.append(text).append("\n\n"); out.append("----------NONVISIBLE TEXT----------\n\n"); if(numScripts>1) { out.append("---Scripts---\n"); out.append(scripts.toString()).append("\n"); } if(numLinks>1) { out.append("---Links---\n"); out.append(links.toString()).append("\n"); } if(numImages>1) { out.append("---Images---\n"); out.append(images.toString()).append("\n"); } if(numComments>1) { out.append("---Comments---\n"); out.append(comments.toString()).append("\n"); } if(numOthers>1) { out.append("---Others---\n"); out.append(others.toString()).append("\n"); } // All done, now make it a reader reader = new StringReader(out.toString()); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to parse the HTML file", ex); } }
diff --git a/src/vm/jvm/runtime/org/perl6/nqp/runtime/StaticCodeInfo.java b/src/vm/jvm/runtime/org/perl6/nqp/runtime/StaticCodeInfo.java index 15d642fa3..557b1fa7d 100644 --- a/src/vm/jvm/runtime/org/perl6/nqp/runtime/StaticCodeInfo.java +++ b/src/vm/jvm/runtime/org/perl6/nqp/runtime/StaticCodeInfo.java @@ -1,207 +1,207 @@ package org.perl6.nqp.runtime; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.HashMap; import org.perl6.nqp.sixmodel.SixModelObject; public class StaticCodeInfo implements Cloneable { /** * The compilation unit where the code lives. */ public CompilationUnit compUnit; /** * Method handle for the code ref. */ MethodHandle mh; /** * The expected arguments needed to invoke the method handle. */ public short argsExpectation; /** * Curried method handle for resuming. */ MethodHandle mhResume; /** * Method name for correlation with stack traces. */ public String methodName; /** * The compilation-unit unique ID of the routine (from QAST cuuid). */ public String uniqueId; /** * Static outer. */ public StaticCodeInfo outerStaticInfo; /** * Most recent invocation, if any. */ public CallFrame priorInvocation; /** * Static lexicals. */ public SixModelObject[] oLexStatic; /** * Flags for each static lexical usage. */ public byte[] oLexStaticFlags; /** * Names of the lexicals we have of each of the base types. */ public String[] oLexicalNames; public String[] iLexicalNames; public String[] nLexicalNames; public String[] sLexicalNames; /** * Map of handlers. */ public long[][] handlers; /** * Static code object (base of any clones). */ public SixModelObject staticCode; /** * Lexical name maps (produced lazily on first use). Note they are only * used when we do lexical lookup by name. */ public HashMap<String, Integer> oLexicalMap; public HashMap<String, Integer> iLexicalMap; public HashMap<String, Integer> nLexicalMap; public HashMap<String, Integer> sLexicalMap; /** * Does this code object have a block exit handler? */ public boolean hasExitHandler; public Integer oTryGetLexicalIdx(String name) { if (oLexicalNames != null) { if (oLexicalMap == null) { HashMap<String, Integer> map = new HashMap<String, Integer>(oLexicalNames.length); for (int i = 0; i < oLexicalNames.length; i++) map.put(oLexicalNames[i], i); oLexicalMap = map; } return oLexicalMap.get(name); } else { return null; } } public Integer iTryGetLexicalIdx(String name) { if (iLexicalNames != null) { if (iLexicalMap == null) { HashMap<String, Integer> map = new HashMap<String, Integer>(iLexicalNames.length); for (int i = 0; i < iLexicalNames.length; i++) map.put(iLexicalNames[i], i); iLexicalMap = map; } return iLexicalMap.get(name); } else { return null; } } public Integer nTryGetLexicalIdx(String name) { if (nLexicalNames != null) { if (nLexicalMap == null) { HashMap<String, Integer> map = new HashMap<String, Integer>(nLexicalNames.length); for (int i = 0; i < nLexicalNames.length; i++) map.put(nLexicalNames[i], i); nLexicalMap = map; } return nLexicalMap.get(name); } else { return null; } } public Integer sTryGetLexicalIdx(String name) { if (sLexicalNames != null) { if (sLexicalMap == null) { HashMap<String, Integer> map = new HashMap<String, Integer>(sLexicalNames.length); for (int i = 0; i < sLexicalNames.length; i++) map.put(sLexicalNames[i], i); sLexicalMap = map; } return sLexicalMap.get(name); } else { return null; } } /** * Initializes the static code info data structure. */ public StaticCodeInfo(CompilationUnit compUnit, MethodHandle mh, String uniqueId, String[] oLexicalNames, String[] iLexicalNames, String[] nLexicalNames, String[] sLexicalNames, long[][] handlers, SixModelObject staticCode, short argsExpectation) { this.compUnit = compUnit; this.mh = mh; this.uniqueId = uniqueId; this.oLexicalNames = oLexicalNames; this.iLexicalNames = iLexicalNames; this.nLexicalNames = nLexicalNames; this.sLexicalNames = sLexicalNames; this.handlers = handlers; this.staticCode = staticCode; if (oLexicalNames != null) { this.oLexStatic = new SixModelObject[oLexicalNames.length]; this.oLexStaticFlags = new byte[oLexicalNames.length]; } this.argsExpectation = argsExpectation; MethodType t = mh.type(); if (t.parameterCount() == 5 && (t.parameterType(4) == ResumeStatus.Frame.class)) { /* Old way; goes away after bootstrap. */ mhResume = MethodHandles.insertArguments(mh, 0, null, null, null, null); this.mh = MethodHandles.insertArguments(mh, 4, (Object)null); } - else if (t.parameterCount() == 5 && (t.parameterType(3) == ResumeStatus.Frame.class)) { + else if (t.parameterCount() >= 4 && (t.parameterType(3) == ResumeStatus.Frame.class)) { mhResume = MethodHandles.insertArguments(mh, 0, null, null, null); switch (argsExpectation) { case ArgsExpectation.USE_BINDER: mhResume = MethodHandles.insertArguments(mhResume, 1, (Object)null); break; case ArgsExpectation.NO_ARGS: /* Nothing to insert. */ break; default: throw new RuntimeException("Unhandled ArgsExpectation in StaticCodeInfo"); } this.mh = MethodHandles.insertArguments(mh, 3, (Object)null); } } public StaticCodeInfo clone() { try { StaticCodeInfo result = (StaticCodeInfo)super.clone(); if (result.oLexStatic != null) { result.oLexStatic = result.oLexStatic.clone(); result.oLexStaticFlags = result.oLexStaticFlags.clone(); } return result; } catch (Exception e) { throw new RuntimeException(e); } } }
true
true
public StaticCodeInfo(CompilationUnit compUnit, MethodHandle mh, String uniqueId, String[] oLexicalNames, String[] iLexicalNames, String[] nLexicalNames, String[] sLexicalNames, long[][] handlers, SixModelObject staticCode, short argsExpectation) { this.compUnit = compUnit; this.mh = mh; this.uniqueId = uniqueId; this.oLexicalNames = oLexicalNames; this.iLexicalNames = iLexicalNames; this.nLexicalNames = nLexicalNames; this.sLexicalNames = sLexicalNames; this.handlers = handlers; this.staticCode = staticCode; if (oLexicalNames != null) { this.oLexStatic = new SixModelObject[oLexicalNames.length]; this.oLexStaticFlags = new byte[oLexicalNames.length]; } this.argsExpectation = argsExpectation; MethodType t = mh.type(); if (t.parameterCount() == 5 && (t.parameterType(4) == ResumeStatus.Frame.class)) { /* Old way; goes away after bootstrap. */ mhResume = MethodHandles.insertArguments(mh, 0, null, null, null, null); this.mh = MethodHandles.insertArguments(mh, 4, (Object)null); } else if (t.parameterCount() == 5 && (t.parameterType(3) == ResumeStatus.Frame.class)) { mhResume = MethodHandles.insertArguments(mh, 0, null, null, null); switch (argsExpectation) { case ArgsExpectation.USE_BINDER: mhResume = MethodHandles.insertArguments(mhResume, 1, (Object)null); break; case ArgsExpectation.NO_ARGS: /* Nothing to insert. */ break; default: throw new RuntimeException("Unhandled ArgsExpectation in StaticCodeInfo"); } this.mh = MethodHandles.insertArguments(mh, 3, (Object)null); } }
public StaticCodeInfo(CompilationUnit compUnit, MethodHandle mh, String uniqueId, String[] oLexicalNames, String[] iLexicalNames, String[] nLexicalNames, String[] sLexicalNames, long[][] handlers, SixModelObject staticCode, short argsExpectation) { this.compUnit = compUnit; this.mh = mh; this.uniqueId = uniqueId; this.oLexicalNames = oLexicalNames; this.iLexicalNames = iLexicalNames; this.nLexicalNames = nLexicalNames; this.sLexicalNames = sLexicalNames; this.handlers = handlers; this.staticCode = staticCode; if (oLexicalNames != null) { this.oLexStatic = new SixModelObject[oLexicalNames.length]; this.oLexStaticFlags = new byte[oLexicalNames.length]; } this.argsExpectation = argsExpectation; MethodType t = mh.type(); if (t.parameterCount() == 5 && (t.parameterType(4) == ResumeStatus.Frame.class)) { /* Old way; goes away after bootstrap. */ mhResume = MethodHandles.insertArguments(mh, 0, null, null, null, null); this.mh = MethodHandles.insertArguments(mh, 4, (Object)null); } else if (t.parameterCount() >= 4 && (t.parameterType(3) == ResumeStatus.Frame.class)) { mhResume = MethodHandles.insertArguments(mh, 0, null, null, null); switch (argsExpectation) { case ArgsExpectation.USE_BINDER: mhResume = MethodHandles.insertArguments(mhResume, 1, (Object)null); break; case ArgsExpectation.NO_ARGS: /* Nothing to insert. */ break; default: throw new RuntimeException("Unhandled ArgsExpectation in StaticCodeInfo"); } this.mh = MethodHandles.insertArguments(mh, 3, (Object)null); } }
diff --git a/portal-lite/src/main/java/de/offis/europeana/mobile/DeviceRecognitionInterceptor.java b/portal-lite/src/main/java/de/offis/europeana/mobile/DeviceRecognitionInterceptor.java index 69426366..02e278b6 100644 --- a/portal-lite/src/main/java/de/offis/europeana/mobile/DeviceRecognitionInterceptor.java +++ b/portal-lite/src/main/java/de/offis/europeana/mobile/DeviceRecognitionInterceptor.java @@ -1,68 +1,68 @@ /* * Copyright 2007 EDL FOUNDATION * * Licensed under the EUPL, Version 1.0 or? as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * you may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ package de.offis.europeana.mobile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This class is meant to be used as an interceptor. * It uses the DeviceRecognition to modify the ViewName to a template * that is best suited for a mobile device's capabilities. * * @author Dennis Heinen <[email protected]> */ public class DeviceRecognitionInterceptor extends HandlerInterceptorAdapter { @Autowired private DeviceRecognition deviceRecognition; /* * modifies the ViewName to a template that is best suited for a mobile device's capabilities. * Information about the device's screen width & height is added to ModelAndView * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) */ @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { super.postHandle(httpServletRequest, httpServletResponse, o, modelAndView); if (deviceRecognition != null) { String currentViewName = modelAndView.getViewName(); - if (currentViewName != null) { + if (currentViewName != null && !currentViewName.startsWith("redirect:")) { DeviceRecognitionResult deviceRecognitionResult = deviceRecognition.getDeviceInformation(httpServletRequest, currentViewName); if (deviceRecognitionResult != null) { modelAndView.setViewName(deviceRecognitionResult.GetTemplateName()); modelAndView.addObject("device_screen_width", deviceRecognitionResult.GetDeviceScreenWidth()); modelAndView.addObject("device_screen_height", deviceRecognitionResult.GetDeviceScreenHeight()); modelAndView.addObject("coverflow_enabled", deviceRecognitionResult.GetCoverflowEnabled()); modelAndView.addObject("is_IEMobile", deviceRecognitionResult.GetIsIEMobile()); } } } } }
true
true
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { super.postHandle(httpServletRequest, httpServletResponse, o, modelAndView); if (deviceRecognition != null) { String currentViewName = modelAndView.getViewName(); if (currentViewName != null) { DeviceRecognitionResult deviceRecognitionResult = deviceRecognition.getDeviceInformation(httpServletRequest, currentViewName); if (deviceRecognitionResult != null) { modelAndView.setViewName(deviceRecognitionResult.GetTemplateName()); modelAndView.addObject("device_screen_width", deviceRecognitionResult.GetDeviceScreenWidth()); modelAndView.addObject("device_screen_height", deviceRecognitionResult.GetDeviceScreenHeight()); modelAndView.addObject("coverflow_enabled", deviceRecognitionResult.GetCoverflowEnabled()); modelAndView.addObject("is_IEMobile", deviceRecognitionResult.GetIsIEMobile()); } } } }
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { super.postHandle(httpServletRequest, httpServletResponse, o, modelAndView); if (deviceRecognition != null) { String currentViewName = modelAndView.getViewName(); if (currentViewName != null && !currentViewName.startsWith("redirect:")) { DeviceRecognitionResult deviceRecognitionResult = deviceRecognition.getDeviceInformation(httpServletRequest, currentViewName); if (deviceRecognitionResult != null) { modelAndView.setViewName(deviceRecognitionResult.GetTemplateName()); modelAndView.addObject("device_screen_width", deviceRecognitionResult.GetDeviceScreenWidth()); modelAndView.addObject("device_screen_height", deviceRecognitionResult.GetDeviceScreenHeight()); modelAndView.addObject("coverflow_enabled", deviceRecognitionResult.GetCoverflowEnabled()); modelAndView.addObject("is_IEMobile", deviceRecognitionResult.GetIsIEMobile()); } } } }
diff --git a/src/java/org/jdesktop/swingx/plaf/windows/WindowsLookAndFeelAddons.java b/src/java/org/jdesktop/swingx/plaf/windows/WindowsLookAndFeelAddons.java index 70a7d79c..b8d48c17 100644 --- a/src/java/org/jdesktop/swingx/plaf/windows/WindowsLookAndFeelAddons.java +++ b/src/java/org/jdesktop/swingx/plaf/windows/WindowsLookAndFeelAddons.java @@ -1,64 +1,63 @@ /* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.plaf.windows; import javax.swing.UIManager; import org.jdesktop.swingx.plaf.basic.BasicLookAndFeelAddons; /** * Adds new pluggable UI following the Windows XP look and feel. */ public class WindowsLookAndFeelAddons extends BasicLookAndFeelAddons { public static final String HOMESTEAD_VISUAL_STYLE = "HomeStead"; public static final String SILVER_VISUAL_STYLE = "Metallic"; public static final String VISTA_VISUAL_STYLE = "NormalColor"; /** * {@inheritDoc} <p> * */ @Override public void initialize() { super.initialize(); // fix Issue #1305-swingx: wrapper for core issue #6753637 // set ui property to prevent eating mousePressed when closing popup - System.out.println(UIManager.getLookAndFeel().getClass().getName() + UIManager.get("PopupMenu.consumeEventOnClose")); UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE); } /** * {@inheritDoc} <p> */ @Override public void uninitialize() { // fix Issue #1305-swingx: wrapper for core issue #6753637 // remove the ui property again UIManager.put("PopupMenu.consumeEventOnClose", null); super.uninitialize(); } }
true
true
public void initialize() { super.initialize(); // fix Issue #1305-swingx: wrapper for core issue #6753637 // set ui property to prevent eating mousePressed when closing popup System.out.println(UIManager.getLookAndFeel().getClass().getName() + UIManager.get("PopupMenu.consumeEventOnClose")); UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE); }
public void initialize() { super.initialize(); // fix Issue #1305-swingx: wrapper for core issue #6753637 // set ui property to prevent eating mousePressed when closing popup UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE); }
diff --git a/Water.java b/Water.java index 4c538f5..69321a6 100644 --- a/Water.java +++ b/Water.java @@ -1,38 +1,38 @@ import greenfoot.*; import javax.swing.JOptionPane; public class Water extends Actor { private int life = 2; public Water() { getImage().scale(10, 10); } public void act() { if (getOneIntersectingObject(Bag.class) != null) { getWorld().addObject(new Floodbank(), getX(), getY()); getWorld().removeObject(this); return; } if (Math.random() > 0.05) return; int dx = 0, dy = 0; switch ((int)(3.0 * Math.random())) { case 0: dx = 0; dy = 1; break; case 1: dx = 1; dy = 0; break; case 2: dx = -1; dy = 0; break; } Actor floodbank = getOneObjectAtOffset(dx, dy, Floodbank.class); if (floodbank == null) return; getWorld().removeObject(floodbank); getWorld().addObject(new Water(), getX() + dx, getY() + dy); Actor meadow = getOneObjectAtOffset(0, 0, Meadow.class); if (meadow == null) return; Greenfoot.stop(); JOptionPane.showMessageDialog(null, "De dijk is doorgebroken!"); - addObject(new GameOverScreen(), 0, 80); + getWorld().addObject(new GameOverScreen(), 0, 80); } }
true
true
public void act() { if (getOneIntersectingObject(Bag.class) != null) { getWorld().addObject(new Floodbank(), getX(), getY()); getWorld().removeObject(this); return; } if (Math.random() > 0.05) return; int dx = 0, dy = 0; switch ((int)(3.0 * Math.random())) { case 0: dx = 0; dy = 1; break; case 1: dx = 1; dy = 0; break; case 2: dx = -1; dy = 0; break; } Actor floodbank = getOneObjectAtOffset(dx, dy, Floodbank.class); if (floodbank == null) return; getWorld().removeObject(floodbank); getWorld().addObject(new Water(), getX() + dx, getY() + dy); Actor meadow = getOneObjectAtOffset(0, 0, Meadow.class); if (meadow == null) return; Greenfoot.stop(); JOptionPane.showMessageDialog(null, "De dijk is doorgebroken!"); addObject(new GameOverScreen(), 0, 80); }
public void act() { if (getOneIntersectingObject(Bag.class) != null) { getWorld().addObject(new Floodbank(), getX(), getY()); getWorld().removeObject(this); return; } if (Math.random() > 0.05) return; int dx = 0, dy = 0; switch ((int)(3.0 * Math.random())) { case 0: dx = 0; dy = 1; break; case 1: dx = 1; dy = 0; break; case 2: dx = -1; dy = 0; break; } Actor floodbank = getOneObjectAtOffset(dx, dy, Floodbank.class); if (floodbank == null) return; getWorld().removeObject(floodbank); getWorld().addObject(new Water(), getX() + dx, getY() + dy); Actor meadow = getOneObjectAtOffset(0, 0, Meadow.class); if (meadow == null) return; Greenfoot.stop(); JOptionPane.showMessageDialog(null, "De dijk is doorgebroken!"); getWorld().addObject(new GameOverScreen(), 0, 80); }
diff --git a/src/com/java/phondeux/team/Team.java b/src/com/java/phondeux/team/Team.java index 0946197..10c338e 100644 --- a/src/com/java/phondeux/team/Team.java +++ b/src/com/java/phondeux/team/Team.java @@ -1,134 +1,134 @@ package com.java.phondeux.team; import java.sql.SQLException; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.event.Event; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; /** * Team for Bukkit * * @author Phondeux */ public class Team extends JavaPlugin{ protected Logger log; protected ConnectionManager cm; protected TeamHandler th; public EventHandler eh; protected StatsHandler sh; private final TeamPlayerListener playerListener = new TeamPlayerListener(this); private final TeamEntityListener entityListener = new TeamEntityListener(this); private final TeamCommand teamCommand = new TeamCommand(this); @Override public void onDisable() { System.out.println("[team] disabled"); } @SuppressWarnings("deprecation") @Override public void onEnable() { log = Logger.getLogger("Minecraft"); getCommand("team").setExecutor(teamCommand); getCommand("tc").setExecutor(teamCommand); PluginManager pm = getServer().getPluginManager(); pm.registerEvent(Event.Type.PLAYER_JOIN, this.playerListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_QUIT, this.playerListener, Event.Priority.Monitor, this); pm.registerEvent(Event.Type.ENTITY_DEATH, this.entityListener, Event.Priority.Monitor, this); pm.registerEvent(Event.Type.ENTITY_DAMAGE, this.entityListener, Event.Priority.Monitor, this); pm.registerEvent(Event.Type.PLAYER_CHAT, this.playerListener, Event.Priority.Normal, this); initialize(); PluginDescriptionFile pdfFile = this.getDescription(); System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" ); } private void initialize() { try { log.info("[Team] Connecting to database.."); cm = new ConnectionManager("localhost/teamdata", "teamuser", "teampass"); log.info("[Team] Initializing TeamHandler.."); th = new TeamHandler(this, cm); log.info("[Team] Initializing EventHandler.."); eh = new EventHandler(this, cm); log.info("[Team] Initializing StatsHandler.."); sh = new StatsHandler(this, cm); } catch (SQLException e) { e.printStackTrace(); log.severe("[Team] Initialization failed due to SQLException!"); getPluginLoader().disablePlugin(this); return; } catch (ClassNotFoundException e) { e.printStackTrace(); log.severe("[Team] Initialization failed due to the driver not being found!"); getPluginLoader().disablePlugin(this); return; } initializeEvents(); } private void initializeEvents() { eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " created a new team, " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!"); } }, EventHandler.Type.TeamCreate); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " disbanded the team " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!"); th.teamSendToMembers(child, ChatColor.RED + "disbanded."); } }, EventHandler.Type.TeamDisband); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, TeamUtils.formatTeam(sh.GetTeamStats(child), data)); } }, EventHandler.Type.TeamMotd); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " joined!"); } }, EventHandler.Type.PlayerJoin); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " left!"); } }, EventHandler.Type.PlayerLeave); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is now invited!"); } }, EventHandler.Type.PlayerInvite); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is no longer invited!"); } }, EventHandler.Type.PlayerDeinvite); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " was kicked!"); } }, EventHandler.Type.PlayerKicked); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { - th.teamChatter.remove(parent); + if (th.teamChatter.contains(parent)) th.teamChatter.remove(parent); } }, EventHandler.Type.PlayerDeath); } }
true
true
private void initializeEvents() { eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " created a new team, " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!"); } }, EventHandler.Type.TeamCreate); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " disbanded the team " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!"); th.teamSendToMembers(child, ChatColor.RED + "disbanded."); } }, EventHandler.Type.TeamDisband); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, TeamUtils.formatTeam(sh.GetTeamStats(child), data)); } }, EventHandler.Type.TeamMotd); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " joined!"); } }, EventHandler.Type.PlayerJoin); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " left!"); } }, EventHandler.Type.PlayerLeave); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is now invited!"); } }, EventHandler.Type.PlayerInvite); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is no longer invited!"); } }, EventHandler.Type.PlayerDeinvite); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " was kicked!"); } }, EventHandler.Type.PlayerKicked); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamChatter.remove(parent); } }, EventHandler.Type.PlayerDeath); }
private void initializeEvents() { eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " created a new team, " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!"); } }, EventHandler.Type.TeamCreate); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " disbanded the team " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!"); th.teamSendToMembers(child, ChatColor.RED + "disbanded."); } }, EventHandler.Type.TeamDisband); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, TeamUtils.formatTeam(sh.GetTeamStats(child), data)); } }, EventHandler.Type.TeamMotd); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " joined!"); } }, EventHandler.Type.PlayerJoin); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " left!"); } }, EventHandler.Type.PlayerLeave); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is now invited!"); } }, EventHandler.Type.PlayerInvite); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is no longer invited!"); } }, EventHandler.Type.PlayerDeinvite); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " was kicked!"); } }, EventHandler.Type.PlayerKicked); eh.RegisterCallback(new EventHandler.EventCallback() { public void run(int parent, int child, String data) { if (th.teamChatter.contains(parent)) th.teamChatter.remove(parent); } }, EventHandler.Type.PlayerDeath); }
diff --git a/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java b/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java index 0bb671c82..22b77e270 100644 --- a/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java +++ b/src/realms/welcome-admin/yanel/resources/show-realms/src/java/org/wyona/yanel/impl/resources/ShowRealms.java @@ -1,212 +1,213 @@ /* * Copyright 2006 Wyona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.wyona.org/licenses/APACHE-LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wyona.yanel.impl.resources; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.util.Calendar; import java.io.StringBufferInputStream; //import java.io.StringReader; //import java.util.Enumeration; //import java.util.HashMap; //import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.log4j.Category; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.wyona.yarep.core.NoSuchNodeException; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import org.wyona.yanel.core.Yanel; import org.wyona.yarep.util.RepoPath; import org.wyona.yarep.util.YarepUtil; /** * */ public class ShowRealms extends Resource implements ViewableV2 { private static Category log = Category.getInstance(ShowRealms.class); /** * */ public ShowRealms() { } /** * */ public ViewDescriptor[] getViewDescriptors() { return null; } /** * */ public View getView(String viewId) throws Exception { View defaultView = new View(); defaultView.setMimeType("application/xml"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); defaultView.setInputStream(new java.io.StringBufferInputStream(sb .toString())); String servletContext = request.getContextPath(); Repository contentRepo = getRealm().getRepository(); sb.append("<yanel-info>"); sb.append("<realms>"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { sb.append("<realm>"); sb.append("<name>" + realms[i].getName() + "</name>"); sb.append("<id>" + realms[i].getID() + "</id>"); sb.append("<mountpoint>" + realms[i].getMountPoint() + "</mountpoint>"); //sb.append("<description>" + realms[i].getDescription() + "</description>"); sb.append("</realm>"); } sb.append("</realms>"); sb.append("<resourcetypes>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { sb.append("<resourcetype>"); try { - //String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + "/resource-types/" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; - String rtYanelHtdocPath = PathUtil.getResourcesHtdocsPathURLencoded(this) + yanel.getReservedPrefix() + "/"; + String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + "resource-types/" + rtds[i].getResourceTypeNamespace().replaceAll("/", "%2f").replaceAll(":", "%3a") + "%3a%3a" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; + // TODO: Use utility class + //String rtYanelHtdocPath = PathUtil.getResourcesHtdocsPathURLencoded(ResourceManager.getResource(rtds[i])) + yanel.getReservedPrefix() + "/"; sb.append("<localname>" + rtds[i].getResourceTypeLocalName() + "</localname>"); sb.append("<description>" + rtds[i].getResourceTypeDescription() + "</description>"); sb.append("<icon alt=\"" + rtds[i].getResourceTypeLocalName() + " resource-type\">" + rtYanelHtdocPath + "icons/32x32/rt-icon.png" + "</icon>"); sb.append("<docu>" + rtYanelHtdocPath + "doc/index.html" + "</docu>"); } catch(Exception e) { log.error(e); } sb.append("</resourcetype>"); } sb.append("</resourcetypes>"); sb.append("</yanel-info>"); Transformer transformer = TransformerFactory.newInstance() .newTransformer(getXSLTStreamSource(getPath(), contentRepo)); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("servlet.context", servletContext); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); // TODO: Is this the best way to generate an InputStream from an // OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformer.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType(getMimeType(getPath())); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType("application/xhtml+xml"); return defaultView; } /** * */ private StreamSource getXSLTStreamSource(String path, Repository repo) throws Exception { String xsltPath = getXSLTPath(); if (xsltPath != null) { return new StreamSource(repo .getInputStream(new org.wyona.yarep.core.Path(getXSLTPath()))); } else { File xsltFile = org.wyona.commons.io.FileUtil.file(rtd .getConfigFile().getParentFile().getAbsolutePath(), "xslt" + File.separator + "info2xhtml.xsl"); log.error("DEBUG: XSLT file: " + xsltFile); return new StreamSource(xsltFile); } } /** * */ private String getXSLTPath() throws Exception { return getConfiguration().getProperty("xslt"); //return getRTI().getProperty("xslt"); } /** * */ public String getMimeType(String path) throws Exception { String mimeType = getConfiguration().getProperty("mime-type"); //String mimeType = getRTI().getProperty("mime-type"); if (mimeType == null) mimeType = "application/xhtml+xml"; return mimeType; } /** * */ private String backToRoot(String path, String backToRoot) { String parent = PathUtil.getParent(path); if (parent != null && !isRoot(parent)) { return backToRoot(parent, backToRoot + "../"); } return backToRoot; } /** * */ private boolean isRoot(String path) { if (path.equals(File.separator)) return true; return false; } public boolean exists() throws Exception { // TODO Auto-generated method stub return false; } public long getSize() throws Exception { // TODO Auto-generated method stub return 0; } }
true
true
public View getView(String viewId) throws Exception { View defaultView = new View(); defaultView.setMimeType("application/xml"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); defaultView.setInputStream(new java.io.StringBufferInputStream(sb .toString())); String servletContext = request.getContextPath(); Repository contentRepo = getRealm().getRepository(); sb.append("<yanel-info>"); sb.append("<realms>"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { sb.append("<realm>"); sb.append("<name>" + realms[i].getName() + "</name>"); sb.append("<id>" + realms[i].getID() + "</id>"); sb.append("<mountpoint>" + realms[i].getMountPoint() + "</mountpoint>"); //sb.append("<description>" + realms[i].getDescription() + "</description>"); sb.append("</realm>"); } sb.append("</realms>"); sb.append("<resourcetypes>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { sb.append("<resourcetype>"); try { //String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + "/resource-types/" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; String rtYanelHtdocPath = PathUtil.getResourcesHtdocsPathURLencoded(this) + yanel.getReservedPrefix() + "/"; sb.append("<localname>" + rtds[i].getResourceTypeLocalName() + "</localname>"); sb.append("<description>" + rtds[i].getResourceTypeDescription() + "</description>"); sb.append("<icon alt=\"" + rtds[i].getResourceTypeLocalName() + " resource-type\">" + rtYanelHtdocPath + "icons/32x32/rt-icon.png" + "</icon>"); sb.append("<docu>" + rtYanelHtdocPath + "doc/index.html" + "</docu>"); } catch(Exception e) { log.error(e); } sb.append("</resourcetype>"); } sb.append("</resourcetypes>"); sb.append("</yanel-info>"); Transformer transformer = TransformerFactory.newInstance() .newTransformer(getXSLTStreamSource(getPath(), contentRepo)); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("servlet.context", servletContext); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); // TODO: Is this the best way to generate an InputStream from an // OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformer.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType(getMimeType(getPath())); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType("application/xhtml+xml"); return defaultView; }
public View getView(String viewId) throws Exception { View defaultView = new View(); defaultView.setMimeType("application/xml"); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); defaultView.setInputStream(new java.io.StringBufferInputStream(sb .toString())); String servletContext = request.getContextPath(); Repository contentRepo = getRealm().getRepository(); sb.append("<yanel-info>"); sb.append("<realms>"); Realm[] realms = yanel.getRealmConfiguration().getRealms(); for (int i = 0; i < realms.length; i++) { sb.append("<realm>"); sb.append("<name>" + realms[i].getName() + "</name>"); sb.append("<id>" + realms[i].getID() + "</id>"); sb.append("<mountpoint>" + realms[i].getMountPoint() + "</mountpoint>"); //sb.append("<description>" + realms[i].getDescription() + "</description>"); sb.append("</realm>"); } sb.append("</realms>"); sb.append("<resourcetypes>"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { sb.append("<resourcetype>"); try { String rtYanelHtdocPath = PathUtil.getGlobalHtdocsPath(this) + "resource-types/" + rtds[i].getResourceTypeNamespace().replaceAll("/", "%2f").replaceAll(":", "%3a") + "%3a%3a" + rtds[i].getResourceTypeLocalName() + "/" + yanel.getReservedPrefix() + "/"; // TODO: Use utility class //String rtYanelHtdocPath = PathUtil.getResourcesHtdocsPathURLencoded(ResourceManager.getResource(rtds[i])) + yanel.getReservedPrefix() + "/"; sb.append("<localname>" + rtds[i].getResourceTypeLocalName() + "</localname>"); sb.append("<description>" + rtds[i].getResourceTypeDescription() + "</description>"); sb.append("<icon alt=\"" + rtds[i].getResourceTypeLocalName() + " resource-type\">" + rtYanelHtdocPath + "icons/32x32/rt-icon.png" + "</icon>"); sb.append("<docu>" + rtYanelHtdocPath + "doc/index.html" + "</docu>"); } catch(Exception e) { log.error(e); } sb.append("</resourcetype>"); } sb.append("</resourcetypes>"); sb.append("</yanel-info>"); Transformer transformer = TransformerFactory.newInstance() .newTransformer(getXSLTStreamSource(getPath(), contentRepo)); transformer.setParameter("yanel.path.name", PathUtil.getName(getPath())); transformer.setParameter("servlet.context", servletContext); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", backToRoot(getPath(), "")); transformer.setParameter("yarep.back2realm", backToRoot(getPath(), "")); // TODO: Is this the best way to generate an InputStream from an // OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); transformer.transform(new StreamSource(new java.io.StringBufferInputStream(sb.toString())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType(getMimeType(getPath())); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos .toByteArray())); defaultView.setMimeType("application/xhtml+xml"); return defaultView; }
diff --git a/cadpage/src/net/anei/cadpage/parsers/IN/INWayneCountyParser.java b/cadpage/src/net/anei/cadpage/parsers/IN/INWayneCountyParser.java index 11dc94132..c401be7cc 100644 --- a/cadpage/src/net/anei/cadpage/parsers/IN/INWayneCountyParser.java +++ b/cadpage/src/net/anei/cadpage/parsers/IN/INWayneCountyParser.java @@ -1,108 +1,108 @@ package net.anei.cadpage.parsers.IN; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.parsers.MsgInfo.Data; import net.anei.cadpage.parsers.MsgParser; /* Wayne County, IN Contact: AJ Locker <[email protected]> Sender: [email protected] The 209 is an apartment or room #. In Indiana, a 10-52 is a medical run. A 10-50 is an MVA. For the complete list of Indiana 10 codes visit http://www.n9wp.com/scan/codes.htm. (911) 05/31 20:20 81 S 14TH ST #209 209: Landmark: MERLE HENDERSON APTS E MAIN ST//S A ST 70 Y/O FEMALE.;CONSC AND ALERT. ABLE TO SPEAK. ; DB JUST STARTED. (911) 05/31 19:56 812 NW 5TH ST #LOT 4 10-52: Landmark: HARBOR LIGHTS NW J ST//INDIANA AV FEMALE FELL AGAIN FROM A STANDING POSITION NO LOC SHE IS UP JUST (911) 05/31 18:43 2005 VI POST RD 10-52 DB: TEST RD//SALISBURY RD S 72 Y/O MALE HAS BEEN SICK FOR A FEW DAYS. CONSC AND ALERT. (911) 05/31 16:37 E MAIN ST // WOODSIDE DR 10-50 PI: E MAIN ST // WOODSIDE DR 37TH ST//34TH ST NECK PAIN;STILL IN THE ROAD WAY (911) 06/01 10:29 408 S 10TH ST #D 10-52 DB: S C ST//S E ST 48 Y/O FEMALE. TROUBLE BREATHING HISTORY: COPD (911) 06/01 12:20 1212 S 20TH ST 10-52: Landmark: BETHLEHEM MANOR APARTMENTS S L ST// ACCIDENTAL CUT TO THE HAND..WAITING AT THE ENTRANCE (911) 06/01 13:27 3601 E MAIN ST : Landmark Comment: WALMART PLAZA Landmark: WALMART 37TH ST//34TH ST ;JUST INSIDE THE GROCERY ENTRANCE (911) 06/01 00:00 BEELOR RD // US 27 10-50 UNK: 3081 BEELOR RD S US 27 // LIBERY AV VEH IN THE DITCH NO DESC (911) 06/01 09:43 900 S A ST : Landmark: LELAND RESIDENCE S 10TH ST//S 9TH ST */ public class INWayneCountyParser extends MsgParser { private static final Pattern MASTER = Pattern.compile("(\\d\\d/\\d\\d) (\\d\\d:\\d\\d) ([^:]+): (.*)"); public INWayneCountyParser() { super("WAYNE COUNTY", "IN"); } @Override public String getFilter() { return "[email protected]"; } @Override public boolean parseMsg(String subject, String body, Data data) { if (!subject.equals("911")) return false; Matcher match = MASTER.matcher(body); if (!match.matches()) return false; data.strDate = match.group(1); data.strTime = match.group(2); String sAddr = match.group(3).trim(); String sExtra = match.group(4).trim(); int pt = sAddr.lastIndexOf(" 10-"); if (pt >= 0) { data.strCall = sAddr.substring(pt+1); sAddr = sAddr.substring(0,pt).trim(); } else { data.strCall = "ALERT"; } pt = sAddr.lastIndexOf('#'); if (pt >= 0) { data.strApt = sAddr.substring(pt+1).trim(); sAddr = sAddr.substring(0,pt).trim(); } sAddr = sAddr.replace("//", "&"); parseAddress(sAddr, data); String[] flds = sExtra.split(" +"); int ndx = 0; String fld = flds[ndx]; if (fld.startsWith("Landmark Comment:")) { pt = fld.indexOf(" Landmark:",17); if (pt >= 0) { data.strPlace = append(fld.substring(pt+10).trim(), "-", fld.substring(17,pt).trim()); } else { data.strPlace = fld.substring(17).trim(); } ndx++; } else if (fld.startsWith("Landmark:")) { data.strPlace = fld.substring(9).trim(); ndx++; } boolean loop = false; do { loop = false; fld = flds[ndx].trim(); if (fld.contains("//")) { data.strCross = fld.replace("//", " & ").replaceAll(" +", " "); ndx++; if (data.strAddress.equals(data.strCross)) { data.strCross = ""; loop = true; } } - } while (loop); + } while (loop && ndx<flds.length); for ( ; ndx<flds.length; ndx++) { fld = flds[ndx].trim(); if (fld.startsWith(";")) fld = fld.substring(1).trim(); data.strSupp = append(data.strSupp, " ", fld); } return true; } }
true
true
public boolean parseMsg(String subject, String body, Data data) { if (!subject.equals("911")) return false; Matcher match = MASTER.matcher(body); if (!match.matches()) return false; data.strDate = match.group(1); data.strTime = match.group(2); String sAddr = match.group(3).trim(); String sExtra = match.group(4).trim(); int pt = sAddr.lastIndexOf(" 10-"); if (pt >= 0) { data.strCall = sAddr.substring(pt+1); sAddr = sAddr.substring(0,pt).trim(); } else { data.strCall = "ALERT"; } pt = sAddr.lastIndexOf('#'); if (pt >= 0) { data.strApt = sAddr.substring(pt+1).trim(); sAddr = sAddr.substring(0,pt).trim(); } sAddr = sAddr.replace("//", "&"); parseAddress(sAddr, data); String[] flds = sExtra.split(" +"); int ndx = 0; String fld = flds[ndx]; if (fld.startsWith("Landmark Comment:")) { pt = fld.indexOf(" Landmark:",17); if (pt >= 0) { data.strPlace = append(fld.substring(pt+10).trim(), "-", fld.substring(17,pt).trim()); } else { data.strPlace = fld.substring(17).trim(); } ndx++; } else if (fld.startsWith("Landmark:")) { data.strPlace = fld.substring(9).trim(); ndx++; } boolean loop = false; do { loop = false; fld = flds[ndx].trim(); if (fld.contains("//")) { data.strCross = fld.replace("//", " & ").replaceAll(" +", " "); ndx++; if (data.strAddress.equals(data.strCross)) { data.strCross = ""; loop = true; } } } while (loop); for ( ; ndx<flds.length; ndx++) { fld = flds[ndx].trim(); if (fld.startsWith(";")) fld = fld.substring(1).trim(); data.strSupp = append(data.strSupp, " ", fld); } return true; }
public boolean parseMsg(String subject, String body, Data data) { if (!subject.equals("911")) return false; Matcher match = MASTER.matcher(body); if (!match.matches()) return false; data.strDate = match.group(1); data.strTime = match.group(2); String sAddr = match.group(3).trim(); String sExtra = match.group(4).trim(); int pt = sAddr.lastIndexOf(" 10-"); if (pt >= 0) { data.strCall = sAddr.substring(pt+1); sAddr = sAddr.substring(0,pt).trim(); } else { data.strCall = "ALERT"; } pt = sAddr.lastIndexOf('#'); if (pt >= 0) { data.strApt = sAddr.substring(pt+1).trim(); sAddr = sAddr.substring(0,pt).trim(); } sAddr = sAddr.replace("//", "&"); parseAddress(sAddr, data); String[] flds = sExtra.split(" +"); int ndx = 0; String fld = flds[ndx]; if (fld.startsWith("Landmark Comment:")) { pt = fld.indexOf(" Landmark:",17); if (pt >= 0) { data.strPlace = append(fld.substring(pt+10).trim(), "-", fld.substring(17,pt).trim()); } else { data.strPlace = fld.substring(17).trim(); } ndx++; } else if (fld.startsWith("Landmark:")) { data.strPlace = fld.substring(9).trim(); ndx++; } boolean loop = false; do { loop = false; fld = flds[ndx].trim(); if (fld.contains("//")) { data.strCross = fld.replace("//", " & ").replaceAll(" +", " "); ndx++; if (data.strAddress.equals(data.strCross)) { data.strCross = ""; loop = true; } } } while (loop && ndx<flds.length); for ( ; ndx<flds.length; ndx++) { fld = flds[ndx].trim(); if (fld.startsWith(";")) fld = fld.substring(1).trim(); data.strSupp = append(data.strSupp, " ", fld); } return true; }
diff --git a/src/main/java/org/osaf/cosmo/jackrabbit/io/ExportCalendarCollectionCommand.java b/src/main/java/org/osaf/cosmo/jackrabbit/io/ExportCalendarCollectionCommand.java index 5ea16a7f1..4ebf979bc 100644 --- a/src/main/java/org/osaf/cosmo/jackrabbit/io/ExportCalendarCollectionCommand.java +++ b/src/main/java/org/osaf/cosmo/jackrabbit/io/ExportCalendarCollectionCommand.java @@ -1,111 +1,111 @@ /* * Copyright 2005 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osaf.cosmo.jackrabbit.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.RepositoryException; import net.fortuna.ical4j.data.CalendarOutputter; import net.fortuna.ical4j.model.Calendar; import org.apache.jackrabbit.server.io.AbstractCommand; import org.apache.jackrabbit.server.io.AbstractContext; import org.apache.jackrabbit.server.io.ExportContext; import org.apache.jackrabbit.webdav.DavException; import org.apache.log4j.Logger; import org.osaf.cosmo.CosmoConstants; import org.osaf.cosmo.dao.CalendarDao; import org.osaf.cosmo.icalendar.CosmoICalendarConstants; import org.osaf.cosmo.jcr.CosmoJcrConstants; /** * A command for exporting a view of the calendar objects contained * within a calendar collection. */ public class ExportCalendarCollectionCommand extends AbstractCommand { private static final Logger log = Logger.getLogger(ExportCalendarCollectionCommand.class); private static final String BEAN_CALENDAR_DAO = "calendarDao"; /** */ public boolean execute(AbstractContext context) throws Exception { if (context instanceof ApplicationContextAwareExportContext) { return execute((ApplicationContextAwareExportContext) context); } else { return false; } } /** */ public boolean execute(ApplicationContextAwareExportContext context) throws Exception { Node resourceNode = context.getNode(); if (resourceNode == null || ! resourceNode.isNodeType(CosmoJcrConstants.NT_CALDAV_COLLECTION)) { return false; } // extract calendar components from the node CalendarDao dao = (CalendarDao) context.getApplicationContext(). getBean(BEAN_CALENDAR_DAO, CalendarDao.class); Calendar calendar = dao.getCalendarObject(resourceNode); // fill in the context File tmpfile = File.createTempFile("__cosmo", CosmoICalendarConstants.FILE_EXTENSION); tmpfile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tmpfile); // XXX: non-validating in production mode CalendarOutputter outputter = new CalendarOutputter(); outputter.output(calendar, out); out.close(); context.setInputStream(new FileInputStream(tmpfile)); context.setContentLength(tmpfile.length()); context.setModificationTime(tmpfile.lastModified()); context.setContentType(CosmoICalendarConstants.CONTENT_TYPE + - "; charset=utf8"); + "; charset=utf-8"); Property contentLanguage = resourceNode.getProperty(CosmoJcrConstants.NP_XML_LANG); context.setContentLanguage(contentLanguage.getString()); java.util.Calendar creationTime = resourceNode.getProperty(CosmoJcrConstants.NP_JCR_CREATED). getDate(); context.setCreationTime(creationTime.getTime().getTime()); context.setETag(""); return true; } }
true
true
public boolean execute(ApplicationContextAwareExportContext context) throws Exception { Node resourceNode = context.getNode(); if (resourceNode == null || ! resourceNode.isNodeType(CosmoJcrConstants.NT_CALDAV_COLLECTION)) { return false; } // extract calendar components from the node CalendarDao dao = (CalendarDao) context.getApplicationContext(). getBean(BEAN_CALENDAR_DAO, CalendarDao.class); Calendar calendar = dao.getCalendarObject(resourceNode); // fill in the context File tmpfile = File.createTempFile("__cosmo", CosmoICalendarConstants.FILE_EXTENSION); tmpfile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tmpfile); // XXX: non-validating in production mode CalendarOutputter outputter = new CalendarOutputter(); outputter.output(calendar, out); out.close(); context.setInputStream(new FileInputStream(tmpfile)); context.setContentLength(tmpfile.length()); context.setModificationTime(tmpfile.lastModified()); context.setContentType(CosmoICalendarConstants.CONTENT_TYPE + "; charset=utf8"); Property contentLanguage = resourceNode.getProperty(CosmoJcrConstants.NP_XML_LANG); context.setContentLanguage(contentLanguage.getString()); java.util.Calendar creationTime = resourceNode.getProperty(CosmoJcrConstants.NP_JCR_CREATED). getDate(); context.setCreationTime(creationTime.getTime().getTime()); context.setETag(""); return true; }
public boolean execute(ApplicationContextAwareExportContext context) throws Exception { Node resourceNode = context.getNode(); if (resourceNode == null || ! resourceNode.isNodeType(CosmoJcrConstants.NT_CALDAV_COLLECTION)) { return false; } // extract calendar components from the node CalendarDao dao = (CalendarDao) context.getApplicationContext(). getBean(BEAN_CALENDAR_DAO, CalendarDao.class); Calendar calendar = dao.getCalendarObject(resourceNode); // fill in the context File tmpfile = File.createTempFile("__cosmo", CosmoICalendarConstants.FILE_EXTENSION); tmpfile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tmpfile); // XXX: non-validating in production mode CalendarOutputter outputter = new CalendarOutputter(); outputter.output(calendar, out); out.close(); context.setInputStream(new FileInputStream(tmpfile)); context.setContentLength(tmpfile.length()); context.setModificationTime(tmpfile.lastModified()); context.setContentType(CosmoICalendarConstants.CONTENT_TYPE + "; charset=utf-8"); Property contentLanguage = resourceNode.getProperty(CosmoJcrConstants.NP_XML_LANG); context.setContentLanguage(contentLanguage.getString()); java.util.Calendar creationTime = resourceNode.getProperty(CosmoJcrConstants.NP_JCR_CREATED). getDate(); context.setCreationTime(creationTime.getTime().getTime()); context.setETag(""); return true; }
diff --git a/src/savant/view/swing/Frame.java b/src/savant/view/swing/Frame.java index 50ff855e..4d95baf8 100644 --- a/src/savant/view/swing/Frame.java +++ b/src/savant/view/swing/Frame.java @@ -1,797 +1,803 @@ /* * Copyright 2010 University of Toronto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package savant.view.swing; import com.jidesoft.action.CommandBar; import com.jidesoft.action.CommandMenuBar; import com.jidesoft.docking.DockableFrame; import com.jidesoft.swing.JideButton; import com.jidesoft.swing.JideMenu; import java.awt.event.AdjustmentEvent; import java.beans.PropertyVetoException; import java.util.logging.Level; import java.util.logging.Logger; import savant.controller.DrawModeController; import savant.controller.RangeController; import savant.controller.event.drawmode.DrawModeChangedEvent; import savant.controller.event.drawmode.DrawModeChangedListener; import savant.model.FileFormat; import savant.model.data.RecordTrack; import savant.model.view.DrawingInstructions; import savant.util.Range; import savant.view.swing.continuous.ContinuousTrackRenderer; import savant.view.swing.interval.BAMCoverageViewTrack; import savant.view.swing.interval.BAMTrackRenderer; import savant.view.swing.interval.BEDTrackRenderer; import savant.view.swing.interval.IntervalTrackRenderer; import savant.view.swing.point.PointTrackRenderer; import savant.view.swing.sequence.SequenceTrackRenderer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import savant.controller.ReferenceController; import savant.model.view.Mode; import savant.view.swing.interval.BAMViewTrack; /** * * @author mfiume */ public class Frame { private boolean isHidden = false; private GraphPane graphPane; private JLayeredPane frameLandscape; private List<ViewTrack> tracks; private boolean isLocked; private Range currentRange; private JLayeredPane jlp; public CommandBar commandBar; public CommandBar commandBarHidden; private JPanel arcLegend; //private boolean legend = false; private List<JCheckBoxMenuItem> visItems; private JideButton arcButton; //private JMenu intervalMenu; private JideButton intervalButton; private boolean commandBarActive = true; private DockableFrame parent; private String name; public JScrollPane scrollPane; //private boolean tempCommandBar = true; public boolean isHidden() { return this.isHidden; } public void setHidden(boolean isHidden) { this.isHidden = isHidden; } public GraphPane getGraphPane() { return this.graphPane; } public JComponent getFrameLandscape() { return this.frameLandscape; } public List<ViewTrack> getTracks() { return this.tracks; } public boolean isOpen() { return getGraphPane() != null; } //public Frame(JComponent frameLandscape) { this((JLayeredPane)frameLandscape, null, null); } //public Frame(JComponent frameLandscape, List<ViewTrack> tracks, String name) { this((JLayeredPane)frameLandscape, tracks, new ArrayList<TrackRenderer>(), name); } //public Frame(JLayeredPane frameLandscape, List<ViewTrack> tracks, List<TrackRenderer> renderers, String name) public Frame(List<ViewTrack> tracks, String name) {this(tracks, new ArrayList<TrackRenderer>(), name); } public Frame(List<ViewTrack> tracks, List<TrackRenderer> renderers, String name) { this.name = name; //INIT LEGEND PANEL arcLegend = new JPanel(); arcLegend.setVisible(false); isLocked = false; this.tracks = new ArrayList<ViewTrack>(); - this.frameLandscape = new JLayeredPane(); + this.frameLandscape = new JLayeredPane(){ + public void repaint(long tm, int x, int y, int width, int height) { + if(x==0 && y==0 && width==frameLandscape.getWidth()-2 && height==frameLandscape.getHeight()-2){ + super.repaint(tm, x, y, width+2, height+2); + } else { + super.repaint(tm, x, y, width, height); + } + } + }; initGraph(); //scrollpane scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setWheelScrollingEnabled(false); - scrollPane.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); - scrollPane.setViewportBorder(BorderFactory.createEmptyBorder(0,0,0,0)); //hide commandBar while scrolling MouseListener ml = new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { if(parent.isActive()) tempHideCommands(); } public void mouseReleased(MouseEvent e) { if(parent.isActive()) tempShowCommands(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }; scrollPane.getVerticalScrollBar().addMouseListener(ml); JScrollBar vsb = scrollPane.getVerticalScrollBar(); for(int i = 0; i < vsb.getComponentCount(); i++){ vsb.getComponent(i).addMouseListener(ml); } //add graphPane -> jlp -> scrollPane jlp = new JLayeredPane(); jlp.setLayout(new GridBagLayout()); GridBagConstraints gbc= new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.gridx = 0; gbc.gridy = 0; jlp.add(this.graphPane, gbc, 0); //scrollPane.getViewport().add(this.graphPane); scrollPane.getViewport().add(jlp); if (!tracks.isEmpty()) { int i=0; Iterator<ViewTrack> it = tracks.iterator(); while ( it.hasNext()) { ViewTrack track = it.next(); // FIXME: track.setFrame(this); TrackRenderer renderer=null; if (!renderers.isEmpty()) { renderer = renderers.get(i++); } addTrack(track, renderer); //CREATE LEGEND PANEL if(track.getDataType().toString().equals("INTERVAL_BAM")){ arcLegend = track.getTrackRenderers().get(0).arcLegendPaint(); } } } //frameLandscape.setLayout(new BorderLayout()); //frameLandscape.add(getGraphPane()); //COMMAND BAR commandBar = new CommandBar(); commandBar.setStretch(false); commandBar.setPaintBackground(false); commandBar.setOpaque(true); commandBar.setChevronAlwaysVisible(false); JMenu optionsMenu = createOptionsMenu(); //JMenu infoMenu = createInfoMenu(); //JideButton lockButton = createLockButton(); JideButton hideButton = createHideButton(); //JideButton colorButton = createColorButton(); //commandBar.add(infoMenu); //commandBar.add(lockButton); //commandBar.add(colorButton); commandBar.add(optionsMenu); if(this.tracks.get(0).getDrawModes().size() > 0){ JMenu displayMenu = createDisplayMenu(); commandBar.add(displayMenu); } if (this.tracks.get(0).getDataType() == FileFormat.INTERVAL_BAM) { arcButton = createArcButton(); commandBar.add(arcButton); arcButton.setVisible(false); intervalButton = createIntervalButton(); commandBar.add(intervalButton); intervalButton.setVisible(false); String drawMode = this.getTracks().get(0).getDrawMode().getName(); if(drawMode.equals("STANDARD") || drawMode.equals("VARIANTS")){ intervalButton.setVisible(true); } //intervalMenu = createIntervalMenu(); //commandBar.add(intervalMenu); //intervalMenu.setVisible(false); //String drawMode = this.getTracks().get(0).getDrawMode().getName(); //if(drawMode.equals("STANDARD") || drawMode.equals("VARIANTS")){ // intervalMenu.setVisible(true); //} } commandBar.add(new JSeparator(SwingConstants.VERTICAL)); commandBar.add(hideButton); commandBar.setVisible(false); //COMMAND BAR HIDDEN //commandBarHidden.setVisible(false); commandBarHidden = new CommandBar(); //commandBarHidden.setVisible(false); commandBarHidden.setOpaque(true); commandBarHidden.setChevronAlwaysVisible(false); JideButton showButton = createShowButton(); commandBarHidden.add(showButton); commandBarHidden.setVisible(false); //GRID FRAMEWORK AND COMPONENT ADDING... frameLandscape.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JLabel l; c.fill = GridBagConstraints.HORIZONTAL; //force commandBars to be full size JPanel contain1 = new JPanel(); contain1.setOpaque(false); contain1.setLayout(new BorderLayout()); contain1.add(commandBar, BorderLayout.WEST); JPanel contain2 = new JPanel(); contain2.setOpaque(false); contain2.setLayout(new BorderLayout()); contain2.add(commandBarHidden, BorderLayout.WEST); //add commandBar/hidden to top left c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; frameLandscape.add(contain1, c, 5); frameLandscape.add(contain2, c, 6); //commandBarHidden.setVisible(true); //filler to extend commandBars JPanel a = new JPanel(); a.setMinimumSize(new Dimension(400,30)); a.setOpaque(false); c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; frameLandscape.add(a, c, 5); //add filler to top middle l = new JLabel(); //l.setOpaque(false); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.gridx = 1; c.gridy = 0; frameLandscape.add(l, c); //add arcLegend to bottom right c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0; c.weighty = 0; c.gridx = 2; c.gridy = 1; c.anchor = GridBagConstraints.NORTHEAST; frameLandscape.add(arcLegend, c, 6); //add graphPane to all cells c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.gridheight = 2; frameLandscape.add(scrollPane, c, 0); frameLandscape.setLayer(commandBar, (Integer) JLayeredPane.PALETTE_LAYER); //frameLandscape.setLayer(getGraphPane(), (Integer) JLayeredPane.DEFAULT_LAYER); frameLandscape.setLayer(scrollPane, (Integer) JLayeredPane.DEFAULT_LAYER); } public void setActiveFrame(){ if(commandBarActive) commandBar.setVisible(true); else commandBarHidden.setVisible(true); } public void setInactiveFrame(){ commandBarHidden.setVisible(false); commandBar.setVisible(false); } public void resetLayers(){ Frame f = this; if(f.getTracks().get(0).getDrawModes().size() > 0 && f.getTracks().get(0).getDrawMode().getName().equals("MATE_PAIRS")){ f.arcLegend.setVisible(true); } else { f.arcLegend.setVisible(false); } ((JLayeredPane) this.getFrameLandscape()).moveToBack(this.getGraphPane()); } private void tempHideCommands(){ commandBar.setVisible(false); commandBarHidden.setVisible(false); } private void tempShowCommands(){ if(commandBarActive){ commandBar.setVisible(true); commandBarHidden.setVisible(false); } else { commandBarHidden.setVisible(true); commandBar.setVisible(false); } } /** * Create the button to hide the commandBar */ private JideButton createHideButton() { JideButton button = new JideButton(); button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/savant/images/arrow_left.png"))); button.setToolTipText("Hide this toolbar"); button.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { commandBar.setVisible(false); commandBarHidden.setVisible(true); commandBarActive = false; ((JideButton)commandBarHidden.getComponent(commandBarHidden.getComponentCount()-1)).setFocusPainted(false); } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); button.setFocusPainted(false); return button; } /** * Create the button to show the commandBar */ private JideButton createShowButton() { JideButton button = new JideButton(); button.setLayout(new BorderLayout()); JLabel l1 = new JLabel("Settings"); l1.setOpaque(false); button.add(l1, BorderLayout.WEST); JLabel l2 = new JLabel(new javax.swing.ImageIcon(getClass().getResource("/savant/images/arrow_right.png"))); button.add(l2, BorderLayout.EAST); button.setToolTipText("Show the toolbar"); button.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { commandBar.setVisible(true); commandBarHidden.setVisible(false); commandBarActive = true; } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); button.setFocusPainted(false); return button; } /** * Create lock button for commandBar */ private JideButton createColorButton() { //TODO: This is temporary until there is an options menu JideButton button = new JideButton("Colour Settings "); button.setToolTipText("Change the colour scheme for this track"); button.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { tracks.get(0).captureColorParameters(); } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); button.setFocusPainted(false); return button; } /** * Create options menu for commandBar */ private JMenu createOptionsMenu() { JCheckBoxMenuItem item; JMenu menu = new JideMenu("Settings"); item = new JCheckBoxMenuItem("Lock Track"); item.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { graphPane.switchLocked(); } }); menu.add(item); JMenuItem item1; item1 = new JMenuItem("Colour Settings..."); item1.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { tracks.get(0).captureColorParameters(); } }); menu.add(item1); return menu; } /** * Create lock button for commandBar */ private JideButton createLockButton() { //TODO: This is temporary until there is an options menu JideButton button = new JideButton("Lock Track "); button.setToolTipText("Prevent range changes on this track"); button.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { JideButton button = new JideButton(); for(int i = 0; i < commandBar.getComponentCount(); i++){ if(commandBar.getComponent(i).getClass() == JideButton.class){ button = (JideButton)commandBar.getComponent(i); if(button.getText().equals("Lock Track ") || button.getText().equals("Unlock Track ")) break; } } if(button.getText().equals("Lock Track ")){ button.setText("Unlock Track "); button.setToolTipText("Allow range changes on this track"); } else { button.setText("Lock Track "); button.setToolTipText("Prevent range changes on this track"); } graphPane.switchLocked(); resetLayers(); } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); button.setFocusPainted(false); return button; } /** * Create info menu for commandBar */ private JMenu createInfoMenu() { JMenu menu = new JideMenu("Info"); JMenuItem item = new JMenuItem("Track Info..."); item.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { //TODO } }); menu.add(item); return menu; } /** * Create the button to show the arc params dialog */ private JideButton createArcButton() { JideButton button = new JideButton("Arc Options"); button.setToolTipText("Change mate pair parameters"); button.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { final BAMViewTrack innerTrack = (BAMViewTrack)tracks.get(0); graphPane.getBAMParams(innerTrack); } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); button.setFocusPainted(false); return button; } /** * Create interval button for commandBar */ private JideButton createIntervalButton() { JideButton button = new JideButton("Interval Options"); button.setToolTipText("Change interval display parameters"); button.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { tracks.get(0).captureIntervalParameters(); } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); button.setFocusPainted(false); return button; } /** * Create the menu for interval options */ /*private JMenu createIntervalMenu() { JMenu menu = new JideMenu("Interval Options"); final JCheckBoxMenuItem dynamic = new JCheckBoxMenuItem("Dynamic Height"); final JCheckBoxMenuItem fixed = new JCheckBoxMenuItem("Fixed Height"); dynamic.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { for(int i = 0; i < graphPane.getTrackRenderers().size(); i++){ graphPane.getTrackRenderers().get(i).setIntervalMode("dynamic"); } dynamic.setState(true); fixed.setState(false); graphPane.setRenderRequired(); graphPane.repaint(); } }); fixed.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { for(int i = 0; i < graphPane.getTrackRenderers().size(); i++){ graphPane.getTrackRenderers().get(i).setIntervalMode("fixed"); } fixed.setState(true); dynamic.setState(false); graphPane.setRenderRequired(); graphPane.repaint(); } }); dynamic.setState(true); menu.add(dynamic); menu.add(fixed); return menu; }*/ /** * Create display menu for commandBar */ private JMenu createDisplayMenu() { JMenu menu = new JideMenu("Display Mode"); //Arc params (if bam file) /*if(this.tracks.get(0).getDataType() == FileFormat.INTERVAL_BAM){ JMenuItem arcParam = new JMenuItem(); arcParam.setText("Change Arc Parameters..."); menu.add(arcParam); arcParam.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { final BAMViewTrack innerTrack = (BAMViewTrack)tracks.get(0); graphPane.getBAMParams(innerTrack); } }); JSeparator jSeparator1 = new JSeparator(); menu.add(jSeparator1); }*/ //display modes List<Mode> drawModes = this.tracks.get(0).getDrawModes(); visItems = new ArrayList<JCheckBoxMenuItem>(); for(int i = 0; i < drawModes.size(); i++){ final JCheckBoxMenuItem item = new JCheckBoxMenuItem(drawModes.get(i).toString()); item.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { if(item.getState()){ for(int j = 0; j < visItems.size(); j++){ visItems.get(j).setState(false); if(item.getText().equals(tracks.get(0).getDrawModes().get(j).toString())){ DrawModeController.getInstance().switchMode(tracks.get(0), tracks.get(0).getDrawModes().get(j)); } } } item.setState(true); } }); if(drawModes.get(i) == this.tracks.get(0).getDrawMode()){ item.setState(true); } visItems.add(item); menu.add(item); } return menu; } /** * Add a track to the list of tracks in * this frame * @param track The track to add * @param renderer to add for this track; if null, add default renderer for data type */ public void addTrack(ViewTrack track, TrackRenderer renderer) { tracks.add(track); if (renderer == null) { switch(track.getDataType()) { case POINT_GENERIC: renderer = new PointTrackRenderer(); break; case INTERVAL_GENERIC: renderer = new IntervalTrackRenderer(); break; case CONTINUOUS_GENERIC: renderer = new ContinuousTrackRenderer(); break; case INTERVAL_BAM: renderer = new BAMTrackRenderer(); break; case INTERVAL_BED: renderer = new BEDTrackRenderer(); break; case SEQUENCE_FASTA: renderer = new SequenceTrackRenderer(); break; } } renderer.getDrawingInstructions().addInstruction( DrawingInstructions.InstructionName.TRACK_DATA_TYPE, track.getDataType()); track.addTrackRenderer(renderer); GraphPane graphPane = getGraphPane(); graphPane.addTrackRenderer(renderer); graphPane.addTrack(track); } public void addTrack(ViewTrack track) { addTrack(track, null); } public void redrawTracksInRange() throws Exception { drawTracksInRange(ReferenceController.getInstance().getReferenceName(), currentRange); } /** * // TODO: comment * @param range */ public void drawTracksInRange(String reference, Range range) { if (!isLocked()) { currentRange = range; } if (this.graphPane.isLocked()) { return; } if (this.tracks.size() > 0) { this.graphPane.setXRange(currentRange); try { for (ViewTrack track : tracks) { track.prepareForRendering(reference, range); } this.graphPane.repaint(); } catch (Throwable throwable) { throwable.printStackTrace(); JOptionPane.showMessageDialog(graphPane, throwable.getMessage()); } } this.resetLayers(); } private GraphPane getNewZedGraphControl() { GraphPane zgc = new GraphPane(this); // TODO: set properties return zgc; } // TODO: what is locking for? public void lockRange(Range r) { setLocked(true, r); } public void unlockRange() { setLocked(false, null); } public void setLocked(boolean b, Range r) { this.isLocked = b; this.currentRange = r; } public boolean isLocked() { return this.isLocked; } private void initGraph() { graphPane = getNewZedGraphControl(); graphPane.setBackground(BrowserDefaults.colorFrameBackground); } // FIXME: this is a horrible kludge public void drawModeChanged(DrawModeChangedEvent evt) { ViewTrack viewTrack = evt.getViewTrack(); // if (getTracks().contains(viewTrack)) { boolean reRender = false; if (viewTrack.getDataType() == FileFormat.INTERVAL_BAM) { if (evt.getMode().getName().equals("MATE_PAIRS")) { reRender = true; setCoverageEnabled(false); this.arcButton.setVisible(true); this.intervalButton.setVisible(false); }else { if(evt.getMode().getName().equals("STANDARD") || evt.getMode().getName().equals("VARIANTS")){ this.intervalButton.setVisible(true); } else { this.intervalButton.setVisible(false); } setCoverageEnabled(true); reRender = true; this.arcButton.setVisible(false); } } if (reRender) { drawTracksInRange(ReferenceController.getInstance().getReferenceName(), RangeController.getInstance().getRange()); } // } } private void setCoverageEnabled(boolean enabled) { for (ViewTrack track: getTracks()) { if (track instanceof BAMCoverageViewTrack) { ((BAMCoverageViewTrack) track).setEnabled(enabled); } } } /** * Create a new panel to draw on. */ public JPanel getLayerToDraw(){ JPanel p = new JPanel(); p.setOpaque(false); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.gridheight = 2; jlp.add(p,c,2); jlp.setLayer(p, 50); return p; } /** * Export this frame as an image. */ public BufferedImage frameToImage(){ BufferedImage bufferedImage = new BufferedImage(getGraphPane().getWidth(), getGraphPane().getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); this.getGraphPane().render(g); g.setColor(Color.black); g.setFont(new Font(null, Font.BOLD, 13)); g.drawString(this.getTracks().get(0).getName(), 2, 15); return bufferedImage; } /** * Give reference to DockableFrame container. */ public void setDockableFrame(DockableFrame df){ this.parent = df; } public String getName(){ return this.name; } }
false
true
public Frame(List<ViewTrack> tracks, List<TrackRenderer> renderers, String name) { this.name = name; //INIT LEGEND PANEL arcLegend = new JPanel(); arcLegend.setVisible(false); isLocked = false; this.tracks = new ArrayList<ViewTrack>(); this.frameLandscape = new JLayeredPane(); initGraph(); //scrollpane scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setWheelScrollingEnabled(false); scrollPane.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); scrollPane.setViewportBorder(BorderFactory.createEmptyBorder(0,0,0,0)); //hide commandBar while scrolling MouseListener ml = new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { if(parent.isActive()) tempHideCommands(); } public void mouseReleased(MouseEvent e) { if(parent.isActive()) tempShowCommands(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }; scrollPane.getVerticalScrollBar().addMouseListener(ml); JScrollBar vsb = scrollPane.getVerticalScrollBar(); for(int i = 0; i < vsb.getComponentCount(); i++){ vsb.getComponent(i).addMouseListener(ml); } //add graphPane -> jlp -> scrollPane jlp = new JLayeredPane(); jlp.setLayout(new GridBagLayout()); GridBagConstraints gbc= new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.gridx = 0; gbc.gridy = 0; jlp.add(this.graphPane, gbc, 0); //scrollPane.getViewport().add(this.graphPane); scrollPane.getViewport().add(jlp); if (!tracks.isEmpty()) { int i=0; Iterator<ViewTrack> it = tracks.iterator(); while ( it.hasNext()) { ViewTrack track = it.next(); // FIXME: track.setFrame(this); TrackRenderer renderer=null; if (!renderers.isEmpty()) { renderer = renderers.get(i++); } addTrack(track, renderer); //CREATE LEGEND PANEL if(track.getDataType().toString().equals("INTERVAL_BAM")){ arcLegend = track.getTrackRenderers().get(0).arcLegendPaint(); } } } //frameLandscape.setLayout(new BorderLayout()); //frameLandscape.add(getGraphPane()); //COMMAND BAR commandBar = new CommandBar(); commandBar.setStretch(false); commandBar.setPaintBackground(false); commandBar.setOpaque(true); commandBar.setChevronAlwaysVisible(false); JMenu optionsMenu = createOptionsMenu(); //JMenu infoMenu = createInfoMenu(); //JideButton lockButton = createLockButton(); JideButton hideButton = createHideButton(); //JideButton colorButton = createColorButton(); //commandBar.add(infoMenu); //commandBar.add(lockButton); //commandBar.add(colorButton); commandBar.add(optionsMenu); if(this.tracks.get(0).getDrawModes().size() > 0){ JMenu displayMenu = createDisplayMenu(); commandBar.add(displayMenu); } if (this.tracks.get(0).getDataType() == FileFormat.INTERVAL_BAM) { arcButton = createArcButton(); commandBar.add(arcButton); arcButton.setVisible(false); intervalButton = createIntervalButton(); commandBar.add(intervalButton); intervalButton.setVisible(false); String drawMode = this.getTracks().get(0).getDrawMode().getName(); if(drawMode.equals("STANDARD") || drawMode.equals("VARIANTS")){ intervalButton.setVisible(true); } //intervalMenu = createIntervalMenu(); //commandBar.add(intervalMenu); //intervalMenu.setVisible(false); //String drawMode = this.getTracks().get(0).getDrawMode().getName(); //if(drawMode.equals("STANDARD") || drawMode.equals("VARIANTS")){ // intervalMenu.setVisible(true); //} } commandBar.add(new JSeparator(SwingConstants.VERTICAL)); commandBar.add(hideButton); commandBar.setVisible(false); //COMMAND BAR HIDDEN //commandBarHidden.setVisible(false); commandBarHidden = new CommandBar(); //commandBarHidden.setVisible(false); commandBarHidden.setOpaque(true); commandBarHidden.setChevronAlwaysVisible(false); JideButton showButton = createShowButton(); commandBarHidden.add(showButton); commandBarHidden.setVisible(false); //GRID FRAMEWORK AND COMPONENT ADDING... frameLandscape.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JLabel l; c.fill = GridBagConstraints.HORIZONTAL; //force commandBars to be full size JPanel contain1 = new JPanel(); contain1.setOpaque(false); contain1.setLayout(new BorderLayout()); contain1.add(commandBar, BorderLayout.WEST); JPanel contain2 = new JPanel(); contain2.setOpaque(false); contain2.setLayout(new BorderLayout()); contain2.add(commandBarHidden, BorderLayout.WEST); //add commandBar/hidden to top left c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; frameLandscape.add(contain1, c, 5); frameLandscape.add(contain2, c, 6); //commandBarHidden.setVisible(true); //filler to extend commandBars JPanel a = new JPanel(); a.setMinimumSize(new Dimension(400,30)); a.setOpaque(false); c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; frameLandscape.add(a, c, 5); //add filler to top middle l = new JLabel(); //l.setOpaque(false); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.gridx = 1; c.gridy = 0; frameLandscape.add(l, c); //add arcLegend to bottom right c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0; c.weighty = 0; c.gridx = 2; c.gridy = 1; c.anchor = GridBagConstraints.NORTHEAST; frameLandscape.add(arcLegend, c, 6); //add graphPane to all cells c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.gridheight = 2; frameLandscape.add(scrollPane, c, 0); frameLandscape.setLayer(commandBar, (Integer) JLayeredPane.PALETTE_LAYER); //frameLandscape.setLayer(getGraphPane(), (Integer) JLayeredPane.DEFAULT_LAYER); frameLandscape.setLayer(scrollPane, (Integer) JLayeredPane.DEFAULT_LAYER); }
public Frame(List<ViewTrack> tracks, List<TrackRenderer> renderers, String name) { this.name = name; //INIT LEGEND PANEL arcLegend = new JPanel(); arcLegend.setVisible(false); isLocked = false; this.tracks = new ArrayList<ViewTrack>(); this.frameLandscape = new JLayeredPane(){ public void repaint(long tm, int x, int y, int width, int height) { if(x==0 && y==0 && width==frameLandscape.getWidth()-2 && height==frameLandscape.getHeight()-2){ super.repaint(tm, x, y, width+2, height+2); } else { super.repaint(tm, x, y, width, height); } } }; initGraph(); //scrollpane scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setWheelScrollingEnabled(false); //hide commandBar while scrolling MouseListener ml = new MouseListener(){ public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { if(parent.isActive()) tempHideCommands(); } public void mouseReleased(MouseEvent e) { if(parent.isActive()) tempShowCommands(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }; scrollPane.getVerticalScrollBar().addMouseListener(ml); JScrollBar vsb = scrollPane.getVerticalScrollBar(); for(int i = 0; i < vsb.getComponentCount(); i++){ vsb.getComponent(i).addMouseListener(ml); } //add graphPane -> jlp -> scrollPane jlp = new JLayeredPane(); jlp.setLayout(new GridBagLayout()); GridBagConstraints gbc= new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.gridx = 0; gbc.gridy = 0; jlp.add(this.graphPane, gbc, 0); //scrollPane.getViewport().add(this.graphPane); scrollPane.getViewport().add(jlp); if (!tracks.isEmpty()) { int i=0; Iterator<ViewTrack> it = tracks.iterator(); while ( it.hasNext()) { ViewTrack track = it.next(); // FIXME: track.setFrame(this); TrackRenderer renderer=null; if (!renderers.isEmpty()) { renderer = renderers.get(i++); } addTrack(track, renderer); //CREATE LEGEND PANEL if(track.getDataType().toString().equals("INTERVAL_BAM")){ arcLegend = track.getTrackRenderers().get(0).arcLegendPaint(); } } } //frameLandscape.setLayout(new BorderLayout()); //frameLandscape.add(getGraphPane()); //COMMAND BAR commandBar = new CommandBar(); commandBar.setStretch(false); commandBar.setPaintBackground(false); commandBar.setOpaque(true); commandBar.setChevronAlwaysVisible(false); JMenu optionsMenu = createOptionsMenu(); //JMenu infoMenu = createInfoMenu(); //JideButton lockButton = createLockButton(); JideButton hideButton = createHideButton(); //JideButton colorButton = createColorButton(); //commandBar.add(infoMenu); //commandBar.add(lockButton); //commandBar.add(colorButton); commandBar.add(optionsMenu); if(this.tracks.get(0).getDrawModes().size() > 0){ JMenu displayMenu = createDisplayMenu(); commandBar.add(displayMenu); } if (this.tracks.get(0).getDataType() == FileFormat.INTERVAL_BAM) { arcButton = createArcButton(); commandBar.add(arcButton); arcButton.setVisible(false); intervalButton = createIntervalButton(); commandBar.add(intervalButton); intervalButton.setVisible(false); String drawMode = this.getTracks().get(0).getDrawMode().getName(); if(drawMode.equals("STANDARD") || drawMode.equals("VARIANTS")){ intervalButton.setVisible(true); } //intervalMenu = createIntervalMenu(); //commandBar.add(intervalMenu); //intervalMenu.setVisible(false); //String drawMode = this.getTracks().get(0).getDrawMode().getName(); //if(drawMode.equals("STANDARD") || drawMode.equals("VARIANTS")){ // intervalMenu.setVisible(true); //} } commandBar.add(new JSeparator(SwingConstants.VERTICAL)); commandBar.add(hideButton); commandBar.setVisible(false); //COMMAND BAR HIDDEN //commandBarHidden.setVisible(false); commandBarHidden = new CommandBar(); //commandBarHidden.setVisible(false); commandBarHidden.setOpaque(true); commandBarHidden.setChevronAlwaysVisible(false); JideButton showButton = createShowButton(); commandBarHidden.add(showButton); commandBarHidden.setVisible(false); //GRID FRAMEWORK AND COMPONENT ADDING... frameLandscape.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JLabel l; c.fill = GridBagConstraints.HORIZONTAL; //force commandBars to be full size JPanel contain1 = new JPanel(); contain1.setOpaque(false); contain1.setLayout(new BorderLayout()); contain1.add(commandBar, BorderLayout.WEST); JPanel contain2 = new JPanel(); contain2.setOpaque(false); contain2.setLayout(new BorderLayout()); contain2.add(commandBarHidden, BorderLayout.WEST); //add commandBar/hidden to top left c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; frameLandscape.add(contain1, c, 5); frameLandscape.add(contain2, c, 6); //commandBarHidden.setVisible(true); //filler to extend commandBars JPanel a = new JPanel(); a.setMinimumSize(new Dimension(400,30)); a.setOpaque(false); c.weightx = 0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; frameLandscape.add(a, c, 5); //add filler to top middle l = new JLabel(); //l.setOpaque(false); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.gridx = 1; c.gridy = 0; frameLandscape.add(l, c); //add arcLegend to bottom right c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0; c.weighty = 0; c.gridx = 2; c.gridy = 1; c.anchor = GridBagConstraints.NORTHEAST; frameLandscape.add(arcLegend, c, 6); //add graphPane to all cells c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 0; c.gridy = 0; c.gridwidth = 3; c.gridheight = 2; frameLandscape.add(scrollPane, c, 0); frameLandscape.setLayer(commandBar, (Integer) JLayeredPane.PALETTE_LAYER); //frameLandscape.setLayer(getGraphPane(), (Integer) JLayeredPane.DEFAULT_LAYER); frameLandscape.setLayer(scrollPane, (Integer) JLayeredPane.DEFAULT_LAYER); }
diff --git a/src/main/java/de/ailis/xadrian/dialogs/WarePricesDialog.java b/src/main/java/de/ailis/xadrian/dialogs/WarePricesDialog.java index 188778e..b521a34 100644 --- a/src/main/java/de/ailis/xadrian/dialogs/WarePricesDialog.java +++ b/src/main/java/de/ailis/xadrian/dialogs/WarePricesDialog.java @@ -1,421 +1,425 @@ /* * $Id$ * Copyright (C) 2009 Klaus Reimer <[email protected]> * See LICENSE.TXT for licensing information */ package de.ailis.xadrian.dialogs; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.NumberFormat; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import de.ailis.xadrian.data.Ware; import de.ailis.xadrian.data.factories.FactoryFactory; import de.ailis.xadrian.data.factories.WareFactory; import de.ailis.xadrian.resources.Images; import de.ailis.xadrian.support.I18N; import de.ailis.xadrian.support.ModalDialog; import de.ailis.xadrian.utils.SwingUtils; /** * Dialog for setting up the ware prices. * * @author Klaus Reimer ([email protected]) * @version $Revision$ */ public class WarePricesDialog extends ModalDialog { /** Serial version UID */ private static final long serialVersionUID = -7047840854198687941L; /** The map with custom prices */ private final Map<Ware, Integer> customPrices = new HashMap<Ware, Integer>(); /** The singleton instance */ private final static WarePricesDialog instance = new WarePricesDialog(); /** The ware prices panel */ private JPanel warePricesPanel; /** The active ware (Is focused when dialog opens) */ private Ware activeWare; /** The scroll pane */ private JScrollPane scrollPane; /** * Constructor */ private WarePricesDialog() { super(Result.OK, Result.CANCEL); } /** * Creates the UI */ @Override protected void createUI() { setTitle(I18N.getTitle("changeWarePrices")); setIconImages(Images.LOGOS); // Create the content panel this.warePricesPanel = new JPanel(); this.warePricesPanel.setLayout(new GridBagLayout()); this.warePricesPanel.setBackground(Color.WHITE); final JScrollPane scrollPane = new JScrollPane(this.warePricesPanel); scrollPane.setBorder(BorderFactory .createBevelBorder(BevelBorder.LOWERED)); scrollPane.setPreferredSize(new Dimension(720, 512)); scrollPane.getVerticalScrollBar().setUnitIncrement(16); this.scrollPane = scrollPane; final JPanel contentPanel = new JPanel(new BorderLayout()); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); contentPanel.add(scrollPane, BorderLayout.CENTER); // Put this last panel into the window add(contentPanel, BorderLayout.CENTER); } /** * Initializes the content. */ private void initContent() { final WareFactory wareFactory = WareFactory.getInstance(); final Color gray = new Color(0xee, 0xee, 0xee); final NumberFormat formatter = NumberFormat.getNumberInstance(); JSpinner focusComponent = null; final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); c.fill = GridBagConstraints.BOTH; for (final Ware ware : wareFactory.getWares()) { // If ware is not used by any buyable factory then ignore it if (FactoryFactory.getInstance().getFactories(ware).isEmpty()) continue; // Get price and check if ware is used int price; final boolean used; if (this.customPrices.containsKey(ware)) { price = this.customPrices.get(ware); used = price > 0; price = Math.abs(price); } else { price = ware.getAvgPrice(); used = true; } // Calculate the color to use in this row final Color color = c.gridy % 2 == 0 ? Color.WHITE : gray; // Add the title label c.gridx = 0; c.weightx = 1; final JLabel titleLabel = new JLabel(String.format( "<html>%s<br /><font size=\"2\" color=\"#888888\">" + "%s / %s / %s Cr</font></html>", ware.getName(), formatter.format(ware.getMinPrice()), formatter.format(ware .getAvgPrice()), formatter.format(ware.getMaxPrice()))); titleLabel.setAlignmentX(LEFT_ALIGNMENT); titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); titleLabel.setOpaque(true); titleLabel.setBackground(color); this.warePricesPanel.add(titleLabel, c); c.weightx = 0; // Add the buy/sell checkbox c.gridx++; final JCheckBox checkBox = new JCheckBox(I18N .getString("changeWarePrices.used")); checkBox.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); checkBox.setBackground(color); checkBox.setOpaque(true); checkBox.setSelected(used); this.warePricesPanel.add(checkBox, c); // Add the price label c.gridx++; final JLabel priceLabel = new JLabel(I18N .getString("changeWarePrices.price") + ":"); final JPanel pricePanel = new JPanel(); pricePanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 0)); pricePanel.setBackground(color); priceLabel.setEnabled(used); pricePanel.add(priceLabel); this.warePricesPanel.add(pricePanel, c); // Add the price slider c.gridx++; final JSlider slider = new JSlider(ware.getMinPrice(), ware .getMaxPrice(), price); final JPanel sliderPanel = new JPanel(new BorderLayout()); sliderPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); slider.setEnabled(used); sliderPanel.setBackground(color); slider.setSnapToTicks(true); slider.setMinorTickSpacing(1); slider.setPaintLabels(false); slider.setPaintTicks(false); slider.setOpaque(false); slider.setPaintTrack(true); slider.setPreferredSize(new Dimension(100, 1)); sliderPanel.add(slider); this.warePricesPanel.add(sliderPanel, c); // Add the price spinner c.gridx++; final SpinnerModel model = new SpinnerNumberModel(price, ware .getMinPrice(), ware.getMaxPrice(), 1); final JSpinner spinner = new JSpinner(model); final JPanel spinnerPanel = new JPanel(new BorderLayout()); spinner.setEnabled(used); spinner.setPreferredSize(new Dimension(100, 1)); SwingUtils.installSpinnerBugWorkaround(spinner); spinnerPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); spinnerPanel.setBackground(color); spinnerPanel.add(spinner, BorderLayout.CENTER); this.warePricesPanel.add(spinnerPanel, c); // Focus the spinner if current ware is the active ware if (ware.equals(this.activeWare)) focusComponent = spinner; // Add the credits label c.gridx++; final JLabel credits = new JLabel("Cr"); final JPanel creditsPanel = new JPanel(); creditsPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); credits.setEnabled(used); creditsPanel.setBackground(color); creditsPanel.add(credits); this.warePricesPanel.add(creditsPanel, c); // Add the reset button c.gridx++; final JButton resetButton = new JButton(I18N .getString("changeWarePrices.reset")); resetButton.setEnabled(!used || price != ware.getAvgPrice()); final JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); buttonPanel.setBackground(color); buttonPanel.add(resetButton); this.warePricesPanel.add(buttonPanel, c); // Setup events slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { spinner.setValue(slider.getValue()); } }); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { slider.setValue((Integer) spinner.getValue()); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); checkBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final boolean enabled = checkBox.isSelected(); slider.setEnabled(enabled); spinner.setEnabled(enabled); credits.setEnabled(enabled); priceLabel.setEnabled(enabled); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { checkBox.setSelected(true); slider.setValue(ware.getAvgPrice()); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); c.gridy++; } setResizable(true); validate(); if (focusComponent != null) { final int height = this.scrollPane.getHeight(); focusComponent.scrollRectToVisible(new Rectangle(0, -height / 2 + focusComponent.getHeight() / 2, 0, height)); focusComponent.requestFocus(); } + else + { + this.scrollPane.getVerticalScrollBar().setValue(0); + } } /** * Updates a custom price * * @param ware * The ware * @param used * If ware is used * @param price * The price */ void updateCustomWare(final Ware ware, final boolean used, final int price) { if (price == ware.getAvgPrice() && used) this.customPrices.remove(ware); else this.customPrices.put(ware, used ? price : -price); } /** * Releases the content. */ private void releaseContent() { for (final Component component : this.warePricesPanel.getComponents()) this.warePricesPanel.remove(component); } /** * Sets the custom prices. * * @param customPrices * The custom prices to set */ public void setCustomPrices(final Map<Ware, Integer> customPrices) { this.customPrices.clear(); this.customPrices.putAll(customPrices); } /** * Returns the custom prices. * * @return The custom prices */ public Map<Ware, Integer> getCustomPrices() { return Collections.unmodifiableMap(this.customPrices); } /** * Sets the active ware. This is the ware which is focused when the dialog * starts. Set it to null to not use a focused ware. * * @param ware * The ware to focus (or null for none) */ public void setActiveWare(final Ware ware) { this.activeWare = ware; } /** * Returns the singleton instance. * * @return The singleton instance */ public static WarePricesDialog getInstance() { return instance; } /** * @see de.ailis.xadrian.support.ModalDialog#open() */ @Override public Result open() { initContent(); try { return super.open(); } finally { releaseContent(); } } }
true
true
private void initContent() { final WareFactory wareFactory = WareFactory.getInstance(); final Color gray = new Color(0xee, 0xee, 0xee); final NumberFormat formatter = NumberFormat.getNumberInstance(); JSpinner focusComponent = null; final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); c.fill = GridBagConstraints.BOTH; for (final Ware ware : wareFactory.getWares()) { // If ware is not used by any buyable factory then ignore it if (FactoryFactory.getInstance().getFactories(ware).isEmpty()) continue; // Get price and check if ware is used int price; final boolean used; if (this.customPrices.containsKey(ware)) { price = this.customPrices.get(ware); used = price > 0; price = Math.abs(price); } else { price = ware.getAvgPrice(); used = true; } // Calculate the color to use in this row final Color color = c.gridy % 2 == 0 ? Color.WHITE : gray; // Add the title label c.gridx = 0; c.weightx = 1; final JLabel titleLabel = new JLabel(String.format( "<html>%s<br /><font size=\"2\" color=\"#888888\">" + "%s / %s / %s Cr</font></html>", ware.getName(), formatter.format(ware.getMinPrice()), formatter.format(ware .getAvgPrice()), formatter.format(ware.getMaxPrice()))); titleLabel.setAlignmentX(LEFT_ALIGNMENT); titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); titleLabel.setOpaque(true); titleLabel.setBackground(color); this.warePricesPanel.add(titleLabel, c); c.weightx = 0; // Add the buy/sell checkbox c.gridx++; final JCheckBox checkBox = new JCheckBox(I18N .getString("changeWarePrices.used")); checkBox.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); checkBox.setBackground(color); checkBox.setOpaque(true); checkBox.setSelected(used); this.warePricesPanel.add(checkBox, c); // Add the price label c.gridx++; final JLabel priceLabel = new JLabel(I18N .getString("changeWarePrices.price") + ":"); final JPanel pricePanel = new JPanel(); pricePanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 0)); pricePanel.setBackground(color); priceLabel.setEnabled(used); pricePanel.add(priceLabel); this.warePricesPanel.add(pricePanel, c); // Add the price slider c.gridx++; final JSlider slider = new JSlider(ware.getMinPrice(), ware .getMaxPrice(), price); final JPanel sliderPanel = new JPanel(new BorderLayout()); sliderPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); slider.setEnabled(used); sliderPanel.setBackground(color); slider.setSnapToTicks(true); slider.setMinorTickSpacing(1); slider.setPaintLabels(false); slider.setPaintTicks(false); slider.setOpaque(false); slider.setPaintTrack(true); slider.setPreferredSize(new Dimension(100, 1)); sliderPanel.add(slider); this.warePricesPanel.add(sliderPanel, c); // Add the price spinner c.gridx++; final SpinnerModel model = new SpinnerNumberModel(price, ware .getMinPrice(), ware.getMaxPrice(), 1); final JSpinner spinner = new JSpinner(model); final JPanel spinnerPanel = new JPanel(new BorderLayout()); spinner.setEnabled(used); spinner.setPreferredSize(new Dimension(100, 1)); SwingUtils.installSpinnerBugWorkaround(spinner); spinnerPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); spinnerPanel.setBackground(color); spinnerPanel.add(spinner, BorderLayout.CENTER); this.warePricesPanel.add(spinnerPanel, c); // Focus the spinner if current ware is the active ware if (ware.equals(this.activeWare)) focusComponent = spinner; // Add the credits label c.gridx++; final JLabel credits = new JLabel("Cr"); final JPanel creditsPanel = new JPanel(); creditsPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); credits.setEnabled(used); creditsPanel.setBackground(color); creditsPanel.add(credits); this.warePricesPanel.add(creditsPanel, c); // Add the reset button c.gridx++; final JButton resetButton = new JButton(I18N .getString("changeWarePrices.reset")); resetButton.setEnabled(!used || price != ware.getAvgPrice()); final JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); buttonPanel.setBackground(color); buttonPanel.add(resetButton); this.warePricesPanel.add(buttonPanel, c); // Setup events slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { spinner.setValue(slider.getValue()); } }); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { slider.setValue((Integer) spinner.getValue()); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); checkBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final boolean enabled = checkBox.isSelected(); slider.setEnabled(enabled); spinner.setEnabled(enabled); credits.setEnabled(enabled); priceLabel.setEnabled(enabled); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { checkBox.setSelected(true); slider.setValue(ware.getAvgPrice()); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); c.gridy++; } setResizable(true); validate(); if (focusComponent != null) { final int height = this.scrollPane.getHeight(); focusComponent.scrollRectToVisible(new Rectangle(0, -height / 2 + focusComponent.getHeight() / 2, 0, height)); focusComponent.requestFocus(); } }
private void initContent() { final WareFactory wareFactory = WareFactory.getInstance(); final Color gray = new Color(0xee, 0xee, 0xee); final NumberFormat formatter = NumberFormat.getNumberInstance(); JSpinner focusComponent = null; final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; c.gridy = 0; c.insets = new Insets(0, 0, 0, 0); c.fill = GridBagConstraints.BOTH; for (final Ware ware : wareFactory.getWares()) { // If ware is not used by any buyable factory then ignore it if (FactoryFactory.getInstance().getFactories(ware).isEmpty()) continue; // Get price and check if ware is used int price; final boolean used; if (this.customPrices.containsKey(ware)) { price = this.customPrices.get(ware); used = price > 0; price = Math.abs(price); } else { price = ware.getAvgPrice(); used = true; } // Calculate the color to use in this row final Color color = c.gridy % 2 == 0 ? Color.WHITE : gray; // Add the title label c.gridx = 0; c.weightx = 1; final JLabel titleLabel = new JLabel(String.format( "<html>%s<br /><font size=\"2\" color=\"#888888\">" + "%s / %s / %s Cr</font></html>", ware.getName(), formatter.format(ware.getMinPrice()), formatter.format(ware .getAvgPrice()), formatter.format(ware.getMaxPrice()))); titleLabel.setAlignmentX(LEFT_ALIGNMENT); titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); titleLabel.setOpaque(true); titleLabel.setBackground(color); this.warePricesPanel.add(titleLabel, c); c.weightx = 0; // Add the buy/sell checkbox c.gridx++; final JCheckBox checkBox = new JCheckBox(I18N .getString("changeWarePrices.used")); checkBox.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); checkBox.setBackground(color); checkBox.setOpaque(true); checkBox.setSelected(used); this.warePricesPanel.add(checkBox, c); // Add the price label c.gridx++; final JLabel priceLabel = new JLabel(I18N .getString("changeWarePrices.price") + ":"); final JPanel pricePanel = new JPanel(); pricePanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 0)); pricePanel.setBackground(color); priceLabel.setEnabled(used); pricePanel.add(priceLabel); this.warePricesPanel.add(pricePanel, c); // Add the price slider c.gridx++; final JSlider slider = new JSlider(ware.getMinPrice(), ware .getMaxPrice(), price); final JPanel sliderPanel = new JPanel(new BorderLayout()); sliderPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); slider.setEnabled(used); sliderPanel.setBackground(color); slider.setSnapToTicks(true); slider.setMinorTickSpacing(1); slider.setPaintLabels(false); slider.setPaintTicks(false); slider.setOpaque(false); slider.setPaintTrack(true); slider.setPreferredSize(new Dimension(100, 1)); sliderPanel.add(slider); this.warePricesPanel.add(sliderPanel, c); // Add the price spinner c.gridx++; final SpinnerModel model = new SpinnerNumberModel(price, ware .getMinPrice(), ware.getMaxPrice(), 1); final JSpinner spinner = new JSpinner(model); final JPanel spinnerPanel = new JPanel(new BorderLayout()); spinner.setEnabled(used); spinner.setPreferredSize(new Dimension(100, 1)); SwingUtils.installSpinnerBugWorkaround(spinner); spinnerPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); spinnerPanel.setBackground(color); spinnerPanel.add(spinner, BorderLayout.CENTER); this.warePricesPanel.add(spinnerPanel, c); // Focus the spinner if current ware is the active ware if (ware.equals(this.activeWare)) focusComponent = spinner; // Add the credits label c.gridx++; final JLabel credits = new JLabel("Cr"); final JPanel creditsPanel = new JPanel(); creditsPanel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); credits.setEnabled(used); creditsPanel.setBackground(color); creditsPanel.add(credits); this.warePricesPanel.add(creditsPanel, c); // Add the reset button c.gridx++; final JButton resetButton = new JButton(I18N .getString("changeWarePrices.reset")); resetButton.setEnabled(!used || price != ware.getAvgPrice()); final JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); buttonPanel.setBackground(color); buttonPanel.add(resetButton); this.warePricesPanel.add(buttonPanel, c); // Setup events slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { spinner.setValue(slider.getValue()); } }); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { slider.setValue((Integer) spinner.getValue()); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); checkBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final boolean enabled = checkBox.isSelected(); slider.setEnabled(enabled); spinner.setEnabled(enabled); credits.setEnabled(enabled); priceLabel.setEnabled(enabled); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { checkBox.setSelected(true); slider.setValue(ware.getAvgPrice()); resetButton.setEnabled(slider.getValue() != ware .getAvgPrice() || !checkBox.isSelected()); updateCustomWare(ware, checkBox.isSelected(), slider .getValue()); } }); c.gridy++; } setResizable(true); validate(); if (focusComponent != null) { final int height = this.scrollPane.getHeight(); focusComponent.scrollRectToVisible(new Rectangle(0, -height / 2 + focusComponent.getHeight() / 2, 0, height)); focusComponent.requestFocus(); } else { this.scrollPane.getVerticalScrollBar().setValue(0); } }
diff --git a/src/com/android/mms/transaction/SmsSingleRecipientSender.java b/src/com/android/mms/transaction/SmsSingleRecipientSender.java index 42d8ad6b..40866d8a 100644 --- a/src/com/android/mms/transaction/SmsSingleRecipientSender.java +++ b/src/com/android/mms/transaction/SmsSingleRecipientSender.java @@ -1,128 +1,130 @@ package com.android.mms.transaction; import java.util.ArrayList; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.Telephony.Mms; import android.telephony.SmsManager; import android.util.Log; import com.android.mms.LogTag; import com.android.mms.MmsConfig; import com.google.android.mms.MmsException; import android.provider.Telephony.Sms; import com.android.mms.data.Conversation; import com.android.mms.ui.MessageUtils; public class SmsSingleRecipientSender extends SmsMessageSender { private final boolean mRequestDeliveryReport; private String mDest; private Uri mUri; private static final String TAG = "SmsSingleRecipientSender"; public SmsSingleRecipientSender(Context context, String dest, String msgText, long threadId, boolean requestDeliveryReport, Uri uri) { super(context, null, msgText, threadId); mRequestDeliveryReport = requestDeliveryReport; mDest = dest; mUri = uri; } public boolean sendMessage(long token) throws MmsException { if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage token: " + token); } if (mMessageText == null) { // Don't try to send an empty message, and destination should be just // one. throw new MmsException("Null message body or have multiple destinations."); } SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> messages = null; if ((MmsConfig.getEmailGateway() != null) && (Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) { String msgText; msgText = mDest + " " + mMessageText; mDest = MmsConfig.getEmailGateway(); messages = smsManager.divideMessage(msgText); } else { messages = smsManager.divideMessage(mMessageText); // remove spaces from destination number (e.g. "801 555 1212" -> "8015551212") mDest = mDest.replaceAll(" ", ""); mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest); } int messageCount = messages.size(); if (messageCount == 0) { // Don't try to send an empty message. throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned " + "empty messages. Original message is \"" + mMessageText + "\""); } boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0); if (!moved) { throw new MmsException("SmsMessageSender.sendMessage: couldn't move message " + "to outbox: " + mUri); } if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " + mRequestDeliveryReport); } ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount); ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount); for (int i = 0; i < messageCount; i++) { - if (mRequestDeliveryReport) { + if (mRequestDeliveryReport && (i == (messageCount - 1))) { // TODO: Fix: It should not be necessary to // specify the class in this intent. Doing that // unnecessarily limits customizability. deliveryIntents.add(PendingIntent.getBroadcast( mContext, 0, new Intent( MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION, mUri, mContext, MessageStatusReceiver.class), - 0)); + 0)); + } else { + deliveryIntents.add(null); } Intent intent = new Intent(SmsReceiverService.MESSAGE_SENT_ACTION, mUri, mContext, SmsReceiver.class); int requestCode = 0; if (i == messageCount -1) { // Changing the requestCode so that a different pending intent // is created for the last fragment with // EXTRA_MESSAGE_SENT_SEND_NEXT set to true. requestCode = 1; intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true); } if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage sendIntent: " + intent); } sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0)); } try { smsManager.sendMultipartTextMessage(mDest, mServiceCenter, messages, sentIntents, deliveryIntents); } catch (Exception ex) { Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex); throw new MmsException("SmsMessageSender.sendMessage: caught " + ex + " from SmsManager.sendTextMessage()"); } if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) { log("sendMessage: address=" + mDest + ", threadId=" + mThreadId + ", uri=" + mUri + ", msgs.count=" + messageCount); } return false; } private void log(String msg) { Log.d(LogTag.TAG, "[SmsSingleRecipientSender] " + msg); } }
false
true
public boolean sendMessage(long token) throws MmsException { if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage token: " + token); } if (mMessageText == null) { // Don't try to send an empty message, and destination should be just // one. throw new MmsException("Null message body or have multiple destinations."); } SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> messages = null; if ((MmsConfig.getEmailGateway() != null) && (Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) { String msgText; msgText = mDest + " " + mMessageText; mDest = MmsConfig.getEmailGateway(); messages = smsManager.divideMessage(msgText); } else { messages = smsManager.divideMessage(mMessageText); // remove spaces from destination number (e.g. "801 555 1212" -> "8015551212") mDest = mDest.replaceAll(" ", ""); mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest); } int messageCount = messages.size(); if (messageCount == 0) { // Don't try to send an empty message. throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned " + "empty messages. Original message is \"" + mMessageText + "\""); } boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0); if (!moved) { throw new MmsException("SmsMessageSender.sendMessage: couldn't move message " + "to outbox: " + mUri); } if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " + mRequestDeliveryReport); } ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount); ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount); for (int i = 0; i < messageCount; i++) { if (mRequestDeliveryReport) { // TODO: Fix: It should not be necessary to // specify the class in this intent. Doing that // unnecessarily limits customizability. deliveryIntents.add(PendingIntent.getBroadcast( mContext, 0, new Intent( MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION, mUri, mContext, MessageStatusReceiver.class), 0)); } Intent intent = new Intent(SmsReceiverService.MESSAGE_SENT_ACTION, mUri, mContext, SmsReceiver.class); int requestCode = 0; if (i == messageCount -1) { // Changing the requestCode so that a different pending intent // is created for the last fragment with // EXTRA_MESSAGE_SENT_SEND_NEXT set to true. requestCode = 1; intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true); } if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage sendIntent: " + intent); } sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0)); } try { smsManager.sendMultipartTextMessage(mDest, mServiceCenter, messages, sentIntents, deliveryIntents); } catch (Exception ex) { Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex); throw new MmsException("SmsMessageSender.sendMessage: caught " + ex + " from SmsManager.sendTextMessage()"); } if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) { log("sendMessage: address=" + mDest + ", threadId=" + mThreadId + ", uri=" + mUri + ", msgs.count=" + messageCount); } return false; }
public boolean sendMessage(long token) throws MmsException { if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage token: " + token); } if (mMessageText == null) { // Don't try to send an empty message, and destination should be just // one. throw new MmsException("Null message body or have multiple destinations."); } SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> messages = null; if ((MmsConfig.getEmailGateway() != null) && (Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) { String msgText; msgText = mDest + " " + mMessageText; mDest = MmsConfig.getEmailGateway(); messages = smsManager.divideMessage(msgText); } else { messages = smsManager.divideMessage(mMessageText); // remove spaces from destination number (e.g. "801 555 1212" -> "8015551212") mDest = mDest.replaceAll(" ", ""); mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest); } int messageCount = messages.size(); if (messageCount == 0) { // Don't try to send an empty message. throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned " + "empty messages. Original message is \"" + mMessageText + "\""); } boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0); if (!moved) { throw new MmsException("SmsMessageSender.sendMessage: couldn't move message " + "to outbox: " + mUri); } if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " + mRequestDeliveryReport); } ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount); ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount); for (int i = 0; i < messageCount; i++) { if (mRequestDeliveryReport && (i == (messageCount - 1))) { // TODO: Fix: It should not be necessary to // specify the class in this intent. Doing that // unnecessarily limits customizability. deliveryIntents.add(PendingIntent.getBroadcast( mContext, 0, new Intent( MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION, mUri, mContext, MessageStatusReceiver.class), 0)); } else { deliveryIntents.add(null); } Intent intent = new Intent(SmsReceiverService.MESSAGE_SENT_ACTION, mUri, mContext, SmsReceiver.class); int requestCode = 0; if (i == messageCount -1) { // Changing the requestCode so that a different pending intent // is created for the last fragment with // EXTRA_MESSAGE_SENT_SEND_NEXT set to true. requestCode = 1; intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true); } if (LogTag.DEBUG_SEND) { Log.v(TAG, "sendMessage sendIntent: " + intent); } sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0)); } try { smsManager.sendMultipartTextMessage(mDest, mServiceCenter, messages, sentIntents, deliveryIntents); } catch (Exception ex) { Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex); throw new MmsException("SmsMessageSender.sendMessage: caught " + ex + " from SmsManager.sendTextMessage()"); } if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) { log("sendMessage: address=" + mDest + ", threadId=" + mThreadId + ", uri=" + mUri + ", msgs.count=" + messageCount); } return false; }
diff --git a/POS/src/ee/ut/math/tvt/BSS/IntroUI.java b/POS/src/ee/ut/math/tvt/BSS/IntroUI.java index b661bf6..7c87cce 100644 --- a/POS/src/ee/ut/math/tvt/BSS/IntroUI.java +++ b/POS/src/ee/ut/math/tvt/BSS/IntroUI.java @@ -1,102 +1,102 @@ package ee.ut.math.tvt.BSS; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import org.apache.log4j.Logger; public class IntroUI extends JFrame{ private static final Logger log = Logger.getLogger(IntroUI.class); private JLabel TName; private JLabel TLeader; private JLabel TLEmail; private JLabel TMember1; private JLabel TMember2; private JLabel TMember3; private JLabel TMember4; private ImageIcon Logo; private JLabel LogoLabel; private JLabel Version; public IntroUI(){ super("IntroUI"); log.info("starting IntroUI"); try { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); TName = new JLabel("Team name: Brewery Software Solutions"); c.gridx = 0; c.gridy = 0; c.weighty = 1.0; c.weightx = 1.0; add(TName, c); TLeader = new JLabel("Team leader: Silver Tiik"); c.gridx = 0; c.gridy = 1; add(TLeader, c); TLEmail = new JLabel("Team leader email: [email protected]"); c.gridx = 0; c.gridy = 2; add(TLEmail, c); TMember1 = new JLabel("Silver Tiik"); c.gridx = 0; c.gridy = 3; add(TMember1, c); TMember2 = new JLabel("Kristian Hunt"); c.gridx = 0; c.gridy = 4; add(TMember2, c); TMember3 = new JLabel("Tanel Joosep"); c.gridx = 0; c.gridy = 5; add(TMember3, c); - TMember4 = new JLabel("Denis Юadan"); + TMember4 = new JLabel("Denis Žadan"); c.gridx = 0; c.gridy = 6; add(TMember4, c); Version = new JLabel("Software version: 0.1"); c.gridx = 0; c.gridy = 7; add(Version, c); Logo = new ImageIcon("logo.png"); LogoLabel = new JLabel(Logo); c.gridx = 1; c.gridy = 0; c.gridheight = 8; add(LogoLabel, c); int width = 700; int height = 400; setSize(width, height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - width) / 2, (screen.height - height) / 2); setVisible(true); log.info("Intro window is opened"); } catch (Exception e) { log.error(e.getMessage()); } finally { } } }
true
true
public IntroUI(){ super("IntroUI"); log.info("starting IntroUI"); try { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); TName = new JLabel("Team name: Brewery Software Solutions"); c.gridx = 0; c.gridy = 0; c.weighty = 1.0; c.weightx = 1.0; add(TName, c); TLeader = new JLabel("Team leader: Silver Tiik"); c.gridx = 0; c.gridy = 1; add(TLeader, c); TLEmail = new JLabel("Team leader email: [email protected]"); c.gridx = 0; c.gridy = 2; add(TLEmail, c); TMember1 = new JLabel("Silver Tiik"); c.gridx = 0; c.gridy = 3; add(TMember1, c); TMember2 = new JLabel("Kristian Hunt"); c.gridx = 0; c.gridy = 4; add(TMember2, c); TMember3 = new JLabel("Tanel Joosep"); c.gridx = 0; c.gridy = 5; add(TMember3, c); TMember4 = new JLabel("Denis Юadan"); c.gridx = 0; c.gridy = 6; add(TMember4, c); Version = new JLabel("Software version: 0.1"); c.gridx = 0; c.gridy = 7; add(Version, c); Logo = new ImageIcon("logo.png"); LogoLabel = new JLabel(Logo); c.gridx = 1; c.gridy = 0; c.gridheight = 8; add(LogoLabel, c); int width = 700; int height = 400; setSize(width, height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - width) / 2, (screen.height - height) / 2); setVisible(true); log.info("Intro window is opened"); } catch (Exception e) { log.error(e.getMessage()); } finally { } }
public IntroUI(){ super("IntroUI"); log.info("starting IntroUI"); try { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); TName = new JLabel("Team name: Brewery Software Solutions"); c.gridx = 0; c.gridy = 0; c.weighty = 1.0; c.weightx = 1.0; add(TName, c); TLeader = new JLabel("Team leader: Silver Tiik"); c.gridx = 0; c.gridy = 1; add(TLeader, c); TLEmail = new JLabel("Team leader email: [email protected]"); c.gridx = 0; c.gridy = 2; add(TLEmail, c); TMember1 = new JLabel("Silver Tiik"); c.gridx = 0; c.gridy = 3; add(TMember1, c); TMember2 = new JLabel("Kristian Hunt"); c.gridx = 0; c.gridy = 4; add(TMember2, c); TMember3 = new JLabel("Tanel Joosep"); c.gridx = 0; c.gridy = 5; add(TMember3, c); TMember4 = new JLabel("Denis Žadan"); c.gridx = 0; c.gridy = 6; add(TMember4, c); Version = new JLabel("Software version: 0.1"); c.gridx = 0; c.gridy = 7; add(Version, c); Logo = new ImageIcon("logo.png"); LogoLabel = new JLabel(Logo); c.gridx = 1; c.gridy = 0; c.gridheight = 8; add(LogoLabel, c); int width = 700; int height = 400; setSize(width, height); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - width) / 2, (screen.height - height) / 2); setVisible(true); log.info("Intro window is opened"); } catch (Exception e) { log.error(e.getMessage()); } finally { } }
diff --git a/server/src/com/chiorichan/command/defaults/UpdateCommand.java b/server/src/com/chiorichan/command/defaults/UpdateCommand.java index 66505be9..eb0814aa 100644 --- a/server/src/com/chiorichan/command/defaults/UpdateCommand.java +++ b/server/src/com/chiorichan/command/defaults/UpdateCommand.java @@ -1,161 +1,161 @@ package com.chiorichan.command.defaults; import java.io.File; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.chiorichan.ChatColor; import com.chiorichan.Loader; import com.chiorichan.command.CommandSender; import com.chiorichan.command.ConsoleCommandSender; import com.chiorichan.updater.BuildArtifact; import com.chiorichan.updater.Download; import com.chiorichan.updater.DownloadListener; import com.chiorichan.updater.OperatingSystem; import com.chiorichan.updater.UpdateInstaller; import com.google.common.base.Strings; public class UpdateCommand extends ChioriCommand { public UpdateCommand() { super( "update" ); this.description = "Gets the version of this server including any plugins in use"; this.usageMessage = "/update [latest]"; this.setPermission( "chiori.command.update" ); } @Override public boolean execute( CommandSender sender, String currentAlias, String[] args ) { if ( !Loader.getInstance().getAutoUpdater().isEnabled() ) { sender.sendMessage( ChatColor.RED + "I'm sorry but updates are disabled on this server per configs!" ); return true; } if ( Loader.getConfig().getBoolean( "auto-updater.console-only" ) && !( sender instanceof ConsoleCommandSender ) ) { sender.sendMessage( ChatColor.RED + "I'm sorry but updates can only be performed from the console!" ); return true; } if ( !testPermission( sender ) ) return true; if ( args.length == 0 ) { sender.sendMessage( ChatColor.AQUA + "Please wait as we check for updates..." ); Loader.getInstance().getAutoUpdater().check( sender ); } else { if ( args[0].equalsIgnoreCase( "latest" ) ) { try { if ( args.length > 1 && args[1].equalsIgnoreCase( "force" ) ) { BuildArtifact latest = Loader.getInstance().getAutoUpdater().getLatest(); if ( latest == null ) sender.sendMessage( ChatColor.RED + "Please review the latest version without \"force\" arg before updating." ); else { sender.sendMessage( ChatColor.YELLOW + "The server is now going into standby mode... Please wait as we download the latest version of Chiori Web Server..." ); Loader.unloadServer( "Preparing to install a new update!" ); File currentJar = new File( URLDecoder.decode( Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8" ) ); File updatedJar = new File( "update.jar" ); Download download = new Download( new URL( latest.getFile() ), updatedJar.getName(), updatedJar.getPath() ); download.setListener( new DownloadProgressDisplay( sender ) ); download.run(); ProcessBuilder processBuilder = new ProcessBuilder(); List<String> commands = new ArrayList<String>(); if ( OperatingSystem.getOperatingSystem().equals( OperatingSystem.WINDOWS ) ) { commands.add( "javaw" ); } else { commands.add( "java" ); } commands.add( "-Xmx256m" ); commands.add( "-cp" ); commands.add( updatedJar.getAbsolutePath() ); commands.add( UpdateInstaller.class.getName() ); commands.add( currentJar.getAbsolutePath() ); commands.add( "" + Runtime.getRuntime().maxMemory() ); // commands.addAll( Arrays.asList( args ) ); processBuilder.command( commands ); try { Process process = processBuilder.start(); process.exitValue(); - Loader.stop(); + Loader.getLogger().severe( "The Auto Updater failed to start. You can find the new Server Version at \"update.jar\"" ); } catch ( IllegalThreadStateException e ) { - Loader.getLogger().severe( "The Auto Updater failed to start. You can find the new Server Version at \"update.jar\"" ); + Loader.stop(); } catch ( Exception e ) { e.printStackTrace(); } } } else { sender.sendMessage( ChatColor.AQUA + "Please wait as we poll the Jenkins Build Server..." ); Loader.getInstance().getAutoUpdater().forceUpdate( sender ); } } catch ( Exception e ) { e.printStackTrace(); } } } return true; } private static class DownloadProgressDisplay implements DownloadListener { private final CommandSender sender; DownloadProgressDisplay(CommandSender _sender) { sender = _sender; sender.sendMessage( "" ); sender.pauseInput( true ); } @Override public void stateChanged( String text, float progress ) { sender.sendMessage( ChatColor.YELLOW + "" + ChatColor.NEGATIVE + text + " -> " + Math.round( progress ) + "% completed! " + ChatColor.DARK_AQUA + "[" + Strings.repeat( "=", Math.round( progress ) ) + Strings.repeat( " ", Math.round( 100 - progress ) ) + "]\r" ); } @Override public void stateDone() { sender.sendMessage( "\n" ); sender.pauseInput( false ); } } }
false
true
public boolean execute( CommandSender sender, String currentAlias, String[] args ) { if ( !Loader.getInstance().getAutoUpdater().isEnabled() ) { sender.sendMessage( ChatColor.RED + "I'm sorry but updates are disabled on this server per configs!" ); return true; } if ( Loader.getConfig().getBoolean( "auto-updater.console-only" ) && !( sender instanceof ConsoleCommandSender ) ) { sender.sendMessage( ChatColor.RED + "I'm sorry but updates can only be performed from the console!" ); return true; } if ( !testPermission( sender ) ) return true; if ( args.length == 0 ) { sender.sendMessage( ChatColor.AQUA + "Please wait as we check for updates..." ); Loader.getInstance().getAutoUpdater().check( sender ); } else { if ( args[0].equalsIgnoreCase( "latest" ) ) { try { if ( args.length > 1 && args[1].equalsIgnoreCase( "force" ) ) { BuildArtifact latest = Loader.getInstance().getAutoUpdater().getLatest(); if ( latest == null ) sender.sendMessage( ChatColor.RED + "Please review the latest version without \"force\" arg before updating." ); else { sender.sendMessage( ChatColor.YELLOW + "The server is now going into standby mode... Please wait as we download the latest version of Chiori Web Server..." ); Loader.unloadServer( "Preparing to install a new update!" ); File currentJar = new File( URLDecoder.decode( Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8" ) ); File updatedJar = new File( "update.jar" ); Download download = new Download( new URL( latest.getFile() ), updatedJar.getName(), updatedJar.getPath() ); download.setListener( new DownloadProgressDisplay( sender ) ); download.run(); ProcessBuilder processBuilder = new ProcessBuilder(); List<String> commands = new ArrayList<String>(); if ( OperatingSystem.getOperatingSystem().equals( OperatingSystem.WINDOWS ) ) { commands.add( "javaw" ); } else { commands.add( "java" ); } commands.add( "-Xmx256m" ); commands.add( "-cp" ); commands.add( updatedJar.getAbsolutePath() ); commands.add( UpdateInstaller.class.getName() ); commands.add( currentJar.getAbsolutePath() ); commands.add( "" + Runtime.getRuntime().maxMemory() ); // commands.addAll( Arrays.asList( args ) ); processBuilder.command( commands ); try { Process process = processBuilder.start(); process.exitValue(); Loader.stop(); } catch ( IllegalThreadStateException e ) { Loader.getLogger().severe( "The Auto Updater failed to start. You can find the new Server Version at \"update.jar\"" ); } catch ( Exception e ) { e.printStackTrace(); } } } else { sender.sendMessage( ChatColor.AQUA + "Please wait as we poll the Jenkins Build Server..." ); Loader.getInstance().getAutoUpdater().forceUpdate( sender ); } } catch ( Exception e ) { e.printStackTrace(); } } } return true; }
public boolean execute( CommandSender sender, String currentAlias, String[] args ) { if ( !Loader.getInstance().getAutoUpdater().isEnabled() ) { sender.sendMessage( ChatColor.RED + "I'm sorry but updates are disabled on this server per configs!" ); return true; } if ( Loader.getConfig().getBoolean( "auto-updater.console-only" ) && !( sender instanceof ConsoleCommandSender ) ) { sender.sendMessage( ChatColor.RED + "I'm sorry but updates can only be performed from the console!" ); return true; } if ( !testPermission( sender ) ) return true; if ( args.length == 0 ) { sender.sendMessage( ChatColor.AQUA + "Please wait as we check for updates..." ); Loader.getInstance().getAutoUpdater().check( sender ); } else { if ( args[0].equalsIgnoreCase( "latest" ) ) { try { if ( args.length > 1 && args[1].equalsIgnoreCase( "force" ) ) { BuildArtifact latest = Loader.getInstance().getAutoUpdater().getLatest(); if ( latest == null ) sender.sendMessage( ChatColor.RED + "Please review the latest version without \"force\" arg before updating." ); else { sender.sendMessage( ChatColor.YELLOW + "The server is now going into standby mode... Please wait as we download the latest version of Chiori Web Server..." ); Loader.unloadServer( "Preparing to install a new update!" ); File currentJar = new File( URLDecoder.decode( Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8" ) ); File updatedJar = new File( "update.jar" ); Download download = new Download( new URL( latest.getFile() ), updatedJar.getName(), updatedJar.getPath() ); download.setListener( new DownloadProgressDisplay( sender ) ); download.run(); ProcessBuilder processBuilder = new ProcessBuilder(); List<String> commands = new ArrayList<String>(); if ( OperatingSystem.getOperatingSystem().equals( OperatingSystem.WINDOWS ) ) { commands.add( "javaw" ); } else { commands.add( "java" ); } commands.add( "-Xmx256m" ); commands.add( "-cp" ); commands.add( updatedJar.getAbsolutePath() ); commands.add( UpdateInstaller.class.getName() ); commands.add( currentJar.getAbsolutePath() ); commands.add( "" + Runtime.getRuntime().maxMemory() ); // commands.addAll( Arrays.asList( args ) ); processBuilder.command( commands ); try { Process process = processBuilder.start(); process.exitValue(); Loader.getLogger().severe( "The Auto Updater failed to start. You can find the new Server Version at \"update.jar\"" ); } catch ( IllegalThreadStateException e ) { Loader.stop(); } catch ( Exception e ) { e.printStackTrace(); } } } else { sender.sendMessage( ChatColor.AQUA + "Please wait as we poll the Jenkins Build Server..." ); Loader.getInstance().getAutoUpdater().forceUpdate( sender ); } } catch ( Exception e ) { e.printStackTrace(); } } } return true; }
diff --git a/src/org/subethamail/smtp/server/Session.java b/src/org/subethamail/smtp/server/Session.java index 8e5916b..a29781c 100644 --- a/src/org/subethamail/smtp/server/Session.java +++ b/src/org/subethamail/smtp/server/Session.java @@ -1,451 +1,452 @@ package org.subethamail.smtp.server; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.security.cert.Certificate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.smtp.AuthenticationHandler; import org.subethamail.smtp.DropConnectionException; import org.subethamail.smtp.MessageContext; import org.subethamail.smtp.MessageHandler; import org.subethamail.smtp.io.CRLFTerminatedReader; /** * The thread that handles a connection. This class * passes most of it's responsibilities off to the * CommandHandler. * * @author Jon Stevens * @author Jeff Schnitzer */ public class Session extends Thread implements MessageContext { private final static Logger log = LoggerFactory.getLogger(Session.class); /** A link to our parent server */ private SMTPServer server; /** Set this true when doing an ordered shutdown */ private boolean quitting = false; /** I/O to the client */ private Socket socket; private InputStream input; private CRLFTerminatedReader reader; private PrintWriter writer; /** Might exist if the client has successfully authenticated */ private AuthenticationHandler authenticationHandler; /** Might exist if the client is giving us a message */ private MessageHandler messageHandler; /** Some state information */ private String helo; private boolean hasMailFrom; private int recipientCount; /** * If the client told us the size of the message, this is the value. * If they didn't, the value will be 0. */ private int declaredMessageSize = 0; /** Some more state information */ private boolean tlsStarted; private Certificate[] tlsPeerCertificates; /** * Creates (but does not start) the thread object. * * @param server a link to our parent * @param socket is the socket to the client * @throws IOException */ public Session(SMTPServer server, Socket socket) throws IOException { super(server.getSessionGroup(), Session.class.getName() + "-" + socket.getInetAddress() + ":" + socket.getPort()); this.server = server; this.setSocket(socket); } /** * @return a reference to the master server object */ public SMTPServer getServer() { return this.server; } /** * The thread for each session runs on this and shuts down when the shutdown member goes true. */ @Override public void run() { if (log.isDebugEnabled()) { InetAddress remoteInetAddress = this.getRemoteAddress().getAddress(); remoteInetAddress.getHostName(); // Causes future toString() to print the name too log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress, this.server.getNumberOfConnections()); } try { if (this.server.hasTooManyConnections()) { log.debug("SMTP Too many connections!"); this.sendResponse("421 Too many connections, try again later"); return; } this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getSoftwareName()); // Start with fresh message state this.resetMessageState(); while (!this.quitting) { try { String line = null; try { line = this.reader.readLine(); } catch (SocketException ex) { // Lots of clients just "hang up" rather than issuing QUIT, which would // fill our logs with the warning in the outer catch. if (log.isDebugEnabled()) log.debug("Error reading client command: " + ex.getMessage(), ex); return; } if (line == null) { log.debug("no more lines from client"); return; } if (log.isDebugEnabled()) log.debug("Client: " + line); this.server.getCommandHandler().handleCommand(this, line); } catch (DropConnectionException ex) { this.sendResponse(ex.getErrorResponse()); + return; } catch (SocketTimeoutException ex) { this.sendResponse("421 Timeout waiting for data from client."); return; } catch (CRLFTerminatedReader.TerminationException te) { String msg = "501 Syntax error at character position " + te.position() + ". CR and LF must be CRLF paired. See RFC 2821 #2.7.1."; log.debug(msg); this.sendResponse(msg); // if people are screwing with things, close connection return; } catch (CRLFTerminatedReader.MaxLineLengthException mlle) { String msg = "501 " + mlle.getMessage(); log.debug(msg); this.sendResponse(msg); // if people are screwing with things, close connection return; } } } catch (IOException e1) { if (!this.quitting) { try { // Send a temporary failure back so that the server will try to resend // the message later. this.sendResponse("450 Problem attempting to execute commands. Please try again later."); } catch (IOException e) {} if (log.isWarnEnabled()) log.warn("Exception during SMTP transaction", e1); } } finally { this.closeConnection(); this.endMessageHandler(); } } /** * Close reader, writer, and socket, logging exceptions but otherwise ignoring them */ private void closeConnection() { try { try { this.writer.close(); this.input.close(); } finally { this.closeSocket(); } } catch (IOException e) { log.info(e.toString()); } } /** * Initializes our reader, writer, and the i/o filter chains based on * the specified socket. This is called internally when we startup * and when (if) SSL is started. */ public void setSocket(Socket socket) throws IOException { this.socket = socket; this.input = this.socket.getInputStream(); this.reader = new CRLFTerminatedReader(this.input); this.writer = new PrintWriter(this.socket.getOutputStream()); this.socket.setSoTimeout(this.server.getConnectionTimeout()); } /** * This method is only used by the start tls command * @return the current socket to the client */ public Socket getSocket() { return this.socket; } /** Close the client socket if it is open */ public void closeSocket() throws IOException { if ((this.socket != null) && this.socket.isBound() && !this.socket.isClosed()) this.socket.close(); } /** * @return the raw input stream from the client */ public InputStream getRawInput() { return this.input; } /** * @return the cooked CRLF-terminated reader from the client */ public CRLFTerminatedReader getReader() { return this.reader; } /** Sends the response to the client */ public void sendResponse(String response) throws IOException { if (log.isDebugEnabled()) log.debug("Server: " + response); this.writer.print(response + "\r\n"); this.writer.flush(); } /* (non-Javadoc) * @see org.subethamail.smtp.MessageContext#getRemoteAddress() */ public InetSocketAddress getRemoteAddress() { return (InetSocketAddress)this.socket.getRemoteSocketAddress(); } /* (non-Javadoc) * @see org.subethamail.smtp.MessageContext#getSMTPServer() */ public SMTPServer getSMTPServer() { return this.server; } /** * @return the current message handler */ public MessageHandler getMessageHandler() { return this.messageHandler; } /** Simple state */ public String getHelo() { return this.helo; } /** */ public void setHelo(String value) { this.helo = value; } /** */ public boolean getHasMailFrom() { return this.hasMailFrom; } /** */ public void setHasMailFrom(boolean value) { this.hasMailFrom = value; } /** */ public void addRecipient() { this.recipientCount++; } /** */ public int getRecipientCount() { return this.recipientCount; } /** */ public boolean isAuthenticated() { return this.authenticationHandler != null; } /** */ public AuthenticationHandler getAuthenticationHandler() { return this.authenticationHandler; } /** * This is called by the AuthCommand when a session is successfully authenticated. The * handler will be an object created by the AuthenticationHandlerFactory. */ public void setAuthenticationHandler(AuthenticationHandler handler) { this.authenticationHandler = handler; } /** * @return the maxMessageSize */ public int getDeclaredMessageSize() { return this.declaredMessageSize; } /** * @param declaredMessageSize the size that the client says the message will be */ public void setDeclaredMessageSize(int declaredMessageSize) { this.declaredMessageSize = declaredMessageSize; } /** * Some state is associated with each particular message (senders, recipients, the message handler). * Some state is not; seeing hello, TLS, authentication. */ public void resetMessageState() { this.endMessageHandler(); this.messageHandler = this.server.getMessageHandlerFactory().create(this); this.helo = null; this.hasMailFrom = false; this.recipientCount = 0; this.declaredMessageSize = 0; } /** Safely calls done() on a message hander, if one exists */ protected void endMessageHandler() { if (this.messageHandler != null) { try { this.messageHandler.done(); } catch (Exception ex) { log.error("done() threw exception", ex); } } } /** * Triggers the shutdown of the thread and the closing of the connection. */ public void quit() { this.quitting = true; this.closeConnection(); } /** * @return true when the TLS handshake was completed, false otherwise */ public boolean isTLSStarted() { return tlsStarted; } /** * @param tlsStarted true when the TLS handshake was completed, false otherwise */ public void setTlsStarted(boolean tlsStarted) { this.tlsStarted = tlsStarted; } public void setTlsPeerCertificates(Certificate[] tlsPeerCertificates) { this.tlsPeerCertificates = tlsPeerCertificates; } /** * {@inheritDoc} */ public Certificate[] getTlsPeerCertificates() { return tlsPeerCertificates; } }
true
true
public void run() { if (log.isDebugEnabled()) { InetAddress remoteInetAddress = this.getRemoteAddress().getAddress(); remoteInetAddress.getHostName(); // Causes future toString() to print the name too log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress, this.server.getNumberOfConnections()); } try { if (this.server.hasTooManyConnections()) { log.debug("SMTP Too many connections!"); this.sendResponse("421 Too many connections, try again later"); return; } this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getSoftwareName()); // Start with fresh message state this.resetMessageState(); while (!this.quitting) { try { String line = null; try { line = this.reader.readLine(); } catch (SocketException ex) { // Lots of clients just "hang up" rather than issuing QUIT, which would // fill our logs with the warning in the outer catch. if (log.isDebugEnabled()) log.debug("Error reading client command: " + ex.getMessage(), ex); return; } if (line == null) { log.debug("no more lines from client"); return; } if (log.isDebugEnabled()) log.debug("Client: " + line); this.server.getCommandHandler().handleCommand(this, line); } catch (DropConnectionException ex) { this.sendResponse(ex.getErrorResponse()); } catch (SocketTimeoutException ex) { this.sendResponse("421 Timeout waiting for data from client."); return; } catch (CRLFTerminatedReader.TerminationException te) { String msg = "501 Syntax error at character position " + te.position() + ". CR and LF must be CRLF paired. See RFC 2821 #2.7.1."; log.debug(msg); this.sendResponse(msg); // if people are screwing with things, close connection return; } catch (CRLFTerminatedReader.MaxLineLengthException mlle) { String msg = "501 " + mlle.getMessage(); log.debug(msg); this.sendResponse(msg); // if people are screwing with things, close connection return; } } } catch (IOException e1) { if (!this.quitting) { try { // Send a temporary failure back so that the server will try to resend // the message later. this.sendResponse("450 Problem attempting to execute commands. Please try again later."); } catch (IOException e) {} if (log.isWarnEnabled()) log.warn("Exception during SMTP transaction", e1); } } finally { this.closeConnection(); this.endMessageHandler(); } }
public void run() { if (log.isDebugEnabled()) { InetAddress remoteInetAddress = this.getRemoteAddress().getAddress(); remoteInetAddress.getHostName(); // Causes future toString() to print the name too log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress, this.server.getNumberOfConnections()); } try { if (this.server.hasTooManyConnections()) { log.debug("SMTP Too many connections!"); this.sendResponse("421 Too many connections, try again later"); return; } this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getSoftwareName()); // Start with fresh message state this.resetMessageState(); while (!this.quitting) { try { String line = null; try { line = this.reader.readLine(); } catch (SocketException ex) { // Lots of clients just "hang up" rather than issuing QUIT, which would // fill our logs with the warning in the outer catch. if (log.isDebugEnabled()) log.debug("Error reading client command: " + ex.getMessage(), ex); return; } if (line == null) { log.debug("no more lines from client"); return; } if (log.isDebugEnabled()) log.debug("Client: " + line); this.server.getCommandHandler().handleCommand(this, line); } catch (DropConnectionException ex) { this.sendResponse(ex.getErrorResponse()); return; } catch (SocketTimeoutException ex) { this.sendResponse("421 Timeout waiting for data from client."); return; } catch (CRLFTerminatedReader.TerminationException te) { String msg = "501 Syntax error at character position " + te.position() + ". CR and LF must be CRLF paired. See RFC 2821 #2.7.1."; log.debug(msg); this.sendResponse(msg); // if people are screwing with things, close connection return; } catch (CRLFTerminatedReader.MaxLineLengthException mlle) { String msg = "501 " + mlle.getMessage(); log.debug(msg); this.sendResponse(msg); // if people are screwing with things, close connection return; } } } catch (IOException e1) { if (!this.quitting) { try { // Send a temporary failure back so that the server will try to resend // the message later. this.sendResponse("450 Problem attempting to execute commands. Please try again later."); } catch (IOException e) {} if (log.isWarnEnabled()) log.warn("Exception during SMTP transaction", e1); } } finally { this.closeConnection(); this.endMessageHandler(); } }
diff --git a/src/gnu/prolog/database/PrologTextLoaderState.java b/src/gnu/prolog/database/PrologTextLoaderState.java index 0874586..55f6cba 100644 --- a/src/gnu/prolog/database/PrologTextLoaderState.java +++ b/src/gnu/prolog/database/PrologTextLoaderState.java @@ -1,567 +1,567 @@ /* GNU Prolog for Java * Copyright (C) 1997-1999 Constantine Plotnikov * Copyright (C) 2010 Daniel Thomas * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. The text of license can be also found * at http://www.gnu.org/copyleft/lgpl.html */ package gnu.prolog.database; import gnu.prolog.io.CharConversionTable; import gnu.prolog.io.ParseException; import gnu.prolog.io.TermWriter; import gnu.prolog.term.AtomTerm; import gnu.prolog.term.CompoundTerm; import gnu.prolog.term.CompoundTermTag; import gnu.prolog.term.Term; import gnu.prolog.vm.Environment; import gnu.prolog.vm.HasEnvironment; import gnu.prolog.vm.Interpreter; import gnu.prolog.vm.PrologException; import gnu.prolog.vm.TermConstants; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Stores the state of all the {@link PrologTextLoader PrologTextLoaders} for * the {@link Environment} instance it is for. * */ public class PrologTextLoaderState implements PrologTextLoaderListener, HasEnvironment { protected final Module module = new Module(); protected Map<Predicate, Map<String, Set<PrologTextLoader>>> predicate2options2loaders = new HashMap<Predicate, Map<String, Set<PrologTextLoader>>>(); protected Predicate currentPredicate = null; protected List<PrologTextLoaderError> errorList = new ArrayList<PrologTextLoaderError>(); protected Set<String> loadedFiles = new HashSet<String>(); protected CharConversionTable convTable = new CharConversionTable(); protected List<PrologTextLoaderListener> listeners = new ArrayList<PrologTextLoaderListener>(); private Environment environment; // arguments of ensure_loaded/1 and include/2 directive protected final static CompoundTermTag resourceTag = CompoundTermTag.get("resource", 1); protected final static CompoundTermTag urlTag = CompoundTermTag.get("url", 1); protected final static CompoundTermTag fileTag = CompoundTermTag.get("file", 1); public PrologTextLoaderState(Environment env) { environment = env; } public Environment getEnvironment() { return environment; } public List<PrologTextLoaderError> getErrors() { return errorList; } public Module getModule() { return module; } /** * @return the convTable */ public CharConversionTable getConversionTable() { return convTable; } protected boolean testOption(PrologTextLoader loader, Predicate p, String option) { Map<String, Set<PrologTextLoader>> options2loaders = predicate2options2loaders.get(p); if (options2loaders == null) { return false; } Set<PrologTextLoader> loaders = options2loaders.get(option); if (loaders == null) { return false; } if (loader != null && !loaders.contains(loader)) { return false; } return true; } protected void defineOption(PrologTextLoader loader, Predicate p, String option) { Map<String, Set<PrologTextLoader>> options2loaders = predicate2options2loaders.get(p); if (options2loaders == null) { options2loaders = new HashMap<String, Set<PrologTextLoader>>(); predicate2options2loaders.put(p, options2loaders); } Set<PrologTextLoader> loaders = options2loaders.get(option); if (loaders == null) { loaders = new HashSet<PrologTextLoader>(); options2loaders.put(option, loaders); } if (!loaders.contains(loader)) { loaders.add(loader); } } protected void defineOptionAndDeclare(PrologTextLoader loader, Predicate p, String option) { defineOption(loader, p, option); defineOption(loader, p, "declared"); } protected boolean isDeclaredInOtherLoaders(PrologTextLoader loader, Predicate p) { Map<String, Set<PrologTextLoader>> options2loaders = predicate2options2loaders.get(p); if (options2loaders == null) { return false; } Set<PrologTextLoader> loaders = options2loaders.get("declared"); if (loaders == null || loaders.isEmpty()) { return false; } Iterator<PrologTextLoader> i = loaders.iterator(); while (i.hasNext()) { if (loader != i.next()) { return true; } } return false; } public boolean declareDynamic(PrologTextLoader loader, CompoundTermTag tag) { Predicate p = module.getOrCreateDefinedPredicate(tag); if (testOption(loader, p, "dynamic")) { return true; } if (isDeclaredInOtherLoaders(loader, p)) { if (!testOption(loader, p, "multifile")) { logError(loader, "non multifile predicate could not be changed in other prolog text."); return false; } if (!testOption(null, p, "dynamic")) { logError(loader, "predicate was not declared dynamic in other texts, dynamic option should be the same in each prolog text."); return false; } } else { if (testOption(loader, p, "defined")) { logError(loader, "predicate was already defined and could not be declared dynamic."); return false; } } if (p.getType() == Predicate.TYPE.UNDEFINED) { p.setType(Predicate.TYPE.USER_DEFINED); } p.setDynamic(); defineOptionAndDeclare(loader, p, "dynamic"); return true; } public void declareMultifile(PrologTextLoader loader, CompoundTermTag tag) { Predicate p = module.getOrCreateDefinedPredicate(tag); if (testOption(loader, p, "multifile")) { return; } if (isDeclaredInOtherLoaders(loader, p)) { if (!testOption(null, p, "multifile")) { logError(loader, "non multifile predicate could not be changed in other prolog text."); return; } } else { if (testOption(loader, p, "defined")) { logError(loader, "predicate was already defined and could not be declared multifile."); return; } } if (p.getType() == Predicate.TYPE.UNDEFINED) { p.setType(Predicate.TYPE.USER_DEFINED); } defineOptionAndDeclare(loader, p, "multifile"); } public void declareDiscontiguous(PrologTextLoader loader, CompoundTermTag tag) { Predicate p = module.getOrCreateDefinedPredicate(tag); if (testOption(loader, p, "discontiguous")) { return; } if (isDeclaredInOtherLoaders(loader, p)) { if (!testOption(null, p, "multifile")) { logError(loader, "non multifile predicate could not be changed in other prolog text."); return; } } if (testOption(loader, p, "defined")) { logError(loader, "predicate was already defined and could not be declared discontiguous."); return; } if (p.getType() == Predicate.TYPE.UNDEFINED) { p.setType(Predicate.TYPE.USER_DEFINED); } defineOptionAndDeclare(loader, p, "discontiguous"); } public void addClause(PrologTextLoader loader, Term term) { Term head = term; CompoundTermTag headTag; if (term instanceof CompoundTerm && ((CompoundTerm) term).tag == TermConstants.clauseTag) { head = ((CompoundTerm) term).args[0]; } if (head instanceof AtomTerm) { headTag = CompoundTermTag.get((AtomTerm) head, 0); } else if (head instanceof CompoundTerm) { headTag = ((CompoundTerm) head).tag; } else { logError(loader, "predicate head is not a callable term."); return; } if (currentPredicate == null || headTag != currentPredicate.getTag()) { currentPredicate = null; Predicate p = module.getOrCreateDefinedPredicate(headTag); if (testOption(loader, p, "defined") && !testOption(loader, p, "discontiguous")) { logError(loader, "predicate is not discontiguous."); return; } if (!testOption(loader, p, "declared") && testOption(null, p, "declared") && !testOption(loader, p, "multifile")) { - logError(loader, "predicate is not multifile."); + logError(loader, "predicate is not multifile: " + p.getTag()); return; } if (!testOption(loader, p, "dynamic") && testOption(null, p, "dynamic")) { logError(loader, "predicate is not declared dynamic in this prolog text."); return; } currentPredicate = p; if (!testOption(loader, p, "defined")) { if (p.getType() == Predicate.TYPE.UNDEFINED) { p.setType(Predicate.TYPE.USER_DEFINED); } defineOptionAndDeclare(loader, p, "defined"); } } try { currentPredicate.addClauseLast(Predicate.prepareClause(term)); } catch (PrologException ex) { logError(loader, ex.getMessage()); } } public void defineExternal(PrologTextLoader loader, CompoundTerm pi, String javaClassName, Predicate.TYPE type) { if (!CompoundTermTag.isPredicateIndicator(pi)) { logError(loader, "predicate indicator is not valid."); return; } CompoundTermTag tag = CompoundTermTag.get(pi); Predicate p = module.getOrCreateDefinedPredicate(tag); if (p.getType() != Predicate.TYPE.UNDEFINED) { logError(loader, "predicate type could not be changed."); return; } p.setType(type); p.setJavaClassName(javaClassName); defineOptionAndDeclare(loader, p, "defined"); } public void logError(PrologTextLoader loader, ParseException ex) { errorList.add(new PrologTextLoaderError(loader, ex)); } public void logError(PrologTextLoader loader, String message) { errorList.add(new PrologTextLoaderError(loader, message)); } /** * To be used for errors during initialisation * * @see #logError(PrologTextLoader,String) * @see Environment#runInitialization(Interpreter) * * @param partialError * the partially filled in error (missing message) * @param message * the message to add */ public void logError(PrologTextLoaderError partialError, String message) { errorList.add(new PrologTextLoaderError(partialError, message)); } public void addInitialization(PrologTextLoader loader, Term term) { module.addInitialization(loader.getCurrentPartialLoaderError(), term); } public void ensureLoaded(Term term) { String inputName = getInputName(term); if (!loadedFiles.contains(inputName)) { loadedFiles.add(inputName); new PrologTextLoader(this, term); } } /** * Resolve the input filename. Will add a .pl or .pro when needed. * * @param filename * @return the file object resolved from the filename */ protected File resolveInputFile(String filename) { File fl = new File(filename); if (fl.exists()) { return fl; } if (!(filename.endsWith(".pl") || filename.endsWith(".pro"))) { fl = new File(filename + ".pro"); if (fl.exists()) { return fl; } fl = new File(filename + ".pl"); if (fl.exists()) { return fl; } } return new File(filename);// reset here as we might have added a .pl } protected String getInputName(Term term) { if (term instanceof AtomTerm) // argument is an atom, which is an filename { return resolveInputFile(((AtomTerm) term).value).toString(); } else if (term instanceof CompoundTerm) { CompoundTerm ct = (CompoundTerm) term; if (ct.tag == fileTag) { if (ct.args[0] instanceof AtomTerm) { return resolveInputFile(getInputName(ct.args[0])).toString(); } } else if (ct.tag == urlTag || ct.tag == resourceTag) { if (ct.args[0] instanceof AtomTerm) { AtomTerm arg = (AtomTerm) ct.args[0]; if (ct.tag == urlTag) { return "url:" + arg.value; } else // resource tag { return "resource:" + arg.value; } } } } return "bad_input(" + TermWriter.toString(term) + ")"; } protected InputStream getInputStream(Term term) throws IOException { if (term instanceof AtomTerm) // argument is an atom, which is an filename { return new FileInputStream(resolveInputFile(((AtomTerm) term).value)); } else if (term instanceof CompoundTerm) { CompoundTerm ct = (CompoundTerm) term; if (ct.tag == fileTag) { if (!(ct.args[0] instanceof AtomTerm)) { throw new IOException("unknown type of datasource"); } return getInputStream(ct.args[0]); } else if (ct.tag == urlTag || ct.tag == resourceTag) { URL url; if (!(ct.args[0] instanceof AtomTerm)) { throw new IOException("unknown type of datasource"); } AtomTerm arg = (AtomTerm) ct.args[0]; if (ct.tag == urlTag) { url = new URL(arg.value); } else // resource tag { url = getClass().getResource(arg.value); if (url == null) { throw new IOException("resource not found"); } } return url.openStream(); } } throw new IOException("unknown type of datasource"); } public boolean addPrologTextLoaderListener(PrologTextLoaderListener listener) { if (listener == null || listener == this) { return false; } return listeners.add(listener); } public boolean removePrologTextLoaderListener(PrologTextLoaderListener listener) { return listeners.remove(listener); } /* * (non-Javadoc) * * @see * gnu.prolog.database.PrologTextLoaderListener#afterIncludeFile(gnu.prolog * .database.PrologTextLoader) */ public void afterIncludeFile(PrologTextLoader loader) { for (PrologTextLoaderListener listener : listeners) { listener.afterIncludeFile(loader); } } /* * (non-Javadoc) * * @see * gnu.prolog.database.PrologTextLoaderListener#afterProcessFile(gnu.prolog * .database.PrologTextLoader) */ public void afterProcessFile(PrologTextLoader loader) { for (PrologTextLoaderListener listener : listeners) { listener.afterProcessFile(loader); } } /* * (non-Javadoc) * * @see * gnu.prolog.database.PrologTextLoaderListener#beforeIncludeFile(gnu.prolog * .database.PrologTextLoader, gnu.prolog.term.Term) */ public void beforeIncludeFile(PrologTextLoader loader, Term argument) { for (PrologTextLoaderListener listener : listeners) { listener.beforeIncludeFile(loader, argument); } } /* * (non-Javadoc) * * @see * gnu.prolog.database.PrologTextLoaderListener#beforeProcessFile(gnu.prolog * .database.PrologTextLoader) */ public void beforeProcessFile(PrologTextLoader loader) { for (PrologTextLoaderListener listener : listeners) { listener.beforeProcessFile(loader); } } }
true
true
public void addClause(PrologTextLoader loader, Term term) { Term head = term; CompoundTermTag headTag; if (term instanceof CompoundTerm && ((CompoundTerm) term).tag == TermConstants.clauseTag) { head = ((CompoundTerm) term).args[0]; } if (head instanceof AtomTerm) { headTag = CompoundTermTag.get((AtomTerm) head, 0); } else if (head instanceof CompoundTerm) { headTag = ((CompoundTerm) head).tag; } else { logError(loader, "predicate head is not a callable term."); return; } if (currentPredicate == null || headTag != currentPredicate.getTag()) { currentPredicate = null; Predicate p = module.getOrCreateDefinedPredicate(headTag); if (testOption(loader, p, "defined") && !testOption(loader, p, "discontiguous")) { logError(loader, "predicate is not discontiguous."); return; } if (!testOption(loader, p, "declared") && testOption(null, p, "declared") && !testOption(loader, p, "multifile")) { logError(loader, "predicate is not multifile."); return; } if (!testOption(loader, p, "dynamic") && testOption(null, p, "dynamic")) { logError(loader, "predicate is not declared dynamic in this prolog text."); return; } currentPredicate = p; if (!testOption(loader, p, "defined")) { if (p.getType() == Predicate.TYPE.UNDEFINED) { p.setType(Predicate.TYPE.USER_DEFINED); } defineOptionAndDeclare(loader, p, "defined"); } } try { currentPredicate.addClauseLast(Predicate.prepareClause(term)); } catch (PrologException ex) { logError(loader, ex.getMessage()); } }
public void addClause(PrologTextLoader loader, Term term) { Term head = term; CompoundTermTag headTag; if (term instanceof CompoundTerm && ((CompoundTerm) term).tag == TermConstants.clauseTag) { head = ((CompoundTerm) term).args[0]; } if (head instanceof AtomTerm) { headTag = CompoundTermTag.get((AtomTerm) head, 0); } else if (head instanceof CompoundTerm) { headTag = ((CompoundTerm) head).tag; } else { logError(loader, "predicate head is not a callable term."); return; } if (currentPredicate == null || headTag != currentPredicate.getTag()) { currentPredicate = null; Predicate p = module.getOrCreateDefinedPredicate(headTag); if (testOption(loader, p, "defined") && !testOption(loader, p, "discontiguous")) { logError(loader, "predicate is not discontiguous."); return; } if (!testOption(loader, p, "declared") && testOption(null, p, "declared") && !testOption(loader, p, "multifile")) { logError(loader, "predicate is not multifile: " + p.getTag()); return; } if (!testOption(loader, p, "dynamic") && testOption(null, p, "dynamic")) { logError(loader, "predicate is not declared dynamic in this prolog text."); return; } currentPredicate = p; if (!testOption(loader, p, "defined")) { if (p.getType() == Predicate.TYPE.UNDEFINED) { p.setType(Predicate.TYPE.USER_DEFINED); } defineOptionAndDeclare(loader, p, "defined"); } } try { currentPredicate.addClauseLast(Predicate.prepareClause(term)); } catch (PrologException ex) { logError(loader, ex.getMessage()); } }
diff --git a/src/opt/boilercontrol/uk/co/jaynne/Scheduler.java b/src/opt/boilercontrol/uk/co/jaynne/Scheduler.java index 2ce07a3..cb00a78 100755 --- a/src/opt/boilercontrol/uk/co/jaynne/Scheduler.java +++ b/src/opt/boilercontrol/uk/co/jaynne/Scheduler.java @@ -1,126 +1,126 @@ package uk.co.jaynne; import java.util.Calendar; import java.util.Set; import java.util.TimeZone; import java.util.Date; import uk.co.jaynne.dataobjects.ScheduleObject; import uk.co.jaynne.datasource.ScheduleSqlSource; import uk.co.jaynne.datasource.interfaces.ScheduleSource; public class Scheduler extends Thread{ private ControlBroker control = ControlBroker.getInstance(); public void run() { while (!Thread.interrupted()) { //Heating and water default to off Calendar calendar = Calendar.getInstance(); /** TimeZone z = calendar.getTimeZone(); int offset = z.getRawOffset(); if(z.inDaylightTime(new Date())){ offset = offset + z.getDSTSavings(); } int offsetHrs = offset / 1000 / 60 / 60; int offsetMins = offset / 1000 / 60 % 60; calendar.add(Calendar.HOUR_OF_DAY, (-offsetHrs)); calendar.add(Calendar.MINUTE, (-offsetMins)); /**/ boolean heating = false; boolean water = false; //Get the day and minute int day = calendar.get(Calendar.DAY_OF_WEEK); int minute = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE); ScheduleSource ss = new ScheduleSqlSource(); //Get the schedules for today Set<ScheduleObject> schedules = ss.getByDay(day); if (schedules == null) { System.out.println("No schedules today"); } else { System.out.println("Time: " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE)); System.out.println("WB: " + control.isWaterBoostOn() + ", WB Finish: " + control.getWaterBoostOffTime()); System.out.println("HB: " + control.isHeatingBoostOn() + ", HB Finish: " + control.getHeatingBoostOffTime()); System.out.println("Currently Desired Temp Set to: " + control.getdesired_temp()); //Loop through all of todays schedules for (ScheduleObject schedule : schedules) { if (schedule.getEnabled()) { //if enabled System.out.print("*"); System.out.print(schedule); //if in active period int timeOnMins = (schedule.getHourOn() * 60) + schedule.getMinuteOn(); int timeOffMins = (schedule.getHourOff() * 60) + schedule.getMinuteOff(); if (minute >= timeOnMins && minute < timeOffMins) { //Including starting minute, excluding ending minute System.out.print(" **ACTIVE**"); //If Boost is ON or desired_temp was manually changed do not overwrite boost desired_temp with scheduled if ((!control.isHeatingBoostOn()) && (!control.ismanual_desired_tempOn())) { System.out.println("Overwriting current desired_temp with scheduled"); control.setdesired_temp(schedule.getTempSet()); } //Only update the h/w status if they are false heating = (heating) ? heating : schedule.getHeatingOn(); water = (water) ? water : schedule.getWaterOn(); } System.out.println(); } else { System.out.print("-"); System.out.println(schedule); } } System.out.println("***********************"); } //Change the heating controls based on the schedule if (heating) { //scheduled so turn on control.turnHeatingOn(); control.heatingOnSchedule = true; if (control.isHeatingBoostOn() && ((calendar.getTimeInMillis() > control.getHeatingBoostOffTime()) && (control.getHeatingBoostOffTime() > 0))) { //If boost is on but it is past the boost time turn off boost (but leave it scheduled on) control.toggleHeatingBoostStatus(); control.manual_desired_temp = false; } } else if (control.isHeatingBoostOn() && calendar.getTimeInMillis() > control.getHeatingBoostOffTime()) { //If boost is on but it is past the boost time turn off control.toggleHeatingBoostStatus(); control.heatingOnSchedule = false; control.manual_desired_temp = false; - } else { //no schedule or boost so turn off + } else if (control.isHeatingOn()) { //no schedule or boost so if on, turn off control.turnHeatingOff(); control.heatingOnSchedule = false; control.manual_desired_temp = false; } //Change the water controls based on the schedule if (water) { //scheduled so turn on control.turnWaterOn(); control.waterOnSchedule = true; if (control.isWaterBoostOn() && ((calendar.getTimeInMillis() > control.getWaterBoostOffTime()) && (control.getWaterBoostOffTime() > 0))) { //If boost is on but it is past the boost time turn off boost (but leave it scheduled on) control.toggleWaterBoostStatus(); } } else if (control.isWaterBoostOn() && calendar.getTimeInMillis() > control.getWaterBoostOffTime()) { //If boost is on but it is past the boost time turn off control.toggleWaterBoostStatus(); control.waterOnSchedule = false; - } else { //no schedule or boost so turn off + } else if (control.isWaterOn()) { //no schedule or boost so if on, turn off control.turnWaterOff(); control.waterOnSchedule = false; } try { Thread.sleep(20000); } catch (InterruptedException e) { break; } } System.out.println("Scheduler interrupted"); } }
false
true
public void run() { while (!Thread.interrupted()) { //Heating and water default to off Calendar calendar = Calendar.getInstance(); /** TimeZone z = calendar.getTimeZone(); int offset = z.getRawOffset(); if(z.inDaylightTime(new Date())){ offset = offset + z.getDSTSavings(); } int offsetHrs = offset / 1000 / 60 / 60; int offsetMins = offset / 1000 / 60 % 60; calendar.add(Calendar.HOUR_OF_DAY, (-offsetHrs)); calendar.add(Calendar.MINUTE, (-offsetMins)); /**/ boolean heating = false; boolean water = false; //Get the day and minute int day = calendar.get(Calendar.DAY_OF_WEEK); int minute = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE); ScheduleSource ss = new ScheduleSqlSource(); //Get the schedules for today Set<ScheduleObject> schedules = ss.getByDay(day); if (schedules == null) { System.out.println("No schedules today"); } else { System.out.println("Time: " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE)); System.out.println("WB: " + control.isWaterBoostOn() + ", WB Finish: " + control.getWaterBoostOffTime()); System.out.println("HB: " + control.isHeatingBoostOn() + ", HB Finish: " + control.getHeatingBoostOffTime()); System.out.println("Currently Desired Temp Set to: " + control.getdesired_temp()); //Loop through all of todays schedules for (ScheduleObject schedule : schedules) { if (schedule.getEnabled()) { //if enabled System.out.print("*"); System.out.print(schedule); //if in active period int timeOnMins = (schedule.getHourOn() * 60) + schedule.getMinuteOn(); int timeOffMins = (schedule.getHourOff() * 60) + schedule.getMinuteOff(); if (minute >= timeOnMins && minute < timeOffMins) { //Including starting minute, excluding ending minute System.out.print(" **ACTIVE**"); //If Boost is ON or desired_temp was manually changed do not overwrite boost desired_temp with scheduled if ((!control.isHeatingBoostOn()) && (!control.ismanual_desired_tempOn())) { System.out.println("Overwriting current desired_temp with scheduled"); control.setdesired_temp(schedule.getTempSet()); } //Only update the h/w status if they are false heating = (heating) ? heating : schedule.getHeatingOn(); water = (water) ? water : schedule.getWaterOn(); } System.out.println(); } else { System.out.print("-"); System.out.println(schedule); } } System.out.println("***********************"); } //Change the heating controls based on the schedule if (heating) { //scheduled so turn on control.turnHeatingOn(); control.heatingOnSchedule = true; if (control.isHeatingBoostOn() && ((calendar.getTimeInMillis() > control.getHeatingBoostOffTime()) && (control.getHeatingBoostOffTime() > 0))) { //If boost is on but it is past the boost time turn off boost (but leave it scheduled on) control.toggleHeatingBoostStatus(); control.manual_desired_temp = false; } } else if (control.isHeatingBoostOn() && calendar.getTimeInMillis() > control.getHeatingBoostOffTime()) { //If boost is on but it is past the boost time turn off control.toggleHeatingBoostStatus(); control.heatingOnSchedule = false; control.manual_desired_temp = false; } else { //no schedule or boost so turn off control.turnHeatingOff(); control.heatingOnSchedule = false; control.manual_desired_temp = false; } //Change the water controls based on the schedule if (water) { //scheduled so turn on control.turnWaterOn(); control.waterOnSchedule = true; if (control.isWaterBoostOn() && ((calendar.getTimeInMillis() > control.getWaterBoostOffTime()) && (control.getWaterBoostOffTime() > 0))) { //If boost is on but it is past the boost time turn off boost (but leave it scheduled on) control.toggleWaterBoostStatus(); } } else if (control.isWaterBoostOn() && calendar.getTimeInMillis() > control.getWaterBoostOffTime()) { //If boost is on but it is past the boost time turn off control.toggleWaterBoostStatus(); control.waterOnSchedule = false; } else { //no schedule or boost so turn off control.turnWaterOff(); control.waterOnSchedule = false; } try { Thread.sleep(20000); } catch (InterruptedException e) { break; } } System.out.println("Scheduler interrupted"); }
public void run() { while (!Thread.interrupted()) { //Heating and water default to off Calendar calendar = Calendar.getInstance(); /** TimeZone z = calendar.getTimeZone(); int offset = z.getRawOffset(); if(z.inDaylightTime(new Date())){ offset = offset + z.getDSTSavings(); } int offsetHrs = offset / 1000 / 60 / 60; int offsetMins = offset / 1000 / 60 % 60; calendar.add(Calendar.HOUR_OF_DAY, (-offsetHrs)); calendar.add(Calendar.MINUTE, (-offsetMins)); /**/ boolean heating = false; boolean water = false; //Get the day and minute int day = calendar.get(Calendar.DAY_OF_WEEK); int minute = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE); ScheduleSource ss = new ScheduleSqlSource(); //Get the schedules for today Set<ScheduleObject> schedules = ss.getByDay(day); if (schedules == null) { System.out.println("No schedules today"); } else { System.out.println("Time: " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE)); System.out.println("WB: " + control.isWaterBoostOn() + ", WB Finish: " + control.getWaterBoostOffTime()); System.out.println("HB: " + control.isHeatingBoostOn() + ", HB Finish: " + control.getHeatingBoostOffTime()); System.out.println("Currently Desired Temp Set to: " + control.getdesired_temp()); //Loop through all of todays schedules for (ScheduleObject schedule : schedules) { if (schedule.getEnabled()) { //if enabled System.out.print("*"); System.out.print(schedule); //if in active period int timeOnMins = (schedule.getHourOn() * 60) + schedule.getMinuteOn(); int timeOffMins = (schedule.getHourOff() * 60) + schedule.getMinuteOff(); if (minute >= timeOnMins && minute < timeOffMins) { //Including starting minute, excluding ending minute System.out.print(" **ACTIVE**"); //If Boost is ON or desired_temp was manually changed do not overwrite boost desired_temp with scheduled if ((!control.isHeatingBoostOn()) && (!control.ismanual_desired_tempOn())) { System.out.println("Overwriting current desired_temp with scheduled"); control.setdesired_temp(schedule.getTempSet()); } //Only update the h/w status if they are false heating = (heating) ? heating : schedule.getHeatingOn(); water = (water) ? water : schedule.getWaterOn(); } System.out.println(); } else { System.out.print("-"); System.out.println(schedule); } } System.out.println("***********************"); } //Change the heating controls based on the schedule if (heating) { //scheduled so turn on control.turnHeatingOn(); control.heatingOnSchedule = true; if (control.isHeatingBoostOn() && ((calendar.getTimeInMillis() > control.getHeatingBoostOffTime()) && (control.getHeatingBoostOffTime() > 0))) { //If boost is on but it is past the boost time turn off boost (but leave it scheduled on) control.toggleHeatingBoostStatus(); control.manual_desired_temp = false; } } else if (control.isHeatingBoostOn() && calendar.getTimeInMillis() > control.getHeatingBoostOffTime()) { //If boost is on but it is past the boost time turn off control.toggleHeatingBoostStatus(); control.heatingOnSchedule = false; control.manual_desired_temp = false; } else if (control.isHeatingOn()) { //no schedule or boost so if on, turn off control.turnHeatingOff(); control.heatingOnSchedule = false; control.manual_desired_temp = false; } //Change the water controls based on the schedule if (water) { //scheduled so turn on control.turnWaterOn(); control.waterOnSchedule = true; if (control.isWaterBoostOn() && ((calendar.getTimeInMillis() > control.getWaterBoostOffTime()) && (control.getWaterBoostOffTime() > 0))) { //If boost is on but it is past the boost time turn off boost (but leave it scheduled on) control.toggleWaterBoostStatus(); } } else if (control.isWaterBoostOn() && calendar.getTimeInMillis() > control.getWaterBoostOffTime()) { //If boost is on but it is past the boost time turn off control.toggleWaterBoostStatus(); control.waterOnSchedule = false; } else if (control.isWaterOn()) { //no schedule or boost so if on, turn off control.turnWaterOff(); control.waterOnSchedule = false; } try { Thread.sleep(20000); } catch (InterruptedException e) { break; } } System.out.println("Scheduler interrupted"); }
diff --git a/framework/test-src/play/cache/EhCacheImplTest.java b/framework/test-src/play/cache/EhCacheImplTest.java index f724c27a..89f94d17 100644 --- a/framework/test-src/play/cache/EhCacheImplTest.java +++ b/framework/test-src/play/cache/EhCacheImplTest.java @@ -1,32 +1,35 @@ package play.cache; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; public class EhCacheImplTest { @Test public void verifyThatTTLSurvivesIncrDecr() throws Exception { - final EhCacheImpl cache = EhCacheImpl.getInstance(); + EhCacheImpl cache = EhCacheImpl.getInstance(); + if (cache==null) { + cache = EhCacheImpl.newInstance(); + } cache.clear(); final String key = "EhCacheImplTest_verifyThatTTLSurvivesIncrDecr"; final int expiration = 1; cache.add(key, 1, expiration); Thread.sleep(100); cache.incr(key, 4); Thread.sleep(100); cache.decr(key, 3); Thread.sleep(950); assertThat(cache.get(key)).isEqualTo(2L); //no make sure it disappear after the 1 sec + 200 mils Thread.sleep(150); assertThat(cache.get(key)).isNull(); } }
true
true
public void verifyThatTTLSurvivesIncrDecr() throws Exception { final EhCacheImpl cache = EhCacheImpl.getInstance(); cache.clear(); final String key = "EhCacheImplTest_verifyThatTTLSurvivesIncrDecr"; final int expiration = 1; cache.add(key, 1, expiration); Thread.sleep(100); cache.incr(key, 4); Thread.sleep(100); cache.decr(key, 3); Thread.sleep(950); assertThat(cache.get(key)).isEqualTo(2L); //no make sure it disappear after the 1 sec + 200 mils Thread.sleep(150); assertThat(cache.get(key)).isNull(); }
public void verifyThatTTLSurvivesIncrDecr() throws Exception { EhCacheImpl cache = EhCacheImpl.getInstance(); if (cache==null) { cache = EhCacheImpl.newInstance(); } cache.clear(); final String key = "EhCacheImplTest_verifyThatTTLSurvivesIncrDecr"; final int expiration = 1; cache.add(key, 1, expiration); Thread.sleep(100); cache.incr(key, 4); Thread.sleep(100); cache.decr(key, 3); Thread.sleep(950); assertThat(cache.get(key)).isEqualTo(2L); //no make sure it disappear after the 1 sec + 200 mils Thread.sleep(150); assertThat(cache.get(key)).isNull(); }
diff --git a/src/test/java/org/abqjug/MultimapTest.java b/src/test/java/org/abqjug/MultimapTest.java index 0cc52cd..ebe2541 100644 --- a/src/test/java/org/abqjug/MultimapTest.java +++ b/src/test/java/org/abqjug/MultimapTest.java @@ -1,83 +1,83 @@ /** * Copyright 2010-2013 Daniel Hinojosa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.abqjug; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import org.testng.annotations.Test; import static org.fest.assertions.Assertions.assertThat; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Created by Daniel Hinojosa * User: Daniel Hinojosa * Date: 03 Mar 14, 2010, 2010 * Time: 3:20:24 PM * url: <a href="http://www.evolutionnext.com">http://www.evolutionnext.com</a> * email: <a href="mailto:[email protected]">[email protected]</a> * tel: 505.363.5832 */ public class MultimapTest { @Test(groups = "multimap") public void testMultiMap() { Multimap<String, Integer> superBowlMap = ArrayListMultimap.create(); superBowlMap.put("Dallas Cowboys", 1971); superBowlMap.put("Dallas Cowboys", 1992); superBowlMap.put("Dallas Cowboys", 1993); superBowlMap.put("Dallas Cowboys", 1995); superBowlMap.put("Dallas Cowboys", 1977); superBowlMap.put("Pittsburgh Steelers", 1975); - superBowlMap.put("Pittsburgh Steelers", 197); + superBowlMap.put("Pittsburgh Steelers", 1976); superBowlMap.put("Pittsburgh Steelers", 1979); superBowlMap.put("Pittsburgh Steelers", 1980); superBowlMap.put("Pittsburgh Steelers", 2006); superBowlMap.put("Pittsburgh Steelers", 2009); // assertEquals(superBowlMap.get("Dallas Cowboys").size(), 5); //// assertEquals(superBowlMap.get("Buffalo Bills").toString(), "[]"); // assertThat(superBowlMap.get("Dallas Cowboys")).contains(1971, 1992, 1993, 1993, 1995, 1977); superBowlMap.get("Dallas Cowboys").add(2013); assertThat(superBowlMap.get("Dallas Cowboys").size()).isEqualTo(6); assertThat(superBowlMap.get("Cleveland Browns").size()).isEqualTo(0); assertThat(superBowlMap.containsKey("Seattle Seahawks")).isFalse(); assertThat(superBowlMap.keySet()).hasSize(2); superBowlMap.get("Denver Broncos").add(1999); assertThat(superBowlMap.keySet()).hasSize(3); // ArrayListMultimap<Integer, String> newMap = // ArrayListMultimap.create(); // superBowlMap.put("Dallas Cowboys", 1975); // newMap.put(1984, "Oakland Raiders"); // Multimaps.invertFrom(superBowlMap, newMap); // assertTrue(newMap.keys().size() == 12); // superBowlMap.get("Seattle Seahawks"); // assertThat(superBowlMap.containsKey("Seattle Seahawks")).isFalse(); // assertThat(superBowlMap.get("Chicago Bears").size()).isEqualTo(0); // assertThat(superBowlMap.containsKey("Chicago Bears")).isFalse(); // // // //// assertThat(superBowlMap.get("Seattle Seahawks")).hasSize(1); //// assertThat(superBowlMap.containsKey("Seattle Seahawks")).isTrue(); // System.out.println(superBowlMap.keySet()); } }
true
true
public void testMultiMap() { Multimap<String, Integer> superBowlMap = ArrayListMultimap.create(); superBowlMap.put("Dallas Cowboys", 1971); superBowlMap.put("Dallas Cowboys", 1992); superBowlMap.put("Dallas Cowboys", 1993); superBowlMap.put("Dallas Cowboys", 1995); superBowlMap.put("Dallas Cowboys", 1977); superBowlMap.put("Pittsburgh Steelers", 1975); superBowlMap.put("Pittsburgh Steelers", 197); superBowlMap.put("Pittsburgh Steelers", 1979); superBowlMap.put("Pittsburgh Steelers", 1980); superBowlMap.put("Pittsburgh Steelers", 2006); superBowlMap.put("Pittsburgh Steelers", 2009); // assertEquals(superBowlMap.get("Dallas Cowboys").size(), 5); //// assertEquals(superBowlMap.get("Buffalo Bills").toString(), "[]"); // assertThat(superBowlMap.get("Dallas Cowboys")).contains(1971, 1992, 1993, 1993, 1995, 1977); superBowlMap.get("Dallas Cowboys").add(2013); assertThat(superBowlMap.get("Dallas Cowboys").size()).isEqualTo(6); assertThat(superBowlMap.get("Cleveland Browns").size()).isEqualTo(0); assertThat(superBowlMap.containsKey("Seattle Seahawks")).isFalse(); assertThat(superBowlMap.keySet()).hasSize(2); superBowlMap.get("Denver Broncos").add(1999); assertThat(superBowlMap.keySet()).hasSize(3); // ArrayListMultimap<Integer, String> newMap = // ArrayListMultimap.create(); // superBowlMap.put("Dallas Cowboys", 1975); // newMap.put(1984, "Oakland Raiders"); // Multimaps.invertFrom(superBowlMap, newMap); // assertTrue(newMap.keys().size() == 12); // superBowlMap.get("Seattle Seahawks"); // assertThat(superBowlMap.containsKey("Seattle Seahawks")).isFalse(); // assertThat(superBowlMap.get("Chicago Bears").size()).isEqualTo(0); // assertThat(superBowlMap.containsKey("Chicago Bears")).isFalse(); // // // //// assertThat(superBowlMap.get("Seattle Seahawks")).hasSize(1); //// assertThat(superBowlMap.containsKey("Seattle Seahawks")).isTrue(); // System.out.println(superBowlMap.keySet()); }
public void testMultiMap() { Multimap<String, Integer> superBowlMap = ArrayListMultimap.create(); superBowlMap.put("Dallas Cowboys", 1971); superBowlMap.put("Dallas Cowboys", 1992); superBowlMap.put("Dallas Cowboys", 1993); superBowlMap.put("Dallas Cowboys", 1995); superBowlMap.put("Dallas Cowboys", 1977); superBowlMap.put("Pittsburgh Steelers", 1975); superBowlMap.put("Pittsburgh Steelers", 1976); superBowlMap.put("Pittsburgh Steelers", 1979); superBowlMap.put("Pittsburgh Steelers", 1980); superBowlMap.put("Pittsburgh Steelers", 2006); superBowlMap.put("Pittsburgh Steelers", 2009); // assertEquals(superBowlMap.get("Dallas Cowboys").size(), 5); //// assertEquals(superBowlMap.get("Buffalo Bills").toString(), "[]"); // assertThat(superBowlMap.get("Dallas Cowboys")).contains(1971, 1992, 1993, 1993, 1995, 1977); superBowlMap.get("Dallas Cowboys").add(2013); assertThat(superBowlMap.get("Dallas Cowboys").size()).isEqualTo(6); assertThat(superBowlMap.get("Cleveland Browns").size()).isEqualTo(0); assertThat(superBowlMap.containsKey("Seattle Seahawks")).isFalse(); assertThat(superBowlMap.keySet()).hasSize(2); superBowlMap.get("Denver Broncos").add(1999); assertThat(superBowlMap.keySet()).hasSize(3); // ArrayListMultimap<Integer, String> newMap = // ArrayListMultimap.create(); // superBowlMap.put("Dallas Cowboys", 1975); // newMap.put(1984, "Oakland Raiders"); // Multimaps.invertFrom(superBowlMap, newMap); // assertTrue(newMap.keys().size() == 12); // superBowlMap.get("Seattle Seahawks"); // assertThat(superBowlMap.containsKey("Seattle Seahawks")).isFalse(); // assertThat(superBowlMap.get("Chicago Bears").size()).isEqualTo(0); // assertThat(superBowlMap.containsKey("Chicago Bears")).isFalse(); // // // //// assertThat(superBowlMap.get("Seattle Seahawks")).hasSize(1); //// assertThat(superBowlMap.containsKey("Seattle Seahawks")).isTrue(); // System.out.println(superBowlMap.keySet()); }